From 9d4f0b36c3cbfaab41d029cc9cba0e9865771c39 Mon Sep 17 00:00:00 2001 From: Marius Date: Tue, 17 Mar 2026 12:41:30 +0200 Subject: [PATCH] feat: add detailed implementation plan for PowerMonitor feature Made-with: Cursor --- docs/plans/2026-03-17-power-monitor-design.md | 1327 +++++++++++++++-- 1 file changed, 1183 insertions(+), 144 deletions(-) diff --git a/docs/plans/2026-03-17-power-monitor-design.md b/docs/plans/2026-03-17-power-monitor-design.md index bf85c45..24fce01 100644 --- a/docs/plans/2026-03-17-power-monitor-design.md +++ b/docs/plans/2026-03-17-power-monitor-design.md @@ -1,194 +1,1233 @@ -# Power Monitor — "Other" Power Usage & Cost Tracking +# Power Monitor Implementation Plan -## Problem +> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. -A P1 smart meter tracks total home power consumption in near real-time (~1-10s updates). Over 30 Sonoff and Zigbee devices each report individual power usage but with up to ~30 seconds of staleness. There is no visibility into what untracked devices are consuming, and no per-device or whole-home cost tracking integrated with NordPool electricity prices. +**Goal:** Track "other" (untracked) power usage and per-device/total/other electricity costs with NordPool price integration, exposed as MQTT entities in Home Assistant. -## Goals +**Architecture:** A new `PowerMonitor.Manager` project follows the existing NordPool.Manager pattern: an `Init` class schedules periodic polling, a discovery service auto-discovers HA power sensors, a calculation service computes "other" power with EMA smoothing, a cost service maintains 4-window cost accumulators per source, and an entity service manages MQTT entities. A `PowerMonitor.Models` project holds shared models. -- Calculate "other" (untracked) power usage: `total - sum(known devices)` -- Track electricity cost at three levels: total home, per device, and "other" -- Detect anomalies when untracked power exceeds a configurable threshold -- Expose everything as HA entities for dashboards and automations -- Auto-discover power sensors with manual re-discovery via HA button +**Tech Stack:** .NET 10, NetDaemon (v26.3.0), MQTT Entity Manager, xUnit + Moq + FluentAssertions -## Approach +--- -Periodic polling with exponential moving average smoothing. Every 15 seconds (configurable), read all power sensors, compute "other" power, apply smoothing, calculate costs, and push to HA entities. +### Task 1: Create project scaffolding and solution structure -## Architecture +**Files:** +- Create: `PowerMonitor.Models/PowerMonitor.Models.csproj` +- Create: `PowerMonitor.Manager/PowerMonitor.Manager.csproj` +- Create: `PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj` +- Modify: `HomeAssistantSDK.sln` +- Modify: `HomeAssistant.Server/HomeAssistant.Server.csproj` -### Project Structure +**Step 1: Create `PowerMonitor.Models/PowerMonitor.Models.csproj`** -``` -PowerMonitor.Manager/ -├── PowerMonitorInit.cs # [NetDaemonApp] orchestrator, schedules polling -├── PowerMonitorEntityService.cs # Creates/updates MQTT entities in HA -├── PowerSensorDiscoveryService.cs # Auto-discovers power sensors from HA -├── OtherPowerCalculationService.cs # total - sum(known) + smoothing -├── PowerCostCalculationService.cs # NordPool price integration, cost accumulation -├── Interface/ -│ ├── IPowerMonitorInit.cs -│ ├── IPowerMonitorEntityService.cs -│ ├── IPowerSensorDiscoveryService.cs -│ ├── IOtherPowerCalculationService.cs -│ └── IPowerCostCalculationService.cs -└── Models/ - ├── PowerCalculationResult.cs - ├── PowerUpdateContext.cs - ├── PowerSensorConfig.cs - ├── CostAccumulator.cs - └── Consts/ - └── PowerMonitorConsts.cs +```xml + -PowerMonitor.Models/ -├── PowerMonitorEntity.cs -└── PowerSensorInfo.cs + + net10.0 + enable + enable + PowerMonitor.Models + -PowerMonitor.Manager.Tests/ -├── OtherPowerCalculationServiceTests.cs -├── CostAccumulatorTests.cs -├── PowerSensorDiscoveryServiceTests.cs -├── PowerCostCalculationServiceTests.cs -└── PowerMonitorEntityServiceTests.cs + + + + + + + + + ``` -### Service Responsibilities +**Step 2: Create `PowerMonitor.Manager/PowerMonitor.Manager.csproj`** -| Service | Responsibility | -|---|---| -| `PowerMonitorInit` | NetDaemon app entry point. Runs initialization, schedules periodic polling, subscribes to re-discovery button. | -| `PowerSensorDiscoveryService` | Queries HA for all power sensors (`device_class: power`, `unit: W/kW`). Applies exclusion patterns. Identifies main meter vs device sensors. | -| `OtherPowerCalculationService` | Computes `other = total - sum(devices)`, clamps negatives to 0, applies exponential moving average smoothing. | -| `PowerCostCalculationService` | Maintains `CostAccumulator` instances per tracked source. Computes `cost = power_kW × price × (interval / 3600)`. Manages four accumulation windows. | -| `PowerMonitorEntityService` | Creates, updates, resets, and cleans up all MQTT entities in HA. Handles per-device entity lifecycle. | +```xml + -## Sensor Discovery + + net10.0 + enable + enable + PowerMonitorManager + -### Initial Discovery + + + <_Parameter1>PowerMonitor.Manager.Tests + + -Runs once at startup: -1. Query all HA entities with `device_class: power` and `unit_of_measurement: W` or `kW` -2. Identify main meter by configured `MainMeterEntityId` -3. Exclude sensors matching `ExcludedSensorPatterns` -4. Everything remaining is a tracked device sensor + + + + + -### Re-Discovery + + + -Triggered manually via `button.powermonitor_rediscover_sensors` in HA: -- Re-scans all power sensors -- Creates entities for newly discovered sensors -- Cleans up entities for removed sensors -- Updates the `sensor.powermonitor_status` discovered sensors list + +``` -### Configuration (`appsettings.json`) +**Step 3: Create `PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj`** -```json +```xml + + + + net10.0 + enable + enable + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + +``` + +**Step 4: Add all three projects to `HomeAssistantSDK.sln`** + +Run: `dotnet sln add PowerMonitor.Models/PowerMonitor.Models.csproj PowerMonitor.Manager/PowerMonitor.Manager.csproj PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj` + +**Step 5: Add project reference from `HomeAssistant.Server` to `PowerMonitor.Manager`** + +Add to `HomeAssistant.Server/HomeAssistant.Server.csproj` `` with project references: +```xml + + +``` + +**Step 6: Verify solution builds** + +Run: `dotnet build HomeAssistantSDK.sln` +Expected: Build succeeded with 0 errors + +**Step 7: Commit** + +``` +git add -A && git commit -m "feat: scaffold PowerMonitor projects and add to solution" +``` + +--- + +### Task 2: Create configuration model and constants + +**Files:** +- Create: `PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs` +- Create: `PowerMonitor.Manager/Models/PowerMonitorOptions.cs` +- Modify: `HomeAssistant.Server/appsettings.json` + +**Step 1: Create `PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs`** + +```csharp +namespace PowerMonitorManager.Models.Consts; + +public static class PowerMonitorConsts { - "PowerMonitor": { + public const int DefaultPollIntervalSeconds = 15; + public const int DefaultSmoothingWindowSize = 10; + public const double DefaultAnomalyThresholdWatts = 500.0; + public const int SecondsPerHour = 3600; + public const double WattsPerKilowatt = 1000.0; + public const string PowerDeviceClass = "power"; + public const string WattUnit = "W"; + public const string KilowattUnit = "kW"; + public const string EurUnit = "EUR"; + public const string MonetaryDeviceClass = "monetary"; + public const string TotalStateClass = "total"; + public const string MeasurementStateClass = "measurement"; + + public const int MainMeterMaxConsecutiveFailures = 5; + + public const int MinutesPerQuarterHour = 15; + public const int MinutesPerHour = 60; +} +``` + +**Step 2: Create `PowerMonitor.Manager/Models/PowerMonitorOptions.cs`** + +```csharp +namespace PowerMonitorManager.Models; + +public sealed class PowerMonitorOptions +{ + public const string SectionName = "PowerMonitor"; + + public string MainMeterEntityId { get; set; } = string.Empty; + public int PollIntervalSeconds { get; set; } = Consts.PowerMonitorConsts.DefaultPollIntervalSeconds; + public int SmoothingWindowSize { get; set; } = Consts.PowerMonitorConsts.DefaultSmoothingWindowSize; + public double AnomalyThresholdWatts { get; set; } = Consts.PowerMonitorConsts.DefaultAnomalyThresholdWatts; + public string[] ExcludedSensorPatterns { get; set; } = []; +} +``` + +**Step 3: Add `PowerMonitor` section to `HomeAssistant.Server/appsettings.json`** + +Add after the `CodeGeneration` section: +```json +"PowerMonitor": { "MainMeterEntityId": "sensor.p1_meter_power", "PollIntervalSeconds": 15, "SmoothingWindowSize": 10, "AnomalyThresholdWatts": 500, "ExcludedSensorPatterns": [ - "sensor.nordpool_*", - "sensor.powermonitor_*" + "sensor.nordpool_*", + "sensor.powermonitor_*" ] - } } ``` -| Setting | Default | Purpose | -|---|---|---| -| `MainMeterEntityId` | — | P1 meter entity ID (required) | -| `PollIntervalSeconds` | 15 | Poll interval in seconds | -| `SmoothingWindowSize` | 10 | EMA window size (10 × 15s = 2.5 min) | -| `AnomalyThresholdWatts` | 500 | Threshold for anomaly binary sensor | -| `ExcludedSensorPatterns` | `[]` | Glob patterns for sensors to ignore | +**Step 4: Verify build** -## Calculation & Data Flow +Run: `dotnet build PowerMonitor.Manager/PowerMonitor.Manager.csproj` +Expected: Build succeeded -### Poll Cycle (every 15 seconds) +**Step 5: Commit** -1. Read P1 main meter → total power (W) -2. Read all discovered device sensors → individual power readings -3. Compute raw other: `total - sum(devices)`, clamp to 0 -4. Apply EMA smoothing: `smoothed = α × raw + (1 - α) × previous`, where `α = 2 / (windowSize + 1)` -5. Get current NordPool price from `INordPoolPriceService` -6. For each source (total, each device, other): `cost_increment = power_kW × price × (interval_s / 3600)` -7. Add increment to all four accumulation buckets -8. At window boundaries, store completed value as `previous_*` and reset -9. Push all values to HA entities via MQTT +``` +git add -A && git commit -m "feat: add PowerMonitor configuration model and constants" +``` -### Cost Accumulation Windows +--- -| Window | Resets At | Purpose | -|---|---|---| -| 15 min | :00, :15, :30, :45 | Granular recent cost | -| 1 hour | Top of each hour | Short-term trends | -| 1 day | Midnight | Daily cost tracking | -| 1 month | 1st of month, midnight | Billing cycle tracking | +### Task 3: Create shared models -### Edge Cases +**Files:** +- Create: `PowerMonitor.Models/PowerMonitorEntity.cs` +- Create: `PowerMonitor.Models/PowerSensorInfo.cs` +- Create: `PowerMonitor.Manager/Models/PowerCalculationResult.cs` +- Create: `PowerMonitor.Manager/Models/PowerUpdateContext.cs` +- Create: `PowerMonitor.Manager/Models/CostAccumulator.cs` +- Create: `PowerMonitor.Manager/Models/CostSnapshot.cs` -| Condition | Behavior | -|---|---| -| Main meter `unavailable` | Skip cycle, log warning, increment circuit breaker counter | -| 5+ consecutive main meter failures | Set status to `"warning"` with reason, resume when available | -| Device sensor `unavailable` | Treat as 0W, add to `degraded_sensors` list in status entity | -| Negative "other" (devices > total) | Clamp to 0, set `data_quality: "device_sum_exceeds_total"` | -| NordPool price unavailable | Use last known price, set `price_source: "stale"` | -| Mid-window restart | Buckets start at 0, `partial_window: true` until first full window | +**Step 1: Create `PowerMonitor.Models/PowerMonitorEntity.cs`** -## HA Entities +Follows same pattern as `NordPool.Models/NordPoolEntities.cs`: -### System-Level Entities +```csharp +using HomeAssistant.Models; +using NetDaemon.Extensions.MqttEntityManager; -| Entity ID | Type | State | Key Attributes | -|---|---|---|---| -| `sensor.powermonitor_total_power` | sensor | Total W | `unit: W`, `device_class: power` | -| `sensor.powermonitor_total_cost_15min` | sensor | EUR | `device_class: monetary`, `previous_15min` | -| `sensor.powermonitor_total_cost_1h` | sensor | EUR | `device_class: monetary`, `previous_1h` | -| `sensor.powermonitor_total_cost_daily` | sensor | EUR | `device_class: monetary`, `previous_daily` | -| `sensor.powermonitor_total_cost_monthly` | sensor | EUR | `device_class: monetary`, `previous_monthly` | -| `sensor.powermonitor_other_power` | sensor | Smoothed W | `raw_power`, `smoothed_power`, `data_quality` | -| `sensor.powermonitor_other_cost_15min` | sensor | EUR | Same pattern as total | -| `sensor.powermonitor_other_cost_1h` | sensor | EUR | | -| `sensor.powermonitor_other_cost_daily` | sensor | EUR | | -| `sensor.powermonitor_other_cost_monthly` | sensor | EUR | | -| `binary_sensor.powermonitor_anomaly` | binary_sensor | on/off | `smoothed_watts`, `threshold`, `duration_above` | -| `sensor.powermonitor_status` | sensor | ok/warning | `tracked_sensors_count`, `last_poll`, `discovered_sensors`, `degraded_sensors` | -| `button.powermonitor_rediscover_sensors` | button | — | Triggers re-discovery | +namespace PowerMonitor.Models; -### Per-Device Entities (auto-generated) +public class PowerMonitorEntity : EntityCreateModel +{ + public string Domain { get; set; } + public string Identifier { get; set; } + public string Name { get; set; } -For each discovered sensor (e.g., `sonoff_1002230e32`): + public PowerMonitorEntity(string domain, string identifier, string name) + { + Domain = domain; + Identifier = identifier; + EntityId = $"{Domain}.{Identifier}"; + Name = string.IsNullOrWhiteSpace(name) ? identifier : name; -| Entity ID | Type | State | -|---|---|---| -| `sensor.powermonitor__cost_15min` | sensor | EUR | -| `sensor.powermonitor__cost_1h` | sensor | EUR | -| `sensor.powermonitor__cost_daily` | sensor | EUR | -| `sensor.powermonitor__cost_monthly` | sensor | EUR | + Options = new EntityCreationOptions + { + UniqueId = EntityId, + Name = Name + }; + } +} +``` -All cost entities share: `unit_of_measurement: EUR`, `device_class: monetary`, `state_class: total`, `partial_window`, `price_source`, `last_updated`. +**Step 2: Create `PowerMonitor.Models/PowerSensorInfo.cs`** -## Error Handling +```csharp +namespace PowerMonitor.Models; -- All entity writes use safe wrappers (try/catch per write, log and continue) -- Circuit breaker on main meter: 5 consecutive failures → warning state -- Individual device failures don't block the poll cycle -- Thread safety via `ConcurrentDictionary` for cost accumulators -- All HA entity writes parallelized via `Task.WhenAll` +public sealed class PowerSensorInfo +{ + public required string EntityId { get; init; } + public required string FriendlyName { get; init; } + public required string DeviceName { get; init; } + public string UnitOfMeasurement { get; init; } = "W"; +} +``` -## Testing +**Step 3: Create `PowerMonitor.Manager/Models/PowerCalculationResult.cs`** -| Test Class | Coverage | -|---|---| -| `OtherPowerCalculationServiceTests` | Raw calculation, EMA smoothing, negative clamping, edge cases | -| `CostAccumulatorTests` | Window resets (15min, 1h, daily, monthly), partial windows, thread safety | -| `PowerSensorDiscoveryServiceTests` | Pattern matching, exclusion filters, re-discovery, new/removed sensors | -| `PowerCostCalculationServiceTests` | NordPool integration, stale price fallback, per-device cost | -| `PowerMonitorEntityServiceTests` | Entity creation, update, cleanup, per-device lifecycle | +```csharp +namespace PowerMonitorManager.Models; -All tests use xUnit, Moq, and FluentAssertions. +public sealed class PowerCalculationResult +{ + public double TotalPowerWatts { get; init; } + public double KnownDevicesSumWatts { get; init; } + public double RawOtherPowerWatts { get; init; } + public double SmoothedOtherPowerWatts { get; init; } + public string DataQuality { get; init; } = "ok"; + public IReadOnlyDictionary DevicePowerReadings { get; init; } = new Dictionary(); +} +``` + +**Step 4: Create `PowerMonitor.Manager/Models/PowerUpdateContext.cs`** + +```csharp +namespace PowerMonitorManager.Models; + +public sealed class PowerUpdateContext +{ + public required PowerCalculationResult Calculation { get; init; } + public required double CurrentNordPoolPrice { get; init; } + public required string PriceUnit { get; init; } + public required string PriceSource { get; init; } + public required IReadOnlyDictionary DeviceCosts { get; init; } + public required CostSnapshot TotalCost { get; init; } + public required CostSnapshot OtherCost { get; init; } + public required bool IsAnomaly { get; init; } + public required TimeSpan AnomalyDuration { get; init; } + public required double AnomalyThresholdWatts { get; init; } + public required int TrackedSensorCount { get; init; } + public required IReadOnlyList DegradedSensors { get; init; } + public required string SystemStatus { get; init; } +} +``` + +**Step 5: Create `PowerMonitor.Manager/Models/CostSnapshot.cs`** + +```csharp +namespace PowerMonitorManager.Models; + +public sealed class CostSnapshot +{ + public double Cost15Min { get; init; } + public double Cost1Hour { get; init; } + public double CostDaily { get; init; } + public double CostMonthly { get; init; } + public double Previous15Min { get; init; } + public double Previous1Hour { get; init; } + public double PreviousDaily { get; init; } + public double PreviousMonthly { get; init; } + public bool PartialWindow { get; init; } +} +``` + +**Step 6: Create `PowerMonitor.Manager/Models/CostAccumulator.cs`** + +This is the core cost tracking state machine. Thread-safe via `lock`. + +```csharp +namespace PowerMonitorManager.Models; + +public sealed class CostAccumulator +{ + private readonly object _lock = new(); + + private double _cost15Min; + private double _cost1Hour; + private double _costDaily; + private double _costMonthly; + + private double _previous15Min; + private double _previous1Hour; + private double _previousDaily; + private double _previousMonthly; + + private DateTime _last15MinReset; + private DateTime _last1HourReset; + private DateTime _lastDailyReset; + private DateTime _lastMonthlyReset; + + private bool _partialWindow = true; + + public CostAccumulator(DateTime now) + { + _last15MinReset = now; + _last1HourReset = now; + _lastDailyReset = now; + _lastMonthlyReset = now; + } + + public void AddCost(double costIncrement, DateTime now) + { + lock (_lock) + { + CheckAndResetWindows(now); + + _cost15Min += costIncrement; + _cost1Hour += costIncrement; + _costDaily += costIncrement; + _costMonthly += costIncrement; + } + } + + public CostSnapshot GetSnapshot() + { + lock (_lock) + { + return new CostSnapshot + { + Cost15Min = _cost15Min, + Cost1Hour = _cost1Hour, + CostDaily = _costDaily, + CostMonthly = _costMonthly, + Previous15Min = _previous15Min, + Previous1Hour = _previous1Hour, + PreviousDaily = _previousDaily, + PreviousMonthly = _previousMonthly, + PartialWindow = _partialWindow + }; + } + } + + private void CheckAndResetWindows(DateTime now) + { + if (IsNew15MinWindow(now, _last15MinReset)) + { + _previous15Min = _cost15Min; + _cost15Min = 0; + _last15MinReset = now; + _partialWindow = false; + } + + if (IsNewHourWindow(now, _last1HourReset)) + { + _previous1Hour = _cost1Hour; + _cost1Hour = 0; + _last1HourReset = now; + } + + if (IsNewDayWindow(now, _lastDailyReset)) + { + _previousDaily = _costDaily; + _costDaily = 0; + _lastDailyReset = now; + } + + if (IsNewMonthWindow(now, _lastMonthlyReset)) + { + _previousMonthly = _costMonthly; + _costMonthly = 0; + _lastMonthlyReset = now; + } + } + + internal static bool IsNew15MinWindow(DateTime now, DateTime lastReset) + { + var currentSlot = now.Minute / 15; + var lastSlot = lastReset.Minute / 15; + return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot; + } + + internal static bool IsNewHourWindow(DateTime now, DateTime lastReset) + { + return now.Date != lastReset.Date || now.Hour != lastReset.Hour; + } + + internal static bool IsNewDayWindow(DateTime now, DateTime lastReset) + { + return now.Date != lastReset.Date; + } + + internal static bool IsNewMonthWindow(DateTime now, DateTime lastReset) + { + return now.Year != lastReset.Year || now.Month != lastReset.Month; + } +} +``` + +**Step 7: Verify build** + +Run: `dotnet build PowerMonitor.Manager/PowerMonitor.Manager.csproj` +Expected: Build succeeded + +**Step 8: Commit** + +``` +git add -A && git commit -m "feat: add PowerMonitor shared models, CostAccumulator, and entity types" +``` + +--- + +### Task 4: CostAccumulator tests (TDD) + +**Files:** +- Create: `PowerMonitor.Manager.Tests/CostAccumulatorTests.cs` + +**Step 1: Write tests** + +```csharp +using FluentAssertions; +using PowerMonitorManager.Models; + +namespace PowerMonitor.Manager.Tests; + +public class CostAccumulatorTests +{ + #region AddCost and GetSnapshot + + [Fact] + public void GetSnapshot_WhenNew_ShouldReturnZeroCosts() + { + var sut = new CostAccumulator(new DateTime(2026, 3, 17, 10, 0, 0)); + + var snapshot = sut.GetSnapshot(); + + snapshot.Cost15Min.Should().Be(0); + snapshot.Cost1Hour.Should().Be(0); + snapshot.CostDaily.Should().Be(0); + snapshot.CostMonthly.Should().Be(0); + snapshot.PartialWindow.Should().BeTrue(); + } + + [Fact] + public void AddCost_ShouldAccumulateInAllWindows() + { + var now = new DateTime(2026, 3, 17, 10, 0, 0); + var sut = new CostAccumulator(now); + + sut.AddCost(0.05, now.AddSeconds(15)); + sut.AddCost(0.03, now.AddSeconds(30)); + + var snapshot = sut.GetSnapshot(); + snapshot.Cost15Min.Should().BeApproximately(0.08, 0.0001); + snapshot.Cost1Hour.Should().BeApproximately(0.08, 0.0001); + snapshot.CostDaily.Should().BeApproximately(0.08, 0.0001); + snapshot.CostMonthly.Should().BeApproximately(0.08, 0.0001); + } + + #endregion + + #region 15-minute window resets + + [Fact] + public void AddCost_When15MinWindowCrosses_ShouldResetAndStorePrevious() + { + var now = new DateTime(2026, 3, 17, 10, 14, 0); + var sut = new CostAccumulator(now); + sut.AddCost(0.10, now); + + sut.AddCost(0.02, new DateTime(2026, 3, 17, 10, 15, 0)); + + var snapshot = sut.GetSnapshot(); + snapshot.Cost15Min.Should().BeApproximately(0.02, 0.0001); + snapshot.Previous15Min.Should().BeApproximately(0.10, 0.0001); + snapshot.PartialWindow.Should().BeFalse(); + } + + #endregion + + #region Hourly window resets + + [Fact] + public void AddCost_WhenHourWindowCrosses_ShouldResetAndStorePrevious() + { + var now = new DateTime(2026, 3, 17, 10, 59, 0); + var sut = new CostAccumulator(now); + sut.AddCost(0.50, now); + + sut.AddCost(0.01, new DateTime(2026, 3, 17, 11, 0, 0)); + + var snapshot = sut.GetSnapshot(); + snapshot.Cost1Hour.Should().BeApproximately(0.01, 0.0001); + snapshot.Previous1Hour.Should().BeApproximately(0.50, 0.0001); + } + + #endregion + + #region Daily window resets + + [Fact] + public void AddCost_WhenDayChanges_ShouldResetDailyAndStorePrevious() + { + var now = new DateTime(2026, 3, 17, 23, 59, 0); + var sut = new CostAccumulator(now); + sut.AddCost(5.00, now); + + sut.AddCost(0.01, new DateTime(2026, 3, 18, 0, 0, 0)); + + var snapshot = sut.GetSnapshot(); + snapshot.CostDaily.Should().BeApproximately(0.01, 0.0001); + snapshot.PreviousDaily.Should().BeApproximately(5.00, 0.0001); + } + + #endregion + + #region Monthly window resets + + [Fact] + public void AddCost_WhenMonthChanges_ShouldResetMonthlyAndStorePrevious() + { + var now = new DateTime(2026, 3, 31, 23, 59, 0); + var sut = new CostAccumulator(now); + sut.AddCost(100.00, now); + + sut.AddCost(0.01, new DateTime(2026, 4, 1, 0, 0, 0)); + + var snapshot = sut.GetSnapshot(); + snapshot.CostMonthly.Should().BeApproximately(0.01, 0.0001); + snapshot.PreviousMonthly.Should().BeApproximately(100.00, 0.0001); + } + + #endregion + + #region Window boundary detection (static methods) + + [Theory] + [InlineData(10, 0, 10, 14, false)] + [InlineData(10, 0, 10, 15, true)] + [InlineData(10, 14, 10, 15, true)] + [InlineData(10, 29, 10, 30, true)] + [InlineData(10, 44, 10, 45, true)] + [InlineData(10, 45, 10, 59, false)] + [InlineData(10, 45, 11, 0, true)] + public void IsNew15MinWindow_ShouldDetectBoundary(int lastHour, int lastMin, int nowHour, int nowMin, bool expected) + { + var lastReset = new DateTime(2026, 3, 17, lastHour, lastMin, 0); + var now = new DateTime(2026, 3, 17, nowHour, nowMin, 0); + + CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected); + } + + [Theory] + [InlineData(10, 10, false)] + [InlineData(10, 11, true)] + [InlineData(23, 0, true)] + public void IsNewHourWindow_ShouldDetectBoundary(int lastHour, int nowHour, bool expected) + { + var lastReset = new DateTime(2026, 3, 17, lastHour, 0, 0); + var now = new DateTime(2026, 3, 17, nowHour, 0, 0); + + CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected); + } + + [Theory] + [InlineData(17, 17, false)] + [InlineData(17, 18, true)] + public void IsNewDayWindow_ShouldDetectBoundary(int lastDay, int nowDay, bool expected) + { + var lastReset = new DateTime(2026, 3, lastDay, 0, 0, 0); + var now = new DateTime(2026, 3, nowDay, 0, 0, 0); + + CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected); + } + + [Theory] + [InlineData(3, 3, false)] + [InlineData(3, 4, true)] + [InlineData(12, 1, true)] + public void IsNewMonthWindow_ShouldDetectBoundary(int lastMonth, int nowMonth, bool expected) + { + var lastReset = new DateTime(2026, lastMonth, 1, 0, 0, 0); + var now = new DateTime(2026, nowMonth, 1, 0, 0, 0); + + CostAccumulator.IsNewMonthWindow(now, lastReset).Should().Be(expected); + } + + #endregion + + #region Thread safety + + [Fact] + public void AddCost_ConcurrentAccess_ShouldNotLoseData() + { + var now = new DateTime(2026, 3, 17, 10, 0, 0); + var sut = new CostAccumulator(now); + const double incrementPerCall = 0.001; + const int callsPerThread = 1000; + const int threadCount = 10; + + var tasks = Enumerable.Range(0, threadCount) + .Select(_ => Task.Run(() => + { + for (var i = 0; i < callsPerThread; i++) + { + sut.AddCost(incrementPerCall, now.AddSeconds(1)); + } + })) + .ToArray(); + + Task.WaitAll(tasks); + + var snapshot = sut.GetSnapshot(); + var expected = incrementPerCall * callsPerThread * threadCount; + snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001); + } + + #endregion +} +``` + +**Step 2: Run tests to verify they pass** + +Run: `dotnet test PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj --filter "FullyQualifiedName~CostAccumulatorTests" -v normal` +Expected: All tests pass + +**Step 3: Commit** + +``` +git add -A && git commit -m "test: add CostAccumulator unit tests for all window boundaries and thread safety" +``` + +--- + +### Task 5: OtherPowerCalculationService (TDD) + +**Files:** +- Create: `PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs` +- Create: `PowerMonitor.Manager/OtherPowerCalculationService.cs` +- Create: `PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs` + +**Step 1: Create interface `PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs`** + +```csharp +using PowerMonitorManager.Models; + +namespace PowerMonitorManager.Interface; + +public interface IOtherPowerCalculationService +{ + PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary deviceReadings); + void Reset(); +} +``` + +**Step 2: Write failing tests `PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs`** + +```csharp +using FluentAssertions; +using Microsoft.Extensions.Options; +using PowerMonitorManager; +using PowerMonitorManager.Models; + +namespace PowerMonitor.Manager.Tests; + +public class OtherPowerCalculationServiceTests +{ + private static OtherPowerCalculationService CreateSut(int smoothingWindowSize = 10) + { + var options = Options.Create(new PowerMonitorOptions + { + SmoothingWindowSize = smoothingWindowSize + }); + return new OtherPowerCalculationService(options); + } + + #region Basic calculation + + [Fact] + public void Calculate_ShouldReturnOtherAsTotalMinusDevices() + { + var sut = CreateSut(smoothingWindowSize: 1); + var devices = new Dictionary + { + ["sensor.device_a_power"] = 500, + ["sensor.device_b_power"] = 300 + }; + + var result = sut.Calculate(1000, devices); + + result.TotalPowerWatts.Should().Be(1000); + result.KnownDevicesSumWatts.Should().Be(800); + result.RawOtherPowerWatts.Should().Be(200); + result.DataQuality.Should().Be("ok"); + } + + [Fact] + public void Calculate_WhenDevicesSumExceedsTotal_ShouldClampToZero() + { + var sut = CreateSut(smoothingWindowSize: 1); + var devices = new Dictionary + { + ["sensor.device_a_power"] = 800, + ["sensor.device_b_power"] = 500 + }; + + var result = sut.Calculate(1000, devices); + + result.RawOtherPowerWatts.Should().Be(0); + result.SmoothedOtherPowerWatts.Should().Be(0); + result.DataQuality.Should().Be("device_sum_exceeds_total"); + } + + [Fact] + public void Calculate_WithNoDevices_ShouldReturnTotalAsOther() + { + var sut = CreateSut(smoothingWindowSize: 1); + var devices = new Dictionary(); + + var result = sut.Calculate(1500, devices); + + result.RawOtherPowerWatts.Should().Be(1500); + result.KnownDevicesSumWatts.Should().Be(0); + } + + [Fact] + public void Calculate_ShouldIncludeAllDeviceReadingsInResult() + { + var sut = CreateSut(smoothingWindowSize: 1); + var devices = new Dictionary + { + ["sensor.a"] = 100, + ["sensor.b"] = 200 + }; + + var result = sut.Calculate(500, devices); + + result.DevicePowerReadings.Should().HaveCount(2); + result.DevicePowerReadings["sensor.a"].Should().Be(100); + result.DevicePowerReadings["sensor.b"].Should().Be(200); + } + + #endregion + + #region EMA smoothing + + [Fact] + public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage() + { + var sut = CreateSut(smoothingWindowSize: 4); + var devices = new Dictionary(); + + var result1 = sut.Calculate(1000, devices); + result1.SmoothedOtherPowerWatts.Should().BeApproximately(1000, 0.1); + + var result2 = sut.Calculate(500, devices); + result2.SmoothedOtherPowerWatts.Should().BeLessThan(1000); + result2.SmoothedOtherPowerWatts.Should().BeGreaterThan(500); + } + + [Fact] + public void Calculate_MultipleCallsWithSameValue_ShouldConverge() + { + var sut = CreateSut(smoothingWindowSize: 5); + var devices = new Dictionary(); + + PowerCalculationResult? result = null; + for (var i = 0; i < 50; i++) + { + result = sut.Calculate(300, devices); + } + + result!.SmoothedOtherPowerWatts.Should().BeApproximately(300, 0.1); + } + + #endregion + + #region Reset + + [Fact] + public void Reset_ShouldClearSmoothedState() + { + var sut = CreateSut(smoothingWindowSize: 10); + var devices = new Dictionary(); + sut.Calculate(1000, devices); + sut.Calculate(1000, devices); + + sut.Reset(); + var result = sut.Calculate(100, devices); + + result.SmoothedOtherPowerWatts.Should().BeApproximately(100, 0.1); + } + + #endregion +} +``` + +**Step 3: Run tests to verify they fail** + +Run: `dotnet test PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj --filter "FullyQualifiedName~OtherPowerCalculationServiceTests" -v normal` +Expected: FAIL — `OtherPowerCalculationService` doesn't exist yet + +**Step 4: Implement `PowerMonitor.Manager/OtherPowerCalculationService.cs`** + +```csharp +using Microsoft.Extensions.Options; +using PowerMonitorManager.Interface; +using PowerMonitorManager.Models; + +namespace PowerMonitorManager; + +public sealed class OtherPowerCalculationService : IOtherPowerCalculationService +{ + private readonly double _alpha; + private double? _previousSmoothed; + private readonly object _lock = new(); + + public OtherPowerCalculationService(IOptions options) + { + var windowSize = options.Value.SmoothingWindowSize; + _alpha = 2.0 / (windowSize + 1); + } + + public PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary deviceReadings) + { + var knownSum = deviceReadings.Values.Sum(); + var rawOther = totalPowerWatts - knownSum; + var dataQuality = "ok"; + + if (rawOther < 0) + { + rawOther = 0; + dataQuality = "device_sum_exceeds_total"; + } + + double smoothed; + lock (_lock) + { + smoothed = _previousSmoothed.HasValue + ? (_alpha * rawOther) + ((1 - _alpha) * _previousSmoothed.Value) + : rawOther; + _previousSmoothed = smoothed; + } + + return new PowerCalculationResult + { + TotalPowerWatts = totalPowerWatts, + KnownDevicesSumWatts = knownSum, + RawOtherPowerWatts = rawOther, + SmoothedOtherPowerWatts = smoothed, + DataQuality = dataQuality, + DevicePowerReadings = new Dictionary(deviceReadings) + }; + } + + public void Reset() + { + lock (_lock) + { + _previousSmoothed = null; + } + } +} +``` + +**Step 5: Run tests to verify they pass** + +Run: `dotnet test PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj --filter "FullyQualifiedName~OtherPowerCalculationServiceTests" -v normal` +Expected: All tests pass + +**Step 6: Commit** + +``` +git add -A && git commit -m "feat: add OtherPowerCalculationService with EMA smoothing and TDD tests" +``` + +--- + +### Task 6: PowerSensorDiscoveryService (TDD) + +**Files:** +- Create: `PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs` +- Create: `PowerMonitor.Manager/PowerSensorDiscoveryService.cs` +- Create: `PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs` + +**Step 1: Create interface `PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs`** + +```csharp +using PowerMonitor.Models; + +namespace PowerMonitorManager.Interface; + +public interface IPowerSensorDiscoveryService +{ + IReadOnlyList DiscoverDeviceSensors(); + IReadOnlyList CurrentDeviceSensors { get; } +} +``` + +**Step 2: Write failing tests `PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs`** + +Tests should mock `IHaContext` to return entities with `device_class: power` and test: +- Discovers sensors with `device_class == "power"` and unit `W` or `kW` +- Excludes the main meter entity +- Applies exclusion patterns (glob matching) +- Excludes sensors matching `sensor.nordpool_*` and `sensor.powermonitor_*` +- Returns empty list when no power sensors exist +- Re-discovery replaces the previous sensor list + +Use NetDaemon's `IHaContext.GetAllEntities()` to query entities. Mock the return to include a mix of power and non-power sensors. + +**Step 3: Implement `PowerMonitor.Manager/PowerSensorDiscoveryService.cs`** + +Query `IHaContext.GetAllEntities()`, filter by `device_class == "power"` and unit `W`/`kW`, apply exclusion patterns using simple glob matching (where `*` matches any characters), exclude the configured `MainMeterEntityId`. + +Store the result in a `IReadOnlyList` property. Re-discovery overwrites this list. + +**Step 4: Run tests, verify pass** + +Run: `dotnet test PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj --filter "FullyQualifiedName~PowerSensorDiscoveryServiceTests" -v normal` +Expected: All tests pass + +**Step 5: Commit** + +``` +git add -A && git commit -m "feat: add PowerSensorDiscoveryService with auto-discovery and exclusion patterns" +``` + +--- + +### Task 7: PowerCostCalculationService (TDD) + +**Files:** +- Create: `PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs` +- Create: `PowerMonitor.Manager/PowerCostCalculationService.cs` +- Create: `PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs` + +**Step 1: Create interface `PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs`** + +```csharp +using PowerMonitorManager.Models; + +namespace PowerMonitorManager.Interface; + +public interface IPowerCostCalculationService +{ + void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now); + CostSnapshot GetTotalCostSnapshot(); + CostSnapshot GetOtherCostSnapshot(); + CostSnapshot GetDeviceCostSnapshot(string entityId); + IReadOnlyDictionary GetAllDeviceCostSnapshots(); + double LastKnownPrice { get; } + string PriceSource { get; } + void SetPrice(double price); +} +``` + +**Step 2: Write failing tests** + +Test cases: +- `RecordCosts` with valid price creates cost increments for total, other, and each device +- Cost formula: `power_kW × price × (interval_s / 3600)` — verify exact values +- When price is 0, `SetPrice` is called with fallback → `PriceSource` becomes `"stale"` +- `GetDeviceCostSnapshot` returns correct snapshot for a specific device +- `GetAllDeviceCostSnapshots` returns all tracked devices +- New devices appearing in `PowerCalculationResult.DevicePowerReadings` get accumulators created automatically +- Thread safety: concurrent `RecordCosts` calls don't lose data + +**Step 3: Implement `PowerCostCalculationService`** + +Uses `ConcurrentDictionary` keyed by entity ID. Three fixed accumulators for "total", "other", plus dynamic ones per device. Computes cost increments as: +``` +costIncrement = (powerWatts / 1000.0) × nordPoolPrice × (pollIntervalSeconds / 3600.0) +``` + +**Step 4: Run tests, verify pass** + +Run: `dotnet test PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj --filter "FullyQualifiedName~PowerCostCalculationServiceTests" -v normal` +Expected: All tests pass + +**Step 5: Commit** + +``` +git add -A && git commit -m "feat: add PowerCostCalculationService with per-device cost accumulators" +``` + +--- + +### Task 8: PowerMonitorEntityService + +**Files:** +- Create: `PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs` +- Create: `PowerMonitor.Manager/PowerMonitorEntityService.cs` +- Create: `PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs` + +**Step 1: Create interface `PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs`** + +```csharp +using PowerMonitor.Models; +using PowerMonitorManager.Models; + +namespace PowerMonitorManager.Interface; + +public interface IPowerMonitorEntityService +{ + Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default); + Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, CancellationToken cancellationToken = default); + Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default); + Task ResetEntitiesAsync(CancellationToken cancellationToken = default); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); + Task CleanupDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, CancellationToken cancellationToken = default); +} +``` + +**Step 2: Write tests** + +Follow exact patterns from `NordPoolEntityServiceTests`: +- `CreateSystemEntitiesAsync` creates all 13 system-level entities +- `CreateDeviceEntitiesAsync` creates 4 cost entities per discovered device +- `UpdateEntitiesAsync` sets state and attributes for all entities +- `CleanupEntitiesAsync` removes all entities +- `CleanupDeviceEntitiesAsync` removes only entities for specified device names +- Safe wrappers: failures on one entity don't crash the whole batch + +**Step 3: Implement `PowerMonitorEntityService`** + +Follows the same `SetEntityStateSafe` / `SetEntityAttributesSafe` pattern from `NordPoolEntityService`. System entities are hardcoded. Device entities are generated from the device name pattern `powermonitor__cost_15min`, etc. + +Entity IDs for system entities: +- `sensor.powermonitor_total_power` +- `sensor.powermonitor_total_cost_15min` +- `sensor.powermonitor_total_cost_1h` +- `sensor.powermonitor_total_cost_daily` +- `sensor.powermonitor_total_cost_monthly` +- `sensor.powermonitor_other_power` +- `sensor.powermonitor_other_cost_15min` +- `sensor.powermonitor_other_cost_1h` +- `sensor.powermonitor_other_cost_daily` +- `sensor.powermonitor_other_cost_monthly` +- `binary_sensor.powermonitor_anomaly` +- `sensor.powermonitor_status` +- `button.powermonitor_rediscover_sensors` + +**Step 4: Run tests, verify pass** + +Run: `dotnet test PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj --filter "FullyQualifiedName~PowerMonitorEntityServiceTests" -v normal` +Expected: All tests pass + +**Step 5: Commit** + +``` +git add -A && git commit -m "feat: add PowerMonitorEntityService with system and per-device MQTT entities" +``` + +--- + +### Task 9: PowerMonitorInit orchestrator + +**Files:** +- Create: `PowerMonitor.Manager/Interface/IPowerMonitorInit.cs` +- Create: `PowerMonitor.Manager/PowerMonitorInit.cs` + +**Step 1: Create interface `PowerMonitor.Manager/Interface/IPowerMonitorInit.cs`** + +```csharp +namespace PowerMonitorManager.Interface; + +public interface IPowerMonitorInit +{ + Task InitializeAsync(); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); +} +``` + +**Step 2: Implement `PowerMonitor.Manager/PowerMonitorInit.cs`** + +This is the `[NetDaemonApp]` entry point. Pattern matches `NordPoolInit`: + +- Constructor: inject `Entities`, `IHaContext`, `ILogger`, `IScheduler`, `IOptions`, `IPowerSensorDiscoveryService`, `IOtherPowerCalculationService`, `IPowerCostCalculationService`, `IPowerMonitorEntityService`, `INordPoolPriceService` +- Startup: + 1. Create system entities + 2. Run initial discovery + 3. Create device entities for discovered sensors + 4. Reset all entities + 5. Schedule periodic polling at configured interval (aligned to interval boundaries) + 6. Subscribe to `button.powermonitor_rediscover_sensors` state changes for re-discovery trigger +- Poll cycle method (`UpdateAsync`): + 1. Read main meter state from `IHaContext` + 2. If unavailable, increment failure counter, skip if below threshold, set warning if at threshold + 3. Read all discovered device sensor states — collect readings, track unavailable ones as 0W + 4. Call `IOtherPowerCalculationService.Calculate()` + 5. Get NordPool price from `INordPoolPriceService.CurrentPrice` (fallback: use `PowerCostCalculationService.LastKnownPrice`) + 6. Call `IPowerCostCalculationService.RecordCosts()` + 7. Build `PowerUpdateContext` + 8. Call `IPowerMonitorEntityService.UpdateEntitiesAsync()` +- Re-discovery handler: + 1. Call `IPowerSensorDiscoveryService.DiscoverDeviceSensors()` + 2. Diff with previous list → find new and removed sensors + 3. Create entities for new sensors + 4. Cleanup entities for removed sensors + 5. Log the change + +**Step 3: Verify build** + +Run: `dotnet build PowerMonitor.Manager/PowerMonitor.Manager.csproj` +Expected: Build succeeded + +**Step 4: Commit** + +``` +git add -A && git commit -m "feat: add PowerMonitorInit orchestrator with polling and re-discovery button" +``` + +--- + +### Task 10: DI registration and final wiring + +**Files:** +- Modify: `HomeAssistant.Server/program.cs` +- Modify: `HomeAssistant.Server/appsettings.json` (already done in Task 2) + +**Step 1: Register PowerMonitor services in `program.cs`** + +Add to the `ConfigureServices` lambda, after the NordPool registrations: + +```csharp +.Configure( + context.Configuration.GetSection(PowerMonitorManager.Models.PowerMonitorOptions.SectionName)) +.AddNetDaemonApp() +.AddSingleton() +.AddSingleton() +.AddSingleton() +.AddTransient() +``` + +Note: update the `ConfigureServices` lambda to accept `(context, services)` instead of `(_, services)` since we now need `context.Configuration`. + +Add required using: +```csharp +using PowerMonitorManager; +using PowerMonitorManager.Interface; +``` + +**Step 2: Add Serilog override for PowerMonitorManager to `appsettings.json`** + +Add to `Serilog.MinimumLevel.Override`: +```json +"PowerMonitorManager": "Information" +``` + +**Step 3: Verify full solution builds** + +Run: `dotnet build HomeAssistantSDK.sln` +Expected: Build succeeded + +**Step 4: Run all tests** + +Run: `dotnet test HomeAssistantSDK.sln -v normal` +Expected: All tests pass (both NordPool and PowerMonitor) + +**Step 5: Commit** + +``` +git add -A && git commit -m "feat: wire up PowerMonitor DI registration and complete integration" +``` + +--- + +Plan complete and saved to `docs/plans/2026-03-17-power-monitor-design.md`. Two execution options: + +**1. Subagent-Driven (this session)** — I dispatch a fresh subagent per task, review between tasks, fast iteration + +**2. Parallel Session (separate)** — Open a new session with executing-plans, batch execution with checkpoints + +Which approach?