9d4f0b36c3
Made-with: Cursor
1234 lines
39 KiB
Markdown
1234 lines
39 KiB
Markdown
# Power Monitor Implementation Plan
|
||
|
||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
|
||
|
||
**Goal:** Track "other" (untracked) power usage and per-device/total/other electricity costs with NordPool price integration, exposed as MQTT entities in Home Assistant.
|
||
|
||
**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.
|
||
|
||
**Tech Stack:** .NET 10, NetDaemon (v26.3.0), MQTT Entity Manager, xUnit + Moq + FluentAssertions
|
||
|
||
---
|
||
|
||
### Task 1: Create project scaffolding and solution structure
|
||
|
||
**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`
|
||
|
||
**Step 1: Create `PowerMonitor.Models/PowerMonitor.Models.csproj`**
|
||
|
||
```xml
|
||
<Project Sdk="Microsoft.NET.Sdk">
|
||
|
||
<PropertyGroup>
|
||
<TargetFramework>net10.0</TargetFramework>
|
||
<ImplicitUsings>enable</ImplicitUsings>
|
||
<Nullable>enable</Nullable>
|
||
<RootNamespace>PowerMonitor.Models</RootNamespace>
|
||
</PropertyGroup>
|
||
|
||
<ItemGroup>
|
||
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
|
||
</ItemGroup>
|
||
|
||
<ItemGroup>
|
||
<PackageReference Include="NetDaemon.Extensions.MqttEntityManager" Version="26.3.0" />
|
||
</ItemGroup>
|
||
|
||
</Project>
|
||
```
|
||
|
||
**Step 2: Create `PowerMonitor.Manager/PowerMonitor.Manager.csproj`**
|
||
|
||
```xml
|
||
<Project Sdk="Microsoft.NET.Sdk">
|
||
|
||
<PropertyGroup>
|
||
<TargetFramework>net10.0</TargetFramework>
|
||
<ImplicitUsings>enable</ImplicitUsings>
|
||
<Nullable>enable</Nullable>
|
||
<RootNamespace>PowerMonitorManager</RootNamespace>
|
||
</PropertyGroup>
|
||
|
||
<ItemGroup>
|
||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||
<_Parameter1>PowerMonitor.Manager.Tests</_Parameter1>
|
||
</AssemblyAttribute>
|
||
</ItemGroup>
|
||
|
||
<ItemGroup>
|
||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
||
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
||
</ItemGroup>
|
||
|
||
<ItemGroup>
|
||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.0-preview.2.25163.2" />
|
||
</ItemGroup>
|
||
|
||
</Project>
|
||
```
|
||
|
||
**Step 3: Create `PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj`**
|
||
|
||
```xml
|
||
<Project Sdk="Microsoft.NET.Sdk">
|
||
|
||
<PropertyGroup>
|
||
<TargetFramework>net10.0</TargetFramework>
|
||
<ImplicitUsings>enable</ImplicitUsings>
|
||
<Nullable>enable</Nullable>
|
||
<IsPackable>false</IsPackable>
|
||
</PropertyGroup>
|
||
|
||
<ItemGroup>
|
||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
||
<PrivateAssets>all</PrivateAssets>
|
||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||
</PackageReference>
|
||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
||
<PackageReference Include="xunit" Version="2.9.3" />
|
||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||
<PrivateAssets>all</PrivateAssets>
|
||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||
</PackageReference>
|
||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||
<PackageReference Include="Moq" Version="4.20.72" />
|
||
</ItemGroup>
|
||
|
||
<ItemGroup>
|
||
<Using Include="Xunit" />
|
||
</ItemGroup>
|
||
|
||
<ItemGroup>
|
||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
||
</ItemGroup>
|
||
|
||
</Project>
|
||
```
|
||
|
||
**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` `<ItemGroup>` with project references:
|
||
```xml
|
||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
||
```
|
||
|
||
**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
|
||
{
|
||
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_*"
|
||
]
|
||
}
|
||
```
|
||
|
||
**Step 4: Verify build**
|
||
|
||
Run: `dotnet build PowerMonitor.Manager/PowerMonitor.Manager.csproj`
|
||
Expected: Build succeeded
|
||
|
||
**Step 5: Commit**
|
||
|
||
```
|
||
git add -A && git commit -m "feat: add PowerMonitor configuration model and constants"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 3: Create shared models
|
||
|
||
**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`
|
||
|
||
**Step 1: Create `PowerMonitor.Models/PowerMonitorEntity.cs`**
|
||
|
||
Follows same pattern as `NordPool.Models/NordPoolEntities.cs`:
|
||
|
||
```csharp
|
||
using HomeAssistant.Models;
|
||
using NetDaemon.Extensions.MqttEntityManager;
|
||
|
||
namespace PowerMonitor.Models;
|
||
|
||
public class PowerMonitorEntity : EntityCreateModel
|
||
{
|
||
public string Domain { get; set; }
|
||
public string Identifier { get; set; }
|
||
public string Name { get; set; }
|
||
|
||
public PowerMonitorEntity(string domain, string identifier, string name)
|
||
{
|
||
Domain = domain;
|
||
Identifier = identifier;
|
||
EntityId = $"{Domain}.{Identifier}";
|
||
Name = string.IsNullOrWhiteSpace(name) ? identifier : name;
|
||
|
||
Options = new EntityCreationOptions
|
||
{
|
||
UniqueId = EntityId,
|
||
Name = Name
|
||
};
|
||
}
|
||
}
|
||
```
|
||
|
||
**Step 2: Create `PowerMonitor.Models/PowerSensorInfo.cs`**
|
||
|
||
```csharp
|
||
namespace PowerMonitor.Models;
|
||
|
||
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";
|
||
}
|
||
```
|
||
|
||
**Step 3: Create `PowerMonitor.Manager/Models/PowerCalculationResult.cs`**
|
||
|
||
```csharp
|
||
namespace PowerMonitorManager.Models;
|
||
|
||
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<string, double> DevicePowerReadings { get; init; } = new Dictionary<string, double>();
|
||
}
|
||
```
|
||
|
||
**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<string, CostSnapshot> 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<string> 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<string, double> 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<string, double>
|
||
{
|
||
["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<string, double>
|
||
{
|
||
["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<string, double>();
|
||
|
||
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<string, double>
|
||
{
|
||
["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<string, double>();
|
||
|
||
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<string, double>();
|
||
|
||
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<string, double>();
|
||
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<PowerMonitorOptions> options)
|
||
{
|
||
var windowSize = options.Value.SmoothingWindowSize;
|
||
_alpha = 2.0 / (windowSize + 1);
|
||
}
|
||
|
||
public PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary<string, double> 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<string, double>(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<PowerSensorInfo> DiscoverDeviceSensors();
|
||
IReadOnlyList<PowerSensorInfo> 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<PowerSensorInfo>` 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<string, CostSnapshot> 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<string, CostAccumulator>` 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<PowerSensorInfo> sensors, CancellationToken cancellationToken = default);
|
||
Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default);
|
||
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||
Task CleanupDeviceEntitiesAsync(IReadOnlyList<string> 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_<device>_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<PowerMonitorOptions>`, `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<PowerMonitorManager.Models.PowerMonitorOptions>(
|
||
context.Configuration.GetSection(PowerMonitorManager.Models.PowerMonitorOptions.SectionName))
|
||
.AddNetDaemonApp<PowerMonitorManager.PowerMonitorInit>()
|
||
.AddSingleton<PowerMonitorManager.Interface.IPowerSensorDiscoveryService, PowerMonitorManager.PowerSensorDiscoveryService>()
|
||
.AddSingleton<PowerMonitorManager.Interface.IOtherPowerCalculationService, PowerMonitorManager.OtherPowerCalculationService>()
|
||
.AddSingleton<PowerMonitorManager.Interface.IPowerCostCalculationService, PowerMonitorManager.PowerCostCalculationService>()
|
||
.AddTransient<PowerMonitorManager.Interface.IPowerMonitorEntityService, PowerMonitorManager.PowerMonitorEntityService>()
|
||
```
|
||
|
||
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?
|