Remove PowerMonitor.Manager project and its dependencies

This commit is contained in:
Marius
2026-03-10 12:27:06 +02:00
parent 41991e78b5
commit 27648ae57c
19 changed files with 1 additions and 1039 deletions
@@ -48,7 +48,5 @@
<ProjectReference Include="..\Mappings\Mappings.csproj" /> <ProjectReference Include="..\Mappings\Mappings.csproj" />
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" /> <ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" /> <ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+1 -2
View File
@@ -4,8 +4,7 @@
"Default": "Warning", "Default": "Warning",
"Override": { "Override": {
"System.Net.Http.HttpClient": "Warning", "System.Net.Http.HttpClient": "Warning",
"NordPoolManager": "Information", "NordPoolManager": "Information"
"PowerMonitorManager": "Information"
} }
}, },
"WriteTo": [ "WriteTo": [
-5
View File
@@ -14,8 +14,6 @@ using NetDaemon.Runtime;
using NordPoolManager; using NordPoolManager;
using NordPoolManager.Interface; using NordPoolManager.Interface;
using HomeAssistantServer; using HomeAssistantServer;
using PowerMonitorManager;
using PowerMonitorManager.Interface;
#pragma warning disable CA1812 #pragma warning disable CA1812
@@ -46,9 +44,6 @@ try
.AddTransient<INordPoolEntityService, NordPoolEntityService>() .AddTransient<INordPoolEntityService, NordPoolEntityService>()
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>() .AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
.AddSingleton<IBoilerControlService, BoilerControlService>() .AddSingleton<IBoilerControlService, BoilerControlService>()
.AddNetDaemonApp<PowerMonitorInit>()
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
) )
.Build() .Build()
.RunAsync() .RunAsync()
-18
View File
@@ -14,12 +14,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.Models", "Hom
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NordPool.Manager.Tests", "NordPool.Manager.Tests\NordPool.Manager.Tests.csproj", "{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NordPool.Manager.Tests", "NordPool.Manager.Tests\NordPool.Manager.Tests.csproj", "{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Models", "PowerMonitor.Models\PowerMonitor.Models.csproj", "{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager", "PowerMonitor.Manager\PowerMonitor.Manager.csproj", "{B2C3D4E5-F6A7-8901-BCDE-F12345678901}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{C3D4E5F6-A7B8-9012-CDEF-123456789012}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -54,18 +48,6 @@ Global
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|Any CPU.Build.0 = Release|Any CPU {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}.Release|Any CPU.Build.0 = Release|Any CPU
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.Build.0 = Release|Any CPU
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|Any CPU.Build.0 = Release|Any CPU
{C3D4E5F6-A7B8-9012-CDEF-123456789012}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3D4E5F6-A7B8-9012-CDEF-123456789012}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3D4E5F6-A7B8-9012-CDEF-123456789012}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3D4E5F6-A7B8-9012-CDEF-123456789012}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution GlobalSection(NestedProjects) = preSolution
EndGlobalSection EndGlobalSection
@@ -1,233 +0,0 @@
using FluentAssertions;
using PowerMonitorManager;
namespace PowerMonitor.Manager.Tests;
public class OtherPowerCalculationServiceTests
{
private readonly OtherPowerCalculationService _sut = new();
#region Normal Calculation
[Fact]
public void CalculateOtherPower_WithValidValues_ShouldReturnDifference()
{
// Arrange
double? totalPower = 3000.0;
IReadOnlyList<double?> monitoredValues = [500.0, 300.0, 200.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(2000.0);
result.SumOfMonitored.Should().Be(1000.0);
}
[Fact]
public void CalculateOtherPower_WhenMonitoredEqualsTotal_ShouldReturnZero()
{
// Arrange
double? totalPower = 1000.0;
IReadOnlyList<double?> monitoredValues = [400.0, 350.0, 250.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(0.0);
result.SumOfMonitored.Should().Be(1000.0);
}
[Fact]
public void CalculateOtherPower_WithSingleMonitoredSensor_ShouldReturnDifference()
{
// Arrange
double? totalPower = 5000.0;
IReadOnlyList<double?> monitoredValues = [1500.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(3500.0);
result.SumOfMonitored.Should().Be(1500.0);
}
[Fact]
public void CalculateOtherPower_WithFractionalValues_ShouldReturnPreciseDifference()
{
// Arrange
double? totalPower = 1234.56;
IReadOnlyList<double?> monitoredValues = [100.11, 200.22, 300.33];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().BeApproximately(633.9, 0.01);
result.SumOfMonitored.Should().BeApproximately(600.66, 0.01);
}
#endregion
#region Clamping to Zero
[Fact]
public void CalculateOtherPower_WhenMonitoredExceedsTotal_ShouldClampToZero()
{
// Arrange
double? totalPower = 500.0;
IReadOnlyList<double?> monitoredValues = [300.0, 400.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(0.0);
result.SumOfMonitored.Should().Be(700.0);
}
[Fact]
public void CalculateOtherPower_WhenTotalIsZeroWithMonitoredValues_ShouldClampToZero()
{
// Arrange
double? totalPower = 0.0;
IReadOnlyList<double?> monitoredValues = [100.0, 200.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(0.0);
result.SumOfMonitored.Should().Be(300.0);
}
#endregion
#region Null and Unavailable Handling
[Fact]
public void CalculateOtherPower_WhenTotalIsNull_ShouldTreatAsZero()
{
// Arrange
IReadOnlyList<double?> monitoredValues = [100.0, 200.0];
// Act
var result = _sut.CalculateOtherPower(null, monitoredValues);
// Assert
result.OtherPower.Should().Be(0.0);
result.SumOfMonitored.Should().Be(300.0);
}
[Fact]
public void CalculateOtherPower_WhenSomeMonitoredAreNull_ShouldTreatNullsAsZero()
{
// Arrange
double? totalPower = 1000.0;
IReadOnlyList<double?> monitoredValues = [200.0, null, 300.0, null];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(500.0);
result.SumOfMonitored.Should().Be(500.0);
}
[Fact]
public void CalculateOtherPower_WhenAllMonitoredAreNull_ShouldReturnTotal()
{
// Arrange
double? totalPower = 1500.0;
IReadOnlyList<double?> monitoredValues = [null, null, null];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(1500.0);
result.SumOfMonitored.Should().Be(0.0);
}
[Fact]
public void CalculateOtherPower_WhenBothTotalAndMonitoredAreNull_ShouldReturnZero()
{
// Arrange
IReadOnlyList<double?> monitoredValues = [null, null];
// Act
var result = _sut.CalculateOtherPower(null, monitoredValues);
// Assert
result.OtherPower.Should().Be(0.0);
result.SumOfMonitored.Should().Be(0.0);
}
#endregion
#region Edge Cases
[Fact]
public void CalculateOtherPower_WithEmptyMonitoredList_ShouldReturnTotal()
{
// Arrange
double? totalPower = 2500.0;
IReadOnlyList<double?> monitoredValues = [];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(2500.0);
result.SumOfMonitored.Should().Be(0.0);
}
[Fact]
public void CalculateOtherPower_WithAllZeroValues_ShouldReturnZero()
{
// Arrange
double? totalPower = 0.0;
IReadOnlyList<double?> monitoredValues = [0.0, 0.0, 0.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(0.0);
result.SumOfMonitored.Should().Be(0.0);
}
[Fact]
public void CalculateOtherPower_WithVeryLargeValues_ShouldHandleCorrectly()
{
// Arrange
double? totalPower = 100_000.0;
IReadOnlyList<double?> monitoredValues = [25_000.0, 30_000.0, 15_000.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().Be(30_000.0);
result.SumOfMonitored.Should().Be(70_000.0);
}
[Fact]
public void CalculateOtherPower_ResultShouldNeverBeNegative()
{
// Arrange
double? totalPower = 100.0;
IReadOnlyList<double?> monitoredValues = [50.0, 60.0, 70.0, 80.0];
// Act
var result = _sut.CalculateOtherPower(totalPower, monitoredValues);
// Assert
result.OtherPower.Should().BeGreaterThanOrEqualTo(0.0);
result.SumOfMonitored.Should().Be(260.0);
}
#endregion
}
@@ -1,34 +0,0 @@
<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>
@@ -1,285 +0,0 @@
using FluentAssertions;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using Moq;
using PowerMonitor.Models;
using PowerMonitorManager;
using PowerMonitorManager.Models;
namespace PowerMonitor.Manager.Tests;
public class PowerMonitorEntityServiceTests
{
private readonly Mock<IEntityManager> _entityManagerMock;
private readonly Mock<ILogger<PowerMonitorEntityService>> _loggerMock;
private readonly PowerMonitorEntityService _sut;
public PowerMonitorEntityServiceTests()
{
_entityManagerMock = new Mock<IEntityManager>();
_loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object);
}
#region CreateEntityAsync
[Fact]
public async Task CreateEntityAsync_ShouldCreateMqttEntity()
{
// Arrange
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CreateEntityAsync();
// Assert
_entityManagerMock.Verify(
em => em.CreateEntityAsync(It.Is<PowerMonitorEntity>(e =>
e.EntityId == "sensor.other_power_usage" &&
e.Domain == "sensor" &&
e.Identifier == "other_power_usage")),
Times.Once);
}
[Fact]
public async Task CreateEntityAsync_WhenCreateFails_ShouldNotThrow()
{
// Arrange
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
// Act
var act = () => _sut.CreateEntityAsync();
// Assert
await act.Should().NotThrowAsync();
}
#endregion
#region ResetEntityAsync
[Fact]
public async Task ResetEntityAsync_ShouldSetStateToZero()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.ResetEntityAsync();
// Assert
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.other_power_usage", "0"),
Times.Once);
}
[Fact]
public async Task ResetEntityAsync_ShouldSetDefaultAttributes()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.ResetEntityAsync();
// Assert
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.other_power_usage", It.IsAny<object>()),
Times.Once);
}
#endregion
#region UpdateEntityAsync
[Fact]
public async Task UpdateEntityAsync_ShouldSetStateWithFormattedPower()
{
// Arrange
var context = new PowerUpdateContext
{
TotalHomePower = 3000.0,
TotalMonitoredPower = 1500.0,
OtherPower = 1500.0,
MonitoredSensorCount = 21
};
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntityAsync(context);
// Assert
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.other_power_usage", "1500.00"),
Times.Once);
}
[Fact]
public async Task UpdateEntityAsync_ShouldSetAttributes()
{
// Arrange
var context = new PowerUpdateContext
{
TotalHomePower = 5000.0,
TotalMonitoredPower = 2000.0,
OtherPower = 3000.0,
MonitoredSensorCount = 15
};
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntityAsync(context);
// Assert
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.other_power_usage", It.IsAny<object>()),
Times.Once);
}
[Fact]
public async Task UpdateEntityAsync_WithZeroPower_ShouldSetZeroState()
{
// Arrange
var context = new PowerUpdateContext
{
TotalHomePower = 0.0,
TotalMonitoredPower = 0.0,
OtherPower = 0.0,
MonitoredSensorCount = 10
};
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntityAsync(context);
// Assert
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.other_power_usage", "0.00"),
Times.Once);
}
#endregion
#region CleanupEntityAsync
[Fact]
public async Task CleanupEntityAsync_ShouldRemoveEntity()
{
// Arrange
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CleanupEntityAsync();
// Assert
_entityManagerMock.Verify(
em => em.RemoveEntity("sensor.other_power_usage"),
Times.Once);
}
[Fact]
public async Task CleanupEntityAsync_WhenRemoveFails_ShouldRethrow()
{
// Arrange
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Remove failed"));
// Act
var act = () => _sut.CleanupEntityAsync();
// Assert
await act.Should().ThrowAsync<InvalidOperationException>()
.WithMessage("Remove failed");
}
#endregion
#region SetEntityStateSafe
[Fact]
public async Task SetEntityStateSafe_ShouldCallSetEntityState()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Act
await _sut.SetEntityStateSafe("sensor.test", "42");
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.test", "42"), Times.Once);
}
[Fact]
public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed"));
// Act
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
// Assert
await act.Should().NotThrowAsync();
}
#endregion
#region SetEntityAttributesSafe
[Fact]
public async Task SetEntityAttributesSafe_ShouldCallSetEntityAttributes()
{
// Arrange
var attributes = new { unit_of_measurement = "W" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.SetEntityAttributesSafe("sensor.test", attributes);
// Assert
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.test", It.IsAny<object>()),
Times.Once);
}
[Fact]
public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow()
{
// Arrange
var attributes = new { unit_of_measurement = "W" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.ThrowsAsync(new InvalidOperationException("Attributes update failed"));
// Act
var act = () => _sut.SetEntityAttributesSafe("sensor.test", attributes);
// Assert
await act.Should().NotThrowAsync();
}
#endregion
}
@@ -1,8 +0,0 @@
using PowerMonitorManager.Models;
namespace PowerMonitorManager.Interface;
public interface IOtherPowerCalculationService
{
PowerCalculationResult CalculateOtherPower(double? totalHomePower, IReadOnlyList<double?> monitoredSensorValues);
}
@@ -1,11 +0,0 @@
using PowerMonitorManager.Models;
namespace PowerMonitorManager.Interface;
public interface IPowerMonitorEntityService
{
Task CreateEntityAsync();
Task ResetEntityAsync();
Task UpdateEntityAsync(PowerUpdateContext context);
Task CleanupEntityAsync();
}
@@ -1,6 +0,0 @@
namespace PowerMonitorManager.Interface;
public interface IPowerMonitorInit
{
Task CleanupEntityAsync();
}
@@ -1,5 +0,0 @@
namespace PowerMonitorManager.Models;
public sealed record PowerCalculationResult(
double OtherPower,
double SumOfMonitored);
@@ -1,9 +0,0 @@
namespace PowerMonitorManager.Models;
public sealed record PowerUpdateContext
{
public required double TotalHomePower { get; init; }
public required double TotalMonitoredPower { get; init; }
public required double OtherPower { get; init; }
public required int MonitoredSensorCount { get; init; }
}
@@ -1,16 +0,0 @@
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
namespace PowerMonitorManager;
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
{
public PowerCalculationResult CalculateOtherPower(double? totalHomePower, IReadOnlyList<double?> monitoredSensorValues)
{
var total = totalHomePower ?? 0.0;
var sumOfMonitored = monitoredSensorValues.Sum(v => v ?? 0.0);
var otherPower = Math.Max(0.0, total - sumOfMonitored);
return new PowerCalculationResult(otherPower, sumOfMonitored);
}
}
@@ -1,26 +0,0 @@
<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>
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
</ItemGroup>
</Project>
@@ -1,126 +0,0 @@
using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using PowerMonitor.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
namespace PowerMonitorManager;
public sealed class PowerMonitorEntityService(
IEntityManager entityManager,
ILogger<PowerMonitorEntityService> logger) : IPowerMonitorEntityService
{
private const string OtherPowerEntityId = PowerSensorConfig.OtherPowerUsageEntityId;
private const string UnitOfMeasurement = "W";
private const string DeviceClass = "power";
private const string StateClass = "measurement";
private const string FriendlyName = "Other Power Usage";
public async Task CreateEntityAsync()
{
try
{
var entity = new PowerMonitorEntity("sensor", "other_power_usage", FriendlyName)
{
AdditionalConfig = new
{
unit_of_measurement = UnitOfMeasurement,
device_class = DeviceClass,
state_class = StateClass
}
};
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", OtherPowerEntityId);
}
}
public async Task ResetEntityAsync()
{
logger.LogInformation("Resetting Other Power entity state to defaults");
await SetEntityStateSafe(OtherPowerEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(OtherPowerEntityId, BuildAttributes(0.0, 0.0, 0.0, 0, null)).ConfigureAwait(false);
}
public async Task UpdateEntityAsync(PowerUpdateContext context)
{
var timestamp = DateTime.UtcNow.ToString("O");
var stateValue = context.OtherPower.ToString("F2", CultureInfo.InvariantCulture);
logger.LogDebug(
"Updating other_power_usage: {OtherPower}W (total: {Total}W, monitored: {Monitored}W, sensors: {Count})",
stateValue, context.TotalHomePower, context.TotalMonitoredPower, context.MonitoredSensorCount);
await SetEntityStateSafe(OtherPowerEntityId, stateValue).ConfigureAwait(false);
await SetEntityAttributesSafe(OtherPowerEntityId, BuildAttributes(
context.TotalHomePower,
context.TotalMonitoredPower,
context.OtherPower,
context.MonitoredSensorCount,
timestamp)).ConfigureAwait(false);
}
public async Task CleanupEntityAsync()
{
try
{
await entityManager.RemoveEntity(OtherPowerEntityId).ConfigureAwait(false);
logger.LogInformation("Other Power entity cleaned up successfully");
}
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up Other Power entity");
throw;
}
}
private static object BuildAttributes(
double totalHomePower,
double totalMonitoredPower,
double otherPower,
int monitoredSensorCount,
string? lastUpdated) => new
{
unit_of_measurement = UnitOfMeasurement,
device_class = DeviceClass,
state_class = StateClass,
friendly_name = FriendlyName,
total_home_power = totalHomePower,
total_monitored_power = totalMonitoredPower,
other_power = otherPower,
monitored_sensor_count = monitoredSensorCount,
last_updated = lastUpdated
};
internal async Task SetEntityStateSafe(string entityId, string state)
{
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
}
}
internal async Task SetEntityAttributesSafe(string entityId, object attributes)
{
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
}
}
}
-178
View File
@@ -1,178 +0,0 @@
using System.Reactive.Linq;
using HomeAssistantGenerated;
using Microsoft.Extensions.Logging;
using NetDaemon.AppModel;
using NetDaemon.HassModel;
using PowerMonitor.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
namespace PowerMonitorManager;
[NetDaemonApp]
public sealed class PowerMonitorInit : IPowerMonitorInit, IAsyncDisposable, IDisposable
{
private readonly ILogger<PowerMonitorInit> _logger;
private readonly IOtherPowerCalculationService _calculationService;
private readonly IPowerMonitorEntityService _entityService;
private readonly SemaphoreSlim _updateLock = new(1, 1);
private readonly List<IDisposable> _subscriptions = [];
private readonly Task _initializationTask;
private NumericSensorEntity TotalHomePowerEntity { get; }
private IReadOnlyList<NumericSensorEntity> MonitoredSensorEntities { get; }
public PowerMonitorInit(
IHaContext haContext,
ILogger<PowerMonitorInit> logger,
IOtherPowerCalculationService calculationService,
IPowerMonitorEntityService entityService)
{
_logger = logger;
_calculationService = calculationService;
_entityService = entityService;
TotalHomePowerEntity = new NumericSensorEntity(haContext, PowerSensorConfig.TotalHomePowerEntityId);
MonitoredSensorEntities = PowerSensorConfig.MonitoredSensorEntityIds
.Select(id => new NumericSensorEntity(haContext, id))
.ToList()
.AsReadOnly();
_initializationTask = InitializeAndSubscribeAsync();
}
private async Task InitializeAndSubscribeAsync()
{
try
{
await InitializeAsync().ConfigureAwait(false);
SubscribeToSensorChanges();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during power monitor initialization");
}
}
private async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3)).ConfigureAwait(false);
await _entityService.CreateEntityAsync().ConfigureAwait(false);
await _entityService.ResetEntityAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
await RecalculateAndUpdateAsync().ConfigureAwait(false);
_logger.LogInformation(
"Power monitor initialized. Monitoring {Count} sensors against total home power",
MonitoredSensorEntities.Count);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing power monitor");
throw;
}
}
private void SubscribeToSensorChanges()
{
var totalSubscription = TotalHomePowerEntity
.StateAllChanges()
.Subscribe(_ => HandleSensorStateChanged(PowerSensorConfig.TotalHomePowerEntityId));
_subscriptions.Add(totalSubscription);
foreach (var sensor in MonitoredSensorEntities)
{
var entityId = sensor.EntityId;
var subscription = sensor
.StateAllChanges()
.Subscribe(_ => HandleSensorStateChanged(entityId));
_subscriptions.Add(subscription);
}
_logger.LogInformation(
"Subscribed to state changes on {Count} sensors (1 total + {MonitoredCount} monitored)",
_subscriptions.Count, MonitoredSensorEntities.Count);
}
private async void HandleSensorStateChanged(string sensorEntityId)
{
try
{
_logger.LogDebug("Sensor state changed: {EntityId}", sensorEntityId);
await RecalculateAndUpdateAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling sensor state change for {EntityId}", sensorEntityId);
}
}
private async Task RecalculateAndUpdateAsync()
{
if (!await _updateLock.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false))
{
_logger.LogDebug("Skipping power recalculation, another update is in progress");
return;
}
try
{
var totalPower = TotalHomePowerEntity.State;
var monitoredValues = MonitoredSensorEntities
.Select(s => s.State)
.ToList();
var result = _calculationService.CalculateOtherPower(totalPower, monitoredValues);
var context = new PowerUpdateContext
{
TotalHomePower = totalPower ?? 0.0,
TotalMonitoredPower = result.SumOfMonitored,
OtherPower = result.OtherPower,
MonitoredSensorCount = MonitoredSensorEntities.Count
};
await _entityService.UpdateEntityAsync(context).ConfigureAwait(false);
}
finally
{
_updateLock.Release();
}
}
public async Task CleanupEntityAsync()
{
await _entityService.CleanupEntityAsync().ConfigureAwait(false);
}
public async ValueTask DisposeAsync()
{
try
{
await _initializationTask.ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Initialization task completed with an error during dispose");
}
Dispose();
}
public void Dispose()
{
foreach (var subscription in _subscriptions)
{
subscription.Dispose();
}
_subscriptions.Clear();
_updateLock.Dispose();
}
}
@@ -1,17 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
</ItemGroup>
</Project>
-25
View File
@@ -1,25 +0,0 @@
using HomeAssistant.Models;
using NetDaemon.Extensions.MqttEntityManager;
namespace PowerMonitor.Models;
public sealed class PowerMonitorEntity : EntityCreateModel
{
public string Domain { get; }
public string Identifier { get; }
public string Name { get; }
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
};
}
}
-33
View File
@@ -1,33 +0,0 @@
namespace PowerMonitor.Models;
public static class PowerSensorConfig
{
public const string TotalHomePowerEntityId = "sensor.sonoff_100267d63f_power";
public const string OtherPowerUsageEntityId = "sensor.other_power_usage";
public static IReadOnlyList<string> MonitoredSensorEntityIds { get; } =
[
"sensor.sonoff_1002230e32_power",
"sensor.sonoff_10018909cb_power",
"sensor.sonoff_100215c534_power",
"sensor.sonoff_100222f7be_power",
"sensor.sonoff_100222ff36_power",
"sensor.sonoff_100222ff63_power",
"sensor.sonoff_1002230a48_power",
"sensor.sonoff_100255ead8_power",
"sensor.sonoff_100255f06c_power",
"sensor.sonoff_100255f738_power",
"sensor.sonoff_10025606e6_power",
"sensor.sonoff_10025609ce_power",
"sensor.sonoff_s60zbtpf_power",
"sensor.sonoff_s60zbtpf_power_2",
"sensor.akvariumas_power",
"sensor.balkony_laps_power",
"sensor.christmas_lights_power_usage",
"sensor.dishwasher_power",
"sensor.fridge_power",
"sensor.temp_power",
"sensor.tv_power"
];
}