diff --git a/HomeAssistant.Server/HomeAssistant.Server.csproj b/HomeAssistant.Server/HomeAssistant.Server.csproj index 102ff02..6daf638 100644 --- a/HomeAssistant.Server/HomeAssistant.Server.csproj +++ b/HomeAssistant.Server/HomeAssistant.Server.csproj @@ -48,7 +48,5 @@ - - diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index ab22610..31ccdf2 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -4,8 +4,7 @@ "Default": "Warning", "Override": { "System.Net.Http.HttpClient": "Warning", - "NordPoolManager": "Information", - "PowerMonitorManager": "Information" + "NordPoolManager": "Information" } }, "WriteTo": [ diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 11cf96b..698fe8a 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -14,8 +14,6 @@ using NetDaemon.Runtime; using NordPoolManager; using NordPoolManager.Interface; using HomeAssistantServer; -using PowerMonitorManager; -using PowerMonitorManager.Interface; #pragma warning disable CA1812 @@ -46,9 +44,6 @@ try .AddTransient() .AddSingleton() .AddSingleton() - .AddNetDaemonApp() - .AddTransient() - .AddSingleton() ) .Build() .RunAsync() diff --git a/HomeAssistantSDK.sln b/HomeAssistantSDK.sln index 5bf3b06..dc2e35c 100644 --- a/HomeAssistantSDK.sln +++ b/HomeAssistantSDK.sln @@ -14,12 +14,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.Models", "Hom EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NordPool.Manager.Tests", "NordPool.Manager.Tests\NordPool.Manager.Tests.csproj", "{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C}" 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 GlobalSection(SolutionConfigurationPlatforms) = preSolution 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}.Release|Any CPU.ActiveCfg = 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 GlobalSection(NestedProjects) = preSolution EndGlobalSection diff --git a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs deleted file mode 100644 index 20fea91..0000000 --- a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs +++ /dev/null @@ -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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 -} diff --git a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj b/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj deleted file mode 100644 index 9a4409f..0000000 --- a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - net10.0 - enable - enable - false - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - diff --git a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs deleted file mode 100644 index 310d62b..0000000 --- a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs +++ /dev/null @@ -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 _entityManagerMock; - private readonly Mock> _loggerMock; - private readonly PowerMonitorEntityService _sut; - - public PowerMonitorEntityServiceTests() - { - _entityManagerMock = new Mock(); - _loggerMock = new Mock>(); - _sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object); - } - - #region CreateEntityAsync - - [Fact] - public async Task CreateEntityAsync_ShouldCreateMqttEntity() - { - // Arrange - _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(Task.CompletedTask); - - // Act - await _sut.CreateEntityAsync(); - - // Assert - _entityManagerMock.Verify( - em => em.CreateEntityAsync(It.Is(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())) - .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(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .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(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - - // Act - await _sut.ResetEntityAsync(); - - // Assert - _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.other_power_usage", It.IsAny()), - 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(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .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(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - - // Act - await _sut.UpdateEntityAsync(context); - - // Assert - _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.other_power_usage", It.IsAny()), - 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(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .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())) - .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())) - .ThrowsAsync(new InvalidOperationException("Remove failed")); - - // Act - var act = () => _sut.CleanupEntityAsync(); - - // Assert - await act.Should().ThrowAsync() - .WithMessage("Remove failed"); - } - - #endregion - - #region SetEntityStateSafe - - [Fact] - public async Task SetEntityStateSafe_ShouldCallSetEntityState() - { - // Arrange - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .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(), It.IsAny())) - .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(), It.IsAny())) - .Returns(Task.CompletedTask); - - // Act - await _sut.SetEntityAttributesSafe("sensor.test", attributes); - - // Assert - _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.test", It.IsAny()), - Times.Once); - } - - [Fact] - public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow() - { - // Arrange - var attributes = new { unit_of_measurement = "W" }; - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Attributes update failed")); - - // Act - var act = () => _sut.SetEntityAttributesSafe("sensor.test", attributes); - - // Assert - await act.Should().NotThrowAsync(); - } - - #endregion -} diff --git a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs b/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs deleted file mode 100644 index 1cb908c..0000000 --- a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs +++ /dev/null @@ -1,8 +0,0 @@ -using PowerMonitorManager.Models; - -namespace PowerMonitorManager.Interface; - -public interface IOtherPowerCalculationService -{ - PowerCalculationResult CalculateOtherPower(double? totalHomePower, IReadOnlyList monitoredSensorValues); -} diff --git a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs b/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs deleted file mode 100644 index d2f4aaa..0000000 --- a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using PowerMonitorManager.Models; - -namespace PowerMonitorManager.Interface; - -public interface IPowerMonitorEntityService -{ - Task CreateEntityAsync(); - Task ResetEntityAsync(); - Task UpdateEntityAsync(PowerUpdateContext context); - Task CleanupEntityAsync(); -} diff --git a/PowerMonitor.Manager/Interface/IPowerMonitorInit.cs b/PowerMonitor.Manager/Interface/IPowerMonitorInit.cs deleted file mode 100644 index 2d4d3b3..0000000 --- a/PowerMonitor.Manager/Interface/IPowerMonitorInit.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace PowerMonitorManager.Interface; - -public interface IPowerMonitorInit -{ - Task CleanupEntityAsync(); -} diff --git a/PowerMonitor.Manager/Models/PowerCalculationResult.cs b/PowerMonitor.Manager/Models/PowerCalculationResult.cs deleted file mode 100644 index 3ff1294..0000000 --- a/PowerMonitor.Manager/Models/PowerCalculationResult.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace PowerMonitorManager.Models; - -public sealed record PowerCalculationResult( - double OtherPower, - double SumOfMonitored); diff --git a/PowerMonitor.Manager/Models/PowerUpdateContext.cs b/PowerMonitor.Manager/Models/PowerUpdateContext.cs deleted file mode 100644 index f0bb514..0000000 --- a/PowerMonitor.Manager/Models/PowerUpdateContext.cs +++ /dev/null @@ -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; } -} diff --git a/PowerMonitor.Manager/OtherPowerCalculationService.cs b/PowerMonitor.Manager/OtherPowerCalculationService.cs deleted file mode 100644 index 52c256d..0000000 --- a/PowerMonitor.Manager/OtherPowerCalculationService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using PowerMonitorManager.Interface; -using PowerMonitorManager.Models; - -namespace PowerMonitorManager; - -public sealed class OtherPowerCalculationService : IOtherPowerCalculationService -{ - public PowerCalculationResult CalculateOtherPower(double? totalHomePower, IReadOnlyList 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); - } -} diff --git a/PowerMonitor.Manager/PowerMonitor.Manager.csproj b/PowerMonitor.Manager/PowerMonitor.Manager.csproj deleted file mode 100644 index de83158..0000000 --- a/PowerMonitor.Manager/PowerMonitor.Manager.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - net10.0 - enable - enable - PowerMonitorManager - - - - - <_Parameter1>PowerMonitor.Manager.Tests - - - - - - - - - - - - - - diff --git a/PowerMonitor.Manager/PowerMonitorEntityService.cs b/PowerMonitor.Manager/PowerMonitorEntityService.cs deleted file mode 100644 index 4fa9d31..0000000 --- a/PowerMonitor.Manager/PowerMonitorEntityService.cs +++ /dev/null @@ -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 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); - } - } -} diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs deleted file mode 100644 index 01cf011..0000000 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ /dev/null @@ -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 _logger; - private readonly IOtherPowerCalculationService _calculationService; - private readonly IPowerMonitorEntityService _entityService; - private readonly SemaphoreSlim _updateLock = new(1, 1); - private readonly List _subscriptions = []; - private readonly Task _initializationTask; - - private NumericSensorEntity TotalHomePowerEntity { get; } - private IReadOnlyList MonitoredSensorEntities { get; } - - public PowerMonitorInit( - IHaContext haContext, - ILogger 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(); - } -} diff --git a/PowerMonitor.Models/PowerMonitor.Models.csproj b/PowerMonitor.Models/PowerMonitor.Models.csproj deleted file mode 100644 index 56d1d3f..0000000 --- a/PowerMonitor.Models/PowerMonitor.Models.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - net10.0 - enable - enable - - - - - - - - - - - diff --git a/PowerMonitor.Models/PowerMonitorEntity.cs b/PowerMonitor.Models/PowerMonitorEntity.cs deleted file mode 100644 index 8f467b0..0000000 --- a/PowerMonitor.Models/PowerMonitorEntity.cs +++ /dev/null @@ -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 - }; - } -} diff --git a/PowerMonitor.Models/PowerSensorConfig.cs b/PowerMonitor.Models/PowerSensorConfig.cs deleted file mode 100644 index 6b0f0fe..0000000 --- a/PowerMonitor.Models/PowerSensorConfig.cs +++ /dev/null @@ -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 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" - ]; -}