From f919d6b25b9ee86efa7ee126cfb6db66ab7d0825 Mon Sep 17 00:00:00 2001 From: ExQz Date: Tue, 1 Dec 2026 12:33:31 +0200 Subject: [PATCH] Apply code formatting cleanup across the monitor projects - Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests - Expand single-statement guards and loops into braced blocks - Realign wrapped method arguments, chained calls and continuations - Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty` - Flatten the boiler config expression and reindent the remaining touched files --- .../BatteryMonitorTestData.cs | 47 ++- .../BatteryNotificationServiceTests.cs | 90 +++-- .../BatterySensorDiscoveryServiceTests.cs | 80 ++-- BatteryMonitor.Manager/BatteryMonitorInit.cs | 29 +- .../BatteryMonitorServiceRegistration.cs | 20 +- .../BatteryNotificationService.cs | 43 +- .../BatterySensorDiscoveryService.cs | 41 +- .../Interface/IBatteryNotificationService.cs | 4 + .../IBatterySensorDiscoveryService.cs | 4 + .../Models/BatteryMonitorOptions.cs | 4 + .../BoilerControlServiceTests.cs | 53 ++- .../BoilerMonitorConfigTests.cs | 22 +- .../BoilerMonitorEntityServiceTests.cs | 188 +++++---- .../BoilerMonitorOptionsTests.cs | 4 + .../BoilerMonitorTestData.cs | 56 +-- .../WaterReadyServiceTests.cs | 36 +- BoilerMonitor.Manager/BoilerConfigReader.cs | 19 +- BoilerMonitor.Manager/BoilerControlService.cs | 23 +- .../BoilerMonitorEntityService.cs | 247 +++++++----- BoilerMonitor.Manager/BoilerMonitorInit.cs | 252 +++++++----- .../BoilerMonitorServiceRegistration.cs | 24 +- BoilerMonitor.Manager/BoilerRunTimeTracker.cs | 4 + .../Interface/IBoilerControlService.cs | 4 + .../Interface/IBoilerMonitorEntityService.cs | 4 + .../Interface/IBoilerRunTimeTracker.cs | 4 + .../Models/BoilerMonitorConfig.cs | 9 +- BoilerMonitor.Manager/WaterReadyService.cs | 42 +- BoilerMonitor.Models/BoilerMonitorEntity.cs | 4 + HomeAssistant.Entities/EntityManager.cs | 13 +- .../Interfaces/IEntityManager.cs | 6 +- HomeAssistant.Models/EntityCreateModel.cs | 8 +- HomeAssistant.Server/CustomLoggingProvider.cs | 16 +- HomeAssistant.Server/MqttRecreateApp.cs | 63 +-- HomeAssistant.Server/program.cs | 81 ++-- .../LeakMonitorInitTests.cs | 198 ++++----- .../LeakMonitorTestData.cs | 37 +- .../LeakNotificationServiceTests.cs | 119 +++--- LeakMonitor.Manager/LeakMonitorInit.cs | 33 +- .../LeakMonitorServiceRegistration.cs | 14 +- .../LeakNotificationService.cs | 75 ++-- .../Models/LeakMonitorOptions.cs | 4 + .../LightControlServiceTests.cs | 26 +- .../LightMonitorInitTests.cs | 56 +-- .../LightMonitorTestData.cs | 26 +- .../PresenceServiceTests.cs | 30 +- LightMonitor.Manager/LightControlService.cs | 4 + LightMonitor.Manager/LightMonitorInit.cs | 121 +++--- .../LightMonitorServiceRegistration.cs | 18 +- LightMonitor.Manager/PresenceService.cs | 11 +- LightMonitor.Models/LightMonitorOptions.cs | 4 + Mappings/Converters/DateTimeTypeConverter.cs | 6 +- Mappings/GlobalMappingProfile.cs | 6 +- Mappings/NordPoolMappingProfile.cs | 9 +- .../CheapestIntervalsFinderTests.cs | 65 +-- .../CompactNordPoolDayPriceTests.cs | 32 +- .../NordPoolEntityServiceTests.cs | 376 +++++++++++------- NordPool.Manager.Tests/NordPoolInitTests.cs | 84 ++-- .../NordPoolPriceServiceTests.cs | 116 ++++-- NordPool.Manager.Tests/NordPoolTestData.cs | 24 +- NordPool.Manager/CheapestIntervalsFinder.cs | 36 +- .../Interface/ICheapestIntervalsFinder.cs | 10 +- .../INordPoolBoilerConfigProvider.cs | 4 + .../Interface/INordPoolEntityService.cs | 4 + .../Interface/INordPoolPriceService.cs | 4 + .../Models/EntityUpdateContext.cs | 4 + .../NordPoolBoilerConfigProvider.cs | 4 + NordPool.Manager/NordPoolEntityService.cs | 251 +++++++----- NordPool.Manager/NordPoolInit.cs | 43 +- NordPool.Manager/NordPoolPriceService.cs | 55 ++- .../NordPoolServiceRegistration.cs | 15 +- NordPool.Models/CheapestIntervalResult.cs | 16 +- NordPool.Models/CompactNordPoolDayPrice.cs | 30 +- NordPool.Models/Dtos/NordPoolDayPriceDto.cs | 15 +- .../Dtos/NordPoolPriceResultDto.cs | 9 +- NordPool.Models/NordPoolDayPriceExtensions.cs | 4 +- NordPool.Models/NordPoolEntities.cs | 9 +- .../CostAccumulatorTests.cs | 43 +- .../OtherPowerCalculationServiceTests.cs | 18 +- .../PowerCostCalculationServiceTests.cs | 88 ++-- .../PowerLimitEnforcementServiceTests.cs | 79 ++-- .../PowerMonitorEntityServiceTests.cs | 86 ++-- .../PowerMonitorOptionsTests.cs | 4 + .../PowerMonitorTestData.cs | 65 +-- .../PowerSensorDiscoveryServiceTests.cs | 85 ++-- .../IOtherPowerCalculationService.cs | 4 + .../Interface/IPowerCostCalculationService.cs | 4 + .../Interface/IPowerMonitorEntityService.cs | 8 +- .../Interface/IPowerSensorDiscoveryService.cs | 4 + .../Models/CostAccumulator.cs | 8 +- .../Models/PowerMonitorOptions.cs | 4 + .../OtherPowerCalculationService.cs | 12 +- .../PowerCostCalculationService.cs | 26 +- .../PowerLimitEnforcementService.cs | 93 +++-- .../PowerMonitorEntityService.cs | 237 ++++++----- PowerMonitor.Manager/PowerMonitorInit.cs | 121 +++--- .../PowerMonitorServiceRegistration.cs | 18 +- .../PowerNotificationService.cs | 42 +- .../PowerSensorDiscoveryService.cs | 61 ++- PowerMonitor.Models/PowerMonitorEntity.cs | 4 + .../ExhaustFanControlServiceTests.cs | 41 +- .../HumidityRateCalculatorTests.cs | 24 +- .../ShowerDetectionServiceTests.cs | 23 +- .../ShowerMonitorTestData.cs | 18 +- .../ExhaustFanControlService.cs | 30 +- .../HumidityRateCalculator.cs | 23 +- .../Interface/IExhaustFanControlService.cs | 4 + .../Interface/IShowerDetectionService.cs | 4 + .../Interface/IShowerMonitorEntityService.cs | 4 + .../Models/ShowerMonitorOptions.cs | 4 + .../Models/ShowerMonitorUpdateContext.cs | 4 + .../ShowerDetectionService.cs | 47 ++- .../ShowerMonitorEntityService.cs | 102 +++-- ShowerMonitor.Manager/ShowerMonitorInit.cs | 53 ++- .../ShowerMonitorServiceRegistration.cs | 24 +- ShowerMonitor.Models/ShowerMonitorEntity.cs | 4 + 115 files changed, 3115 insertions(+), 1959 deletions(-) diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs index 35f90f7..3d8a85d 100644 --- a/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs +++ b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using System.Text.Json; using BatteryMonitor.Models; @@ -5,6 +7,8 @@ using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace BatteryMonitor.Manager.Tests; /// @@ -20,7 +24,7 @@ internal static class BatteryMonitorTestData /// (threshold, state, expected) rows straddling the strict level < threshold /// boundary, including zero/negative thresholds and int min/max thresholds. /// - public static TheoryData ThresholdBoundaryRows { get; } = new() + public static TheoryData ThresholdBoundaryRows { get; } = new TheoryData { { 5, "4", true }, { 5, "5", false }, @@ -59,7 +63,7 @@ internal static class BatteryMonitorTestData "unknown", "UNAVAILABLE", "UNKNOWN", - "", + string.Empty, " ", "\t", "not_a_number", @@ -85,8 +89,10 @@ internal static class BatteryMonitorTestData } /// A sensor with an arbitrary (or missing) device class. - public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, - string? friendlyName = DefaultFriendlyName) + public static EntitySpec Sensor(string entityId, + string? deviceClass, + string? state, + string? friendlyName = DefaultFriendlyName) { return new EntitySpec { @@ -101,9 +107,15 @@ internal static class BatteryMonitorTestData { var attributes = new Dictionary(StringComparer.Ordinal); - if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass; + if (spec.DeviceClass is not null) + { + attributes["device_class"] = spec.DeviceClass; + } - if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName; + if (spec.FriendlyName is not null) + { + attributes["friendly_name"] = spec.FriendlyName; + } return new EntityState { @@ -122,7 +134,10 @@ internal static class BatteryMonitorTestData foreach (var spec in entities) { - if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec)); + if (spec.HasState) + { + haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec)); + } entityList.Add(new Entity(haContextMock.Object, spec.EntityId)); } @@ -159,10 +174,10 @@ internal static class BatteryMonitorTestData return [ .. Enumerable.Range(0, count) - .Select(i => Battery( - $"sensor.generated_battery_{i:D3}", - i.ToString(CultureInfo.InvariantCulture), - $"Generated Battery {i:D3}")) + .Select(i => Battery( + $"sensor.generated_battery_{i:D3}", + i.ToString(CultureInfo.InvariantCulture), + $"Generated Battery {i:D3}")) ]; } @@ -175,10 +190,10 @@ internal static class BatteryMonitorTestData return [ .. Enumerable.Range(0, count) - .Select(i => CreateSensorInfo( - $"sensor.generated_{i:D3}", - i * 37 % 101, - $"Generated Device {i:D3}")) + .Select(i => CreateSensorInfo( + $"sensor.generated_{i:D3}", + i * 37 % 101, + $"Generated Device {i:D3}")) ]; } @@ -202,7 +217,7 @@ internal static class BatteryMonitorTestData data.Add("sensor.boiler_temp_battery", false); data.Add("sensor.aquarium_leak_sensor_battery", false); data.Add("sensor.temperature", false); - data.Add("", false); + data.Add(string.Empty, false); data.Add(" ", false); return data; diff --git a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs index a27aa94..08163f7 100644 --- a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs +++ b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs @@ -1,3 +1,5 @@ +#region + using System.Text.Json; using BatteryMonitor.Models; using BatteryMonitorManager; @@ -8,12 +10,14 @@ using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; +#endregion + namespace BatteryMonitor.Manager.Tests; public class BatteryNotificationServiceTests { - private readonly Mock _haContextMock = new(); - private readonly Mock> _loggerMock = new(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock> _loggerMock = new Mock>(); private BatteryNotificationService CreateSut() { @@ -23,10 +27,10 @@ public class BatteryNotificationServiceTests private void VerifyCallService(string service, Times times) { _haContextMock.Verify(h => h.CallService( - BatteryMonitorConsts.PersistentNotificationDomain, - service, - It.IsAny(), - It.IsAny()), times); + BatteryMonitorConsts.PersistentNotificationDomain, + service, + It.IsAny(), + It.IsAny()), times); } #region NotifyLowBattery @@ -38,7 +42,7 @@ public class BatteryNotificationServiceTests var devices = CreateSensorInfos( [ .. Enumerable.Range(0, deviceCount) - .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5))) + .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5))) ]); var sut = CreateSut(); @@ -54,17 +58,18 @@ public class BatteryNotificationServiceTests public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray) { IReadOnlyList devices = useArray - ? Array.Empty() - : new List(); + ? Array.Empty() + : new List(); var sut = CreateSut(); sut.NotifyLowBattery(devices); _haContextMock.Verify(h => h.CallService( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny()), Times.Never); + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny()), Times.Never); + _loggerMock.Invocations.Should().BeEmpty(); } @@ -72,18 +77,20 @@ public class BatteryNotificationServiceTests public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary() { object? payload = null; + _haContextMock - .Setup(h => h.CallService( - BatteryMonitorConsts.PersistentNotificationDomain, - BatteryMonitorConsts.PersistentNotificationCreateService, - It.IsAny(), - It.IsAny())) - .Callback((_, _, _, data) => payload = data); + .Setup(h => h.CallService( + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationCreateService, + It.IsAny(), + It.IsAny())) + .Callback((_, _, _, data) => payload = data); var sut = CreateSut(); + sut.NotifyLowBattery(CreateSensorInfos( - ("sensor.a", "Device A", 4), - ("sensor.b", "Device B", 1))); + ("sensor.a", "Device A", 4), + ("sensor.b", "Device B", 1))); payload.Should().NotBeNull(); @@ -101,16 +108,19 @@ public class BatteryNotificationServiceTests public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount() { _loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true); + var devices = CreateSensorInfos( - ("sensor.a", "Device A", 2), - ("sensor.b", "Device B", 3)); + ("sensor.a", "Device A", 2), + ("sensor.b", "Device B", 3)); var sut = CreateSut(); sut.NotifyLowBattery(devices); var logInvocation = _loggerMock.Invocations - .Where(invocation => invocation.Method.Name == nameof(ILogger.Log)) - .Should().ContainSingle().Subject; + .Where(invocation => invocation.Method.Name == nameof(ILogger.Log)) + .Should() + .ContainSingle() + .Subject; logInvocation.Arguments[0].Should().Be(LogLevel.Information); logInvocation.Arguments[2].Should().NotBeNull(); @@ -139,7 +149,10 @@ public class BatteryNotificationServiceTests { var sut = CreateSut(); - for (var i = 0; i < calls; i++) sut.DismissNotification(); + for (var i = 0; i < calls; i++) + { + sut.DismissNotification(); + } VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls)); VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never()); @@ -153,9 +166,9 @@ public class BatteryNotificationServiceTests public void BuildNotificationMessage_ShouldOrderByBatteryLevel() { var devices = CreateSensorInfos( - ("sensor.a", "Device A", 4), - ("sensor.b", "Device B", 1), - ("sensor.c", "Device C", 3)); + ("sensor.a", "Device A", 4), + ("sensor.b", "Device B", 1), + ("sensor.c", "Device C", 3)); var message = BatteryNotificationService.BuildNotificationMessage(devices); @@ -170,9 +183,9 @@ public class BatteryNotificationServiceTests public void BuildNotificationMessage_ShouldKeepInsertionOrderForEqualLevels() { var devices = CreateSensorInfos( - ("sensor.first", "First Device", 4), - ("sensor.second", "Second Device", 4), - ("sensor.third", "Third Device", 1)); + ("sensor.first", "First Device", 4), + ("sensor.second", "Second Device", 4), + ("sensor.third", "Third Device", 1)); var message = BatteryNotificationService.BuildNotificationMessage(devices); @@ -191,8 +204,8 @@ public class BatteryNotificationServiceTests var message = BatteryNotificationService.BuildNotificationMessage(devices); var expectedLines = devices - .OrderBy(d => d.BatteryLevel) - .Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%"); + .OrderBy(d => d.BatteryLevel) + .Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%"); var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); lines.Should().HaveCount(devices.Count + 1); @@ -219,8 +232,9 @@ public class BatteryNotificationServiceTests [InlineData("Full Battery", 100, "- **Full Battery**: 100%")] [InlineData("", 5, "- ****: 5%")] [InlineData(" ", 4, "- ** **: 4%")] - public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel, - string expectedLine) + public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, + double batteryLevel, + string expectedLine) { var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel)); @@ -256,8 +270,8 @@ public class BatteryNotificationServiceTests public void BuildNotificationMessage_WithDuplicateDevices_ShouldListEveryDevice() { var devices = CreateSensorInfos( - ("sensor.duplicate_battery", "Duplicate Battery", 2), - ("sensor.duplicate_battery", "Duplicate Battery", 2)); + ("sensor.duplicate_battery", "Duplicate Battery", 2), + ("sensor.duplicate_battery", "Duplicate Battery", 2)); var message = BatteryNotificationService.BuildNotificationMessage(devices); diff --git a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs index 7b76a42..aec3f17 100644 --- a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs +++ b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using BatteryMonitor.Models; using BatteryMonitorManager; @@ -8,12 +10,14 @@ using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; +#endregion + namespace BatteryMonitor.Manager.Tests; public class BatterySensorDiscoveryServiceTests { - private readonly Mock _haContextMock = new(); - private readonly Mock> _loggerMock = new(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock> _loggerMock = new Mock>(); private BatterySensorDiscoveryService CreateSut() { @@ -42,10 +46,10 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices() { SetupEntities( - Battery("sensor.bathroom_battery", "3", "Bathroom Battery"), - Battery("sensor.bedroom_battery", "80", "Bedroom Battery"), - Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery") - ); + Battery("sensor.bathroom_battery", "3", "Bathroom Battery"), + Battery("sensor.bedroom_battery", "80", "Bedroom Battery"), + Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery") + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -70,9 +74,9 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_ShouldExcludePersonalDevices(string excludedEntityId, string friendlyName) { SetupEntities( - Battery("sensor.bathroom_battery", "2", "Bathroom Battery"), - Battery(excludedEntityId, "1", friendlyName) - ); + Battery("sensor.bathroom_battery", "2", "Bathroom Battery"), + Battery(excludedEntityId, "1", friendlyName) + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -89,12 +93,12 @@ public class BatterySensorDiscoveryServiceTests [InlineData("sensorx.bathroom_battery", "battery")] [InlineData("switch.bathroom_battery", "battery")] public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId, - string? deviceClass) + string? deviceClass) { SetupEntities( - Sensor(entityId, deviceClass, "2", "Ignored Entity"), - Battery("sensor.bedroom_battery", "3", "Bedroom Battery") - ); + Sensor(entityId, deviceClass, "2", "Ignored Entity"), + Battery("sensor.bedroom_battery", "3", "Bedroom Battery") + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -108,9 +112,9 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state) { SetupEntities( - Battery("sensor.bathroom_battery", state, "Bathroom Battery"), - Battery("sensor.bedroom_battery", "3", "Bedroom Battery") - ); + Battery("sensor.bathroom_battery", state, "Bathroom Battery"), + Battery("sensor.bedroom_battery", "3", "Bedroom Battery") + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -123,10 +127,10 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor() { SetupEntities( - new EntitySpec - { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false }, - Battery("sensor.bedroom_battery", "3", "Bedroom Battery") - ); + new EntitySpec + { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false }, + Battery("sensor.bedroom_battery", "3", "Bedroom Battery") + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -137,8 +141,9 @@ public class BatterySensorDiscoveryServiceTests [Theory] [MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))] - public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state, - bool expectedIncluded) + public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, + string state, + bool expectedIncluded) { SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery")); @@ -147,7 +152,10 @@ public class BatterySensorDiscoveryServiceTests result.Should().HaveCount(expectedIncluded ? 1 : 0); - if (!expectedIncluded) return; + if (!expectedIncluded) + { + return; + } result[0].EntityId.Should().Be("sensor.boundary_battery"); result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture)); @@ -157,9 +165,9 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty() { SetupEntities( - Sensor("sensor.temperature", "temperature", "22", "Temperature"), - Sensor("switch.some_switch", null, "on", "Switch") - ); + Sensor("sensor.temperature", "temperature", "22", "Temperature"), + Sensor("switch.some_switch", null, "on", "Switch") + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -171,10 +179,10 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty() { SetupEntities( - Battery("sensor.bathroom_battery", "5", "Bathroom Battery"), - Battery("sensor.bedroom_battery", "50", "Bedroom Battery"), - Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery") - ); + Battery("sensor.bathroom_battery", "5", "Bathroom Battery"), + Battery("sensor.bedroom_battery", "50", "Bedroom Battery"), + Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery") + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -198,9 +206,9 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence() { SetupEntities( - Battery("sensor.duplicate_battery", "2", "Duplicate Battery"), - Battery("sensor.duplicate_battery", "2", "Duplicate Battery") - ); + Battery("sensor.duplicate_battery", "2", "Duplicate Battery"), + Battery("sensor.duplicate_battery", "2", "Duplicate Battery") + ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); @@ -250,8 +258,10 @@ public class BatterySensorDiscoveryServiceTests result.Should().HaveCount(7); result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i)); - result.Select(s => s.FriendlyName).Should() - .OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal)); + + result.Select(s => s.FriendlyName) + .Should() + .OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal)); } #endregion diff --git a/BatteryMonitor.Manager/BatteryMonitorInit.cs b/BatteryMonitor.Manager/BatteryMonitorInit.cs index 56fcec8..d0800b5 100644 --- a/BatteryMonitor.Manager/BatteryMonitorInit.cs +++ b/BatteryMonitor.Manager/BatteryMonitorInit.cs @@ -1,3 +1,5 @@ +#region + using System.Reactive.Concurrency; using BatteryMonitor.Models; using BatteryMonitorManager.Interface; @@ -7,6 +9,8 @@ using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; +#endregion + namespace BatteryMonitorManager; [NetDaemonApp] @@ -58,12 +62,13 @@ public sealed class BatteryMonitorInit if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", - _options.BatteryThresholdPercent); + _options.BatteryThresholdPercent); } } catch (Exception ex) { _logger.LogError(ex, "Error initializing BatteryMonitor"); + throw; } } @@ -71,17 +76,17 @@ public sealed class BatteryMonitorInit private void ScheduleDailyCheck() { _scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () => - { - try - { - _logger.LogInformation("Running scheduled daily battery check"); - CheckAndNotify(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error during scheduled battery check"); - } - }); + { + try + { + _logger.LogInformation("Running scheduled daily battery check"); + CheckAndNotify(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during scheduled battery check"); + } + }); _logger.LogInformation("Scheduled daily battery check at 08:00"); } diff --git a/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs index 5608f34..06bf446 100644 --- a/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs +++ b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs @@ -1,9 +1,13 @@ +#region + using BatteryMonitorManager.Interface; using BatteryMonitorManager.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; +#endregion + namespace BatteryMonitorManager; public static class BatteryMonitorServiceRegistration @@ -11,15 +15,19 @@ public static class BatteryMonitorServiceRegistration public static IServiceCollection AddBatteryMonitor(this IServiceCollection services, IConfiguration configuration) { var options = configuration - .GetSection(BatteryMonitorOptions.SectionName) - .Get() ?? new BatteryMonitorOptions(); + .GetSection(BatteryMonitorOptions.SectionName) + .Get() ?? + new BatteryMonitorOptions(); - if (!options.Enabled) return services; + if (!options.Enabled) + { + return services; + } services - .AddNetDaemonApp() - .AddScoped() - .AddScoped(); + .AddNetDaemonApp() + .AddScoped() + .AddScoped(); return services; } diff --git a/BatteryMonitor.Manager/BatteryNotificationService.cs b/BatteryMonitor.Manager/BatteryNotificationService.cs index 4566dc2..928385f 100644 --- a/BatteryMonitor.Manager/BatteryNotificationService.cs +++ b/BatteryMonitor.Manager/BatteryNotificationService.cs @@ -1,9 +1,13 @@ +#region + using System.Text; using BatteryMonitor.Models; using BatteryMonitorManager.Interface; using Microsoft.Extensions.Logging; using NetDaemon.HassModel; +#endregion + namespace BatteryMonitorManager; public sealed class BatteryNotificationService( @@ -12,37 +16,40 @@ public sealed class BatteryNotificationService( { public void NotifyLowBattery(IReadOnlyList lowBatteryDevices) { - if (lowBatteryDevices.Count == 0) return; + if (lowBatteryDevices.Count == 0) + { + return; + } var message = BuildNotificationMessage(lowBatteryDevices); haContext.CallService( - BatteryMonitorConsts.PersistentNotificationDomain, - BatteryMonitorConsts.PersistentNotificationCreateService, - data: new - { - title = BatteryMonitorConsts.NotificationTitle, - message, - notification_id = BatteryMonitorConsts.NotificationId - }); + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationCreateService, + data: new + { + title = BatteryMonitorConsts.NotificationTitle, + message, + notification_id = BatteryMonitorConsts.NotificationId + }); if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "Sent low battery notification for {Count} device(s)", - lowBatteryDevices.Count); + "Sent low battery notification for {Count} device(s)", + lowBatteryDevices.Count); } } public void DismissNotification() { haContext.CallService( - BatteryMonitorConsts.PersistentNotificationDomain, - BatteryMonitorConsts.PersistentNotificationDismissService, - data: new - { - notification_id = BatteryMonitorConsts.NotificationId - }); + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationDismissService, + data: new + { + notification_id = BatteryMonitorConsts.NotificationId + }); logger.LogDebug("Dismissed low battery notification"); } @@ -54,7 +61,9 @@ public sealed class BatteryNotificationService( sb.AppendLine(); foreach (var device in devices.OrderBy(d => d.BatteryLevel)) + { sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%"); + } return sb.ToString().TrimEnd(); } diff --git a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs index 85b5cdd..51767fe 100644 --- a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs +++ b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using System.Text.Json; using BatteryMonitor.Models; @@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace BatteryMonitorManager; public sealed class BatterySensorDiscoveryService( @@ -17,17 +21,17 @@ public sealed class BatterySensorDiscoveryService( var allEntities = haContext.GetAllEntities(); var lowBatterySensors = allEntities - .Where(IsBatterySensor) - .Where(e => !IsExcludedDevice(e.EntityId)) - .Select(e => TryCreateSensorInfo(e, thresholdPercent)) - .Where(info => info is not null) - .ToList(); + .Where(IsBatterySensor) + .Where(e => !IsExcludedDevice(e.EntityId)) + .Select(e => TryCreateSensorInfo(e, thresholdPercent)) + .Where(info => info is not null) + .ToList(); if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "Battery check: found {Count} sensors below {Threshold}%", - lowBatterySensors.Count, thresholdPercent); + "Battery check: found {Count} sensors below {Threshold}%", + lowBatterySensors.Count, thresholdPercent); } return lowBatterySensors!; @@ -50,7 +54,7 @@ public sealed class BatterySensorDiscoveryService( var lowerEntityId = entityId.ToLowerInvariant(); return BatteryMonitorConsts.ExcludedKeywords - .Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase)); + .Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase)); } private BatterySensorInfo? TryCreateSensorInfo(Entity entity, int thresholdPercent) @@ -62,7 +66,7 @@ public sealed class BatterySensorDiscoveryService( if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, - state ?? "null"); + state ?? "null"); } return null; @@ -73,16 +77,18 @@ public sealed class BatterySensorDiscoveryService( if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, - state); + state); } return null; } - if (batteryLevel >= thresholdPercent) return null; + if (batteryLevel >= thresholdPercent) + { + return null; + } - var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") - ?? entity.EntityId; + var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId; return new BatterySensorInfo { @@ -94,10 +100,13 @@ public sealed class BatterySensorDiscoveryService( private static string? GetJsonStringProperty(JsonElement? element, string propertyName) { - if (element is null) return null; + if (element is null) + { + return null; + } return element.Value.TryGetProperty(propertyName, out var value) - ? value.GetString() - : null; + ? value.GetString() + : null; } } \ No newline at end of file diff --git a/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs index 54caf3b..cdd4357 100644 --- a/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs +++ b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs @@ -1,5 +1,9 @@ +#region + using BatteryMonitor.Models; +#endregion + namespace BatteryMonitorManager.Interface; public interface IBatteryNotificationService diff --git a/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs index af41652..5e5d132 100644 --- a/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs +++ b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs @@ -1,5 +1,9 @@ +#region + using BatteryMonitor.Models; +#endregion + namespace BatteryMonitorManager.Interface; public interface IBatterySensorDiscoveryService diff --git a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs index 34d00d4..2899b5e 100644 --- a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs +++ b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs @@ -1,5 +1,9 @@ +#region + using BatteryMonitor.Models; +#endregion + namespace BatteryMonitorManager.Models; public sealed class BatteryMonitorOptions diff --git a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs index e20a70c..62fb80b 100644 --- a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs @@ -1,14 +1,18 @@ +#region + using BoilerMonitor.Models.Enums; using BoilerMonitorManager; using FluentAssertions; using Microsoft.Extensions.Logging; using Moq; +#endregion + namespace BoilerMonitor.Manager.Tests; public class BoilerControlServiceTests { - private readonly Mock> _loggerMock = new(); + private readonly Mock> _loggerMock = new Mock>(); private BoilerControlService CreateSut() { @@ -34,8 +38,9 @@ public class BoilerControlServiceTests bool budgetExhausted, bool budgetOverride) { - var result = CreateSut().DetermineAction( - isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride); + var result = CreateSut() + .DetermineAction( + isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride); result.Should().Be(BoilerAction.NoChange); } @@ -57,9 +62,10 @@ public class BoilerControlServiceTests [InlineData("0")] public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState) { - var result = CreateSut().DetermineAction( - true, false, switchState, - false, false); + var result = CreateSut() + .DetermineAction( + true, false, switchState, + false, false); result.Should().Be(BoilerAction.TurnOn); } @@ -75,9 +81,10 @@ public class BoilerControlServiceTests string? switchState, BoilerAction expectedAction) { - var result = CreateSut().DetermineAction( - true, false, switchState, - true, true); + var result = CreateSut() + .DetermineAction( + true, false, switchState, + true, true); result.Should().Be(expectedAction); } @@ -93,9 +100,10 @@ public class BoilerControlServiceTests [InlineData("oN")] public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState) { - var result = CreateSut().DetermineAction( - false, false, switchState, - false, false); + var result = CreateSut() + .DetermineAction( + false, false, switchState, + false, false); result.Should().Be(BoilerAction.TurnOff); } @@ -109,9 +117,10 @@ public class BoilerControlServiceTests bool budgetExhausted, bool budgetOverride) { - var result = CreateSut().DetermineAction( - true, waterReady, "on", - budgetExhausted, budgetOverride); + var result = CreateSut() + .DetermineAction( + true, waterReady, "on", + budgetExhausted, budgetOverride); result.Should().Be(BoilerAction.TurnOff); } @@ -124,7 +133,7 @@ public class BoilerControlServiceTests /// Complete truth table for a boiler that is currently ON: it may only stay on when /// it is cheap, water is not ready and the budget is available (or overridden). /// - public static TheoryData SwitchOnActionMatrix => new() + public static TheoryData SwitchOnActionMatrix => new TheoryData { { false, false, false, false, BoilerAction.TurnOff }, { false, false, false, true, BoilerAction.TurnOff }, @@ -153,8 +162,9 @@ public class BoilerControlServiceTests bool budgetOverride, BoilerAction expectedAction) { - var result = CreateSut().DetermineAction( - isNowCheap, waterReady, "on", budgetExhausted, budgetOverride); + var result = CreateSut() + .DetermineAction( + isNowCheap, waterReady, "on", budgetExhausted, budgetOverride); result.Should().Be(expectedAction); } @@ -163,7 +173,7 @@ public class BoilerControlServiceTests /// Complete truth table for a boiler that is currently OFF: it may only turn on when /// it is cheap, water is not ready and the budget is available (or overridden). /// - public static TheoryData SwitchOffActionMatrix => new() + public static TheoryData SwitchOffActionMatrix => new TheoryData { { false, false, false, false, BoilerAction.NoChange }, { false, false, false, true, BoilerAction.NoChange }, @@ -192,8 +202,9 @@ public class BoilerControlServiceTests bool budgetOverride, BoilerAction expectedAction) { - var result = CreateSut().DetermineAction( - isNowCheap, waterReady, "off", budgetExhausted, budgetOverride); + var result = CreateSut() + .DetermineAction( + isNowCheap, waterReady, "off", budgetExhausted, budgetOverride); result.Should().Be(expectedAction); } diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs index 8982bf8..d1981ae 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs @@ -1,5 +1,9 @@ +#region + using FluentAssertions; +#endregion + namespace BoilerMonitor.Manager.Tests; public class BoilerMonitorConfigTests @@ -7,7 +11,7 @@ public class BoilerMonitorConfigTests private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId; private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId; - public static TheoryData ConfigurationCases => new() + public static TheoryData ConfigurationCases => new TheoryData { { "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true }, { "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true }, @@ -18,11 +22,11 @@ public class BoilerMonitorConfigTests { "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true }, { "power entity id null", null, SwitchEntityId, 30, 5.0, false }, - { "power entity id empty", "", SwitchEntityId, 30, 5.0, false }, + { "power entity id empty", string.Empty, SwitchEntityId, 30, 5.0, false }, { "power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false }, { "power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false }, { "switch entity id null", PowerEntityId, null, 30, 5.0, false }, - { "switch entity id empty", PowerEntityId, "", 30, 5.0, false }, + { "switch entity id empty", PowerEntityId, string.Empty, 30, 5.0, false }, { "switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false }, { "both entity ids null", null, null, 30, 5.0, false }, @@ -50,10 +54,10 @@ public class BoilerMonitorConfigTests bool expected) { var config = BoilerMonitorTestData.CreateConfig( - powerEntityId, - switchEntityId, - pollIntervalSeconds, - heatingPowerThresholdWatts); + powerEntityId, + switchEntityId, + pollIntervalSeconds, + heatingPowerThresholdWatts); config.IsFullyConfigured.Should().Be(expected, scenario); } @@ -62,8 +66,8 @@ public class BoilerMonitorConfigTests public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding() { var config = BoilerMonitorTestData.CreateConfig( - " sensor.sonoff_1002230e32_power ", - "SWITCH.SONOFF_1002230E32"); + " sensor.sonoff_1002230e32_power ", + "SWITCH.SONOFF_1002230E32"); config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content"); } diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs index 49bfa5a..b24b2a7 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs @@ -1,3 +1,5 @@ +#region + using System.Text.Json; using BoilerMonitorManager; using FluentAssertions; @@ -8,6 +10,8 @@ using Moq; using NetDaemon.HassModel; using static BoilerMonitor.Models.BoilerMonitorConsts; +#endregion + namespace BoilerMonitor.Manager.Tests; public class BoilerMonitorEntityServiceTests @@ -31,28 +35,31 @@ public class BoilerMonitorEntityServiceTests AutoManagementEntityId ]; - private readonly Mock _entityManagerMock = new(); - private readonly Mock _haContextMock = new(); - private readonly Mock> _loggerMock = new(); + private readonly Mock _entityManagerMock = new Mock(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock> _loggerMock = new Mock>(); public BoilerMonitorEntityServiceTests() { _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); } private BoilerMonitorEntityService CreateSut() { return new BoilerMonitorEntityService( - _entityManagerMock.Object, - _haContextMock.Object, - _loggerMock.Object); + _entityManagerMock.Object, + _haContextMock.Object, + _loggerMock.Object); } #region ReadPersistedState @@ -64,13 +71,14 @@ public class BoilerMonitorEntityServiceTests TimeSpan? expectedRunTime) { _haContextMock.SetupEntityStates( - BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2")); + BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2")); var result = CreateSut().ReadPersistedState(); if (expectedRunTime is null) { result.Should().BeNull(); + return; } @@ -86,13 +94,14 @@ public class BoilerMonitorEntityServiceTests int? expectedSessionCount) { _haContextMock.SetupEntityStates( - BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState)); + BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState)); var result = CreateSut().ReadPersistedState(); if (expectedSessionCount is null) { result.Should().BeNull(); + return; } @@ -105,7 +114,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues() { _haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates( - "7200", "3", "ON")); + "7200", "3", "ON")); var result = CreateSut().ReadPersistedState(); @@ -125,7 +134,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState) { _haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates( - skipPriceCap: switchState, budgetOverride: switchState)); + skipPriceCap: switchState, budgetOverride: switchState)); var result = CreateSut().ReadPersistedState(); @@ -138,7 +147,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull() { _haContextMock.SetupEntityStates( - BoilerMonitorTestData.CreatePersistedEntityStates(null, null)); + BoilerMonitorTestData.CreatePersistedEntityStates(null, null)); CreateSut().ReadPersistedState().Should().BeNull(); } @@ -151,9 +160,10 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp() { var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30); + _haContextMock.SetupEntityState( - WaterReadyEntityId, - BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O"))); + WaterReadyEntityId, + BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O"))); var result = CreateSut().ReadPersistedCooldownTimestamp(); @@ -164,9 +174,10 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp() { var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero); + _haContextMock.SetupEntityState( - WaterReadyEntityId, - BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z")); + WaterReadyEntityId, + BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z")); var result = CreateSut().ReadPersistedCooldownTimestamp(); @@ -193,9 +204,9 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull() { _haContextMock.SetupEntityState( - WaterReadyEntityId, - BoilerMonitorTestData.CreateEntityStateWithAttributes( - new Dictionary { ["friendly_name"] = "Boiler water ready" })); + WaterReadyEntityId, + BoilerMonitorTestData.CreateEntityStateWithAttributes( + new Dictionary { ["friendly_name"] = "Boiler water ready" })); CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); } @@ -212,8 +223,8 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince) { _haContextMock.SetupEntityState( - WaterReadyEntityId, - BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince)); + WaterReadyEntityId, + BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince)); CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); } @@ -222,7 +233,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull() { _haContextMock.Setup(h => h.GetState(WaterReadyEntityId)) - .Throws(new InvalidOperationException("Home Assistant unavailable")); + .Throws(new InvalidOperationException("Home Assistant unavailable")); CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); } @@ -245,12 +256,12 @@ public class BoilerMonitorEntityServiceTests public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting() { var context = BoilerMonitorTestData.CreateUpdateContext( - TimeSpan.FromSeconds(3723.9), - TimeSpan.FromSeconds(42.9), - 150.0, - true, - 4, - waterReady: true); + TimeSpan.FromSeconds(3723.9), + TimeSpan.FromSeconds(42.9), + 150.0, + true, + 4, + waterReady: true); await CreateSut().UpdateEntitiesAsync(context); @@ -260,8 +271,9 @@ public class BoilerMonitorEntityServiceTests _entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), - Times.Exactly(5)); + Times.Exactly(5)); } [Theory] @@ -276,11 +288,12 @@ public class BoilerMonitorEntityServiceTests double budgetPercentage, string expectedState) { - await CreateSut().UpdateEntitiesAsync( - BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage)); + await CreateSut() + .UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage)); _entityManagerMock.Verify( - em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once); + em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once); } [Theory] @@ -291,8 +304,9 @@ public class BoilerMonitorEntityServiceTests [InlineData(3600, "3600")] public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState) { - await CreateSut().UpdateEntitiesAsync( - BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds))); + await CreateSut() + .UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds))); _entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once); } @@ -305,8 +319,9 @@ public class BoilerMonitorEntityServiceTests [InlineData(86_400.0, "86400")] public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState) { - await CreateSut().UpdateEntitiesAsync( - BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds))); + await CreateSut() + .UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds))); _entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once); } @@ -315,15 +330,17 @@ public class BoilerMonitorEntityServiceTests public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes() { object? capturedAttributes = null; - _entityManagerMock - .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny())) - .Callback((_, attributes) => capturedAttributes = attributes) - .Returns(Task.CompletedTask); - await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext( - waterReady: false, - boilerSwitchState: null, - boilerPowerWatts: 1234.5)); + _entityManagerMock + .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny())) + .Callback((_, attributes) => capturedAttributes = attributes) + .Returns(Task.CompletedTask); + + await CreateSut() + .UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext( + waterReady: false, + boilerSwitchState: null, + boilerPowerWatts: 1234.5)); capturedAttributes.Should().NotBeNull(); var attributes = JsonSerializer.SerializeToElement(capturedAttributes!); @@ -338,13 +355,15 @@ public class BoilerMonitorEntityServiceTests { var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15); object? capturedAttributes = null; - _entityManagerMock - .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny())) - .Callback((_, attributes) => capturedAttributes = attributes) - .Returns(Task.CompletedTask); - await CreateSut().UpdateEntitiesAsync( - BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince)); + _entityManagerMock + .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny())) + .Callback((_, attributes) => capturedAttributes = attributes) + .Returns(Task.CompletedTask); + + await CreateSut() + .UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince)); var attributes = JsonSerializer.SerializeToElement(capturedAttributes!); attributes.GetProperty("cooldown_since").GetString().Should().Be(cooldownSince.ToString("O")); @@ -358,49 +377,54 @@ public class BoilerMonitorEntityServiceTests public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce() { var createdEntityIds = new List(); + _entityManagerMock - .Setup(em => em.CreateEntityAsync(It.IsAny())) - .Callback(entity => createdEntityIds.Add(entity.EntityId)) - .Returns(Task.CompletedTask); + .Setup(em => em.CreateEntityAsync(It.IsAny())) + .Callback(entity => createdEntityIds.Add(entity.EntityId)) + .Returns(Task.CompletedTask); await CreateSut().CreateEntitiesAsync(); createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems(); - createdEntityIds.Should().Contain( - [ - ConfigPowerEntityId, - ConfigSwitchEntityId, - ConfigPollIntervalEntityId, - ConfigHeatingThresholdEntityId, - CleanupButtonEntityId, - WaterReadyEntityId, - TodayRuntimeEntityId, - BudgetExhaustedEntityId, - AutoManagementEntityId - ]); + + createdEntityIds.Should() + .Contain( + [ + ConfigPowerEntityId, + ConfigSwitchEntityId, + ConfigPollIntervalEntityId, + ConfigHeatingThresholdEntityId, + CleanupButtonEntityId, + WaterReadyEntityId, + TodayRuntimeEntityId, + BudgetExhaustedEntityId, + AutoManagementEntityId + ]); } [Fact] public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity() { _entityManagerMock - .Setup(em => - em.CreateEntityAsync(It.Is(entity => entity.EntityId == CleanupButtonEntityId))) - .ThrowsAsync(new InvalidOperationException("MQTT unavailable")); + .Setup(em => + em.CreateEntityAsync(It.Is(entity => entity.EntityId == CleanupButtonEntityId))) + .ThrowsAsync(new InvalidOperationException("MQTT unavailable")); var act = () => CreateSut().CreateEntitiesAsync(); await act.Should().NotThrowAsync(); + _entityManagerMock.Invocations - .Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync)) - .Should().Be(15); + .Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync)) + .Should() + .Be(15); } #endregion #region ResetEntitiesAsync - public static TheoryData ResetEntityStates => new() + public static TheoryData ResetEntityStates => new TheoryData { { StatusEntityId, StatusAwaitingConfiguration }, { WaterReadyEntityId, "unknown" }, @@ -422,16 +446,17 @@ public class BoilerMonitorEntityServiceTests _entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(10)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), - Times.Exactly(5)); + Times.Exactly(5)); } [Fact] public async Task ResetEntitiesAsync_WhenEntityManagerThrows_ShouldNotThrow() { _entityManagerMock - .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("MQTT unavailable")); + .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("MQTT unavailable")); var act = () => CreateSut().ResetEntitiesAsync(); @@ -486,7 +511,9 @@ public class BoilerMonitorEntityServiceTests await CreateSut().CleanupEntitiesAsync(); foreach (var entityId in CleanableEntityIds) + { _entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once); + } _entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never); _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(CleanableEntityIds.Length)); @@ -496,8 +523,8 @@ public class BoilerMonitorEntityServiceTests public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow() { _entityManagerMock - .Setup(em => em.RemoveEntity(It.IsAny())) - .Throws(new InvalidOperationException("MQTT unavailable")); + .Setup(em => em.RemoveEntity(It.IsAny())) + .Throws(new InvalidOperationException("MQTT unavailable")); var act = () => CreateSut().CleanupEntitiesAsync(); @@ -536,12 +563,13 @@ public class BoilerMonitorEntityServiceTests { var canceledToken = new CancellationToken(true); var sut = CreateSut(); + Func act = operation switch { CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken), CancelableOperation.ResetEntities => () => sut.ResetEntitiesAsync(canceledToken), CancelableOperation.UpdateEntities => () => sut.UpdateEntitiesAsync( - BoilerMonitorTestData.CreateUpdateContext(), canceledToken), + BoilerMonitorTestData.CreateUpdateContext(), canceledToken), CancelableOperation.ResetTransientEntities => () => sut.ResetTransientEntitiesAsync(canceledToken), _ => () => sut.CleanupEntitiesAsync(canceledToken) }; diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs index aa9d928..3502de7 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs @@ -1,6 +1,10 @@ +#region + using BoilerMonitorManager.Models; using FluentAssertions; +#endregion + namespace BoilerMonitor.Manager.Tests; public class BoilerMonitorOptionsTests diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs index eb4ef83..6ff128b 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs @@ -1,3 +1,5 @@ +#region + using System.Text.Json; using BoilerMonitorManager.Models; using Microsoft.Extensions.Time.Testing; @@ -6,6 +8,8 @@ using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using static BoilerMonitor.Models.BoilerMonitorConsts; +#endregion + namespace BoilerMonitor.Manager.Tests; /// @@ -19,7 +23,7 @@ internal static class BoilerMonitorTestData public const string SwitchEntityId = "switch.sonoff_1002230e32"; /// Fixed "now" (UTC) used by every time based test. - public static readonly DateTimeOffset BaseTime = new(2026, 3, 31, 12, 0, 0, TimeSpan.Zero); + public static readonly DateTimeOffset BaseTime = new DateTimeOffset(2026, 3, 31, 12, 0, 0, TimeSpan.Zero); public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) { @@ -147,7 +151,7 @@ internal static class BoilerMonitorTestData data.Add("1e9", TimeSpan.FromSeconds(1e9)); data.Add(null, null); - data.Add("", null); + data.Add(string.Empty, null); data.Add(" ", null); data.Add("\t", null); data.Add("unavailable", null); @@ -159,6 +163,7 @@ internal static class BoilerMonitorTestData data.Add("1e308", null); data.Add("-1", null); data.Add("-0.001", null); + return data; } @@ -175,7 +180,7 @@ internal static class BoilerMonitorTestData data.Add("2147483647", int.MaxValue); data.Add(null, null); - data.Add("", null); + data.Add(string.Empty, null); data.Add(" ", null); data.Add("\t", null); data.Add("unavailable", null); @@ -185,6 +190,7 @@ internal static class BoilerMonitorTestData data.Add("-1", null); data.Add("2147483648", null); data.Add("1e3", null); + return data; } @@ -204,6 +210,7 @@ internal static class BoilerMonitorTestData data.Add("actively heating", 2_150.0, false); data.Add("maximum", double.MaxValue, false); data.Add("not-a-number", double.NaN, true); + return data; } @@ -222,6 +229,7 @@ internal static class BoilerMonitorTestData data.Add(TimeSpan.FromHours(25)); data.Add(TimeSpan.FromHours(48)); data.Add(TimeSpan.FromHours(168)); + return data; } @@ -246,33 +254,35 @@ internal static class BoilerMonitorTestData // Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST. // now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z. data.Add( - "DST spring-forward, same UTC day", - new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), - new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)), - true - ); + "DST spring-forward, same UTC day", + new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), + new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)), + true + ); + data.Add( - "DST spring-forward, previous UTC day", - new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), - new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)), - false - ); + "DST spring-forward, previous UTC day", + new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), + new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)), + false + ); // Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice. // now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC. data.Add( - "DST fall-back, ambiguous local hour", - new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)), - new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)), - true - ); + "DST fall-back, ambiguous local hour", + new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)), + new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)), + true + ); data.Add( - "crossing midnight between restore and now", - new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero), - new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero), - false - ); + "crossing midnight between restore and now", + new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero), + new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero), + false + ); + return data; } diff --git a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs index 68940bf..c01a561 100644 --- a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs @@ -1,3 +1,5 @@ +#region + using BoilerMonitor.Models; using BoilerMonitorManager; using FluentAssertions; @@ -5,6 +7,8 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Time.Testing; using Moq; +#endregion + namespace BoilerMonitor.Manager.Tests; public class WaterReadyServiceTests @@ -13,7 +17,7 @@ public class WaterReadyServiceTests private const double HighPowerWatts = 2150.0; private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired; - private readonly Mock> _loggerMock = new(); + private readonly Mock> _loggerMock = new Mock>(); private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider(); private WaterReadyService CreateSut() @@ -25,6 +29,7 @@ public class WaterReadyServiceTests { var sut = CreateSut(); sut.RecordHeatingObserved(); + return sut; } @@ -36,7 +41,11 @@ public class WaterReadyServiceTests double heatingThresholdWatts = Threshold) { var result = false; - for (var i = 0; i < count; i++) result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts); + + for (var i = 0; i < count; i++) + { + result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts); + } return result; } @@ -119,8 +128,10 @@ public class WaterReadyServiceTests sut.ResetCooldown(); - FeedReadings(sut, RequiredReadings).Should().BeTrue( - "ResetCooldown clears the cooldown and counter, not the heating observation"); + FeedReadings(sut, RequiredReadings) + .Should() + .BeTrue( + "ResetCooldown clears the cooldown and counter, not the heating observation"); } [Fact] @@ -261,9 +272,10 @@ public class WaterReadyServiceTests var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts); - result.Should().Be( - expectedBelowThreshold, - $"{scenario}: readings below {Threshold}W are counted as 'not heating'"); + result.Should() + .Be( + expectedBelowThreshold, + $"{scenario}: readings below {Threshold}W are counted as 'not heating'"); } [Theory] @@ -283,7 +295,7 @@ public class WaterReadyServiceTests var sut = CreateSutWithHeatingObserved(); var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts, - heatingThresholdWatts: heatingThresholdWatts); + heatingThresholdWatts: heatingThresholdWatts); result.Should().Be(expected); } @@ -320,8 +332,12 @@ public class WaterReadyServiceTests _timeProvider.Advance(elapsed); sut.IsInCooldown.Should().BeTrue(); - sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue( - "cooldown only clears via explicit ResetCooldown, not by elapsed time"); + + sut.IsWaterReady("off", 0.0, Threshold) + .Should() + .BeTrue( + "cooldown only clears via explicit ResetCooldown, not by elapsed time"); + sut.WaterReadySince.Should().Be(triggeredAt); } diff --git a/BoilerMonitor.Manager/BoilerConfigReader.cs b/BoilerMonitor.Manager/BoilerConfigReader.cs index 99c0a94..9e2703d 100644 --- a/BoilerMonitor.Manager/BoilerConfigReader.cs +++ b/BoilerMonitor.Manager/BoilerConfigReader.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using BoilerMonitor.Models; using Microsoft.Extensions.Logging; @@ -5,6 +7,8 @@ using NetDaemon.HassModel; using static BoilerMonitor.Models.BoilerMonitorConsts; using static NordPool.Models.NordPoolConsts; +#endregion + namespace BoilerMonitorManager; public sealed class BoilerConfigReader(IHaContext haContext, ILogger logger) : IBoilerConfigReader @@ -14,15 +18,20 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger 0 ? pc @@ -43,8 +52,8 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger logger) : IBoilerControlService @@ -25,8 +29,8 @@ public sealed class BoilerControlService(ILogger logger) : if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", - currentSwitchState); + "Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", + currentSwitchState); } return BoilerAction.TurnOn; @@ -38,7 +42,7 @@ public sealed class BoilerControlService(ILogger logger) : if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, - currentSwitchState); + currentSwitchState); } return BoilerAction.TurnOff; @@ -48,8 +52,8 @@ public sealed class BoilerControlService(ILogger logger) : if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug( - "Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", - currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted); + "Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", + currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted); } return BoilerAction.NoChange; @@ -58,10 +62,13 @@ public sealed class BoilerControlService(ILogger logger) : private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted) { - if (waterReady) return "water is already ready"; + if (waterReady) + { + return "water is already ready"; + } return effectiveBudgetExhausted - ? "daily budget is exhausted" - : "not in a cheap interval"; + ? "daily budget is exhausted" + : "not in a cheap interval"; } } \ No newline at end of file diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs index 53acd84..2c85532 100644 --- a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using System.Text.Json; using BoilerMonitor.Models; @@ -9,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.HassModel; using static BoilerMonitor.Models.BoilerMonitorConsts; +#endregion + namespace BoilerMonitorManager; public sealed class BoilerMonitorEntityService( @@ -41,21 +45,21 @@ public sealed class BoilerMonitorEntityService( var entities = GetAllEntities(); var createTasks = entities.Select(async entity => - { - try - { - if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId); - } + { + try + { + if (logger.IsEnabled(LogLevel.Information)) + { + 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}", entity.EntityId); - } - }); + await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId); + } + }); await Task.WhenAll(createTasks).ConfigureAwait(false); } @@ -67,17 +71,18 @@ public sealed class BoilerMonitorEntityService( logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults"); await Task.WhenAll( - ResetStatusAsync(), - ResetWaterReadyAsync(), - ResetSkipPriceCapAsync(), - ResetTodayRuntimeAsync(), - ResetRemainingTimeAsync(), - ResetBudgetPercentageAsync(), - ResetBudgetExhaustedAsync(), - ResetSessionCountAsync(), - ResetBudgetOverrideAsync(), - ResetAutoManagementAsync() - ).ConfigureAwait(false); + ResetStatusAsync(), + ResetWaterReadyAsync(), + ResetSkipPriceCapAsync(), + ResetTodayRuntimeAsync(), + ResetRemainingTimeAsync(), + ResetBudgetPercentageAsync(), + ResetBudgetExhaustedAsync(), + ResetSessionCountAsync(), + ResetBudgetOverrideAsync(), + ResetAutoManagementAsync() + ) + .ConfigureAwait(false); logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults"); } @@ -118,6 +123,7 @@ public sealed class BoilerMonitorEntityService( catch (Exception ex) { logger.LogError(ex, "Error cleaning up BoilerMonitor entities"); + throw; } } @@ -129,9 +135,10 @@ public sealed class BoilerMonitorEntityService( logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)"); await Task.WhenAll( - ResetStatusAsync(), - ResetWaterReadyAsync() - ).ConfigureAwait(false); + ResetStatusAsync(), + ResetWaterReadyAsync() + ) + .ConfigureAwait(false); } public PersistedBoilerState? ReadPersistedState() @@ -149,8 +156,8 @@ public sealed class BoilerMonitorEntityService( if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", - runtimeState, sessionCountState); + "No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", + runtimeState, sessionCountState); } return null; @@ -167,9 +174,9 @@ public sealed class BoilerMonitorEntityService( if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}", - persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, - persisted.BudgetOverrideState); + "Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}", + persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, + persisted.BudgetOverrideState); } return persisted; @@ -177,6 +184,7 @@ public sealed class BoilerMonitorEntityService( catch (Exception ex) { logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities"); + return null; } } @@ -191,9 +199,16 @@ public sealed class BoilerMonitorEntityService( try { var entity = haContext.GetState(WaterReadyEntityId); - if (entity?.Attributes is not IDictionary attributes) return null; - if (!attributes.TryGetValue("cooldown_since", out var value)) return null; + if (entity?.Attributes is not IDictionary attributes) + { + return null; + } + + if (!attributes.TryGetValue("cooldown_since", out var value)) + { + return null; + } var stringValue = value switch { @@ -205,7 +220,7 @@ public sealed class BoilerMonitorEntityService( if (stringValue is not null && DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind, out var parsed)) + DateTimeStyles.RoundtripKind, out var parsed)) { if (logger.IsEnabled(LogLevel.Information)) { @@ -237,10 +252,7 @@ public sealed class BoilerMonitorEntityService( private static bool TryParseEntitySeconds(string? state, out double seconds) { seconds = 0; - var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) - && state is not ("unavailable" or "unknown") - && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) - && seconds >= 0; + var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0; return tryParseEntitySeconds; } @@ -248,10 +260,7 @@ public sealed class BoilerMonitorEntityService( private static bool TryParseEntityInt(string? state, out int value) { value = 0; - var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) - && state is not ("unavailable" or "unknown") - && int.TryParse(state, CultureInfo.InvariantCulture, out value) - && value >= 0; + var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0; return tryParseEntityInt; } @@ -283,7 +292,7 @@ public sealed class BoilerMonitorEntityService( } }, new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", - "Heating power threshold (watts)") + "Heating power threshold (watts)") { AdditionalConfig = new { @@ -362,14 +371,16 @@ public sealed class BoilerMonitorEntityService( private async Task ResetWaterReadyAsync() { await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false); + await SetEntityAttributesSafe(WaterReadyEntityId, new - { - boiler_switch_state = "unknown", - boiler_power_watts = 0.0, - power_threshold_watts = DefaultHeatingPowerThresholdWatts, - friendly_name = "Boiler water ready", - last_updated = (string?)null - }).ConfigureAwait(false); + { + boiler_switch_state = "unknown", + boiler_power_watts = 0.0, + power_threshold_watts = DefaultHeatingPowerThresholdWatts, + friendly_name = "Boiler water ready", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetSkipPriceCapAsync() @@ -380,35 +391,41 @@ public sealed class BoilerMonitorEntityService( private async Task ResetTodayRuntimeAsync() { await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(TodayRuntimeEntityId, new - { - formatted = "0h 0m", - friendly_name = "Today runtime", - last_updated = (string?)null - }).ConfigureAwait(false); + { + formatted = "0h 0m", + friendly_name = "Today runtime", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetRemainingTimeAsync() { await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(RemainingTimeEntityId, new - { - formatted = "0h 0m", - budget_hours = 0.0, - friendly_name = "Remaining budget time", - last_updated = (string?)null - }).ConfigureAwait(false); + { + formatted = "0h 0m", + budget_hours = 0.0, + friendly_name = "Remaining budget time", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetBudgetPercentageAsync() { await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(BudgetPercentageEntityId, new - { - unit_of_measurement = "%", - friendly_name = "Budget usage", - last_updated = (string?)null - }).ConfigureAwait(false); + { + unit_of_measurement = "%", + friendly_name = "Budget usage", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetBudgetExhaustedAsync() @@ -419,11 +436,13 @@ public sealed class BoilerMonitorEntityService( private async Task ResetSessionCountAsync() { await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(SessionCountEntityId, new - { - friendly_name = "Heating sessions today", - last_updated = (string?)null - }).ConfigureAwait(false); + { + friendly_name = "Heating sessions today", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetBudgetOverrideAsync() @@ -439,54 +458,68 @@ public sealed class BoilerMonitorEntityService( private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp) { await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false); + await SetEntityAttributesSafe(WaterReadyEntityId, new - { - boiler_switch_state = ctx.BoilerSwitchState ?? "unknown", - boiler_power_watts = ctx.BoilerPowerWatts, - cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture), - friendly_name = "Boiler water ready", - last_updated = timestamp - }).ConfigureAwait(false); + { + boiler_switch_state = ctx.BoilerSwitchState ?? "unknown", + boiler_power_watts = ctx.BoilerPowerWatts, + cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture), + friendly_name = "Boiler water ready", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp) { await SetEntityStateSafe(TodayRuntimeEntityId, - ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); + await SetEntityAttributesSafe(TodayRuntimeEntityId, new - { - formatted, - friendly_name = "Today runtime", - last_updated = timestamp - }).ConfigureAwait(false); + { + formatted, + friendly_name = "Today runtime", + last_updated = timestamp + }) + .ConfigureAwait(false); } - private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, - string timestamp) + private async Task UpdateRemainingTimeAsync(TimeSpan remaining, + string formatted, + double budgetHours, + string timestamp) { var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds); + await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)) - .ConfigureAwait(false); + .ConfigureAwait(false); + await SetEntityAttributesSafe(RemainingTimeEntityId, new - { - formatted, - budget_hours = budgetHours, - friendly_name = "Remaining budget time", - last_updated = timestamp - }).ConfigureAwait(false); + { + formatted, + budget_hours = budgetHours, + friendly_name = "Remaining budget time", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp) { var clampedPercentage = Math.Clamp(percentage, 0, 100); + await SetEntityStateSafe(BudgetPercentageEntityId, - ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); + await SetEntityAttributesSafe(BudgetPercentageEntityId, new - { - unit_of_measurement = "%", - friendly_name = "Budget usage", - last_updated = timestamp - }).ConfigureAwait(false); + { + unit_of_measurement = "%", + friendly_name = "Budget usage", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateBudgetExhaustedAsync(bool exhausted) @@ -497,12 +530,14 @@ public sealed class BoilerMonitorEntityService( private async Task UpdateSessionCountAsync(int sessionCount, string timestamp) { await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)) - .ConfigureAwait(false); + .ConfigureAwait(false); + await SetEntityAttributesSafe(SessionCountEntityId, new - { - friendly_name = "Heating sessions today", - last_updated = timestamp - }).ConfigureAwait(false); + { + friendly_name = "Heating sessions today", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task SetEntityStateSafe(string entityId, string state) @@ -510,6 +545,7 @@ public sealed class BoilerMonitorEntityService( try { await entityManager.SetEntityState(entityId, state).ConfigureAwait(false); + if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state); @@ -526,6 +562,7 @@ public sealed class BoilerMonitorEntityService( try { await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false); + if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Successfully set attributes for {EntityId}", entityId); diff --git a/BoilerMonitor.Manager/BoilerMonitorInit.cs b/BoilerMonitor.Manager/BoilerMonitorInit.cs index 64e89b6..688a296 100644 --- a/BoilerMonitor.Manager/BoilerMonitorInit.cs +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using System.Reactive.Concurrency; using System.Text.Json; @@ -13,6 +15,8 @@ using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using static BoilerMonitor.Models.BoilerMonitorConsts; +#endregion + namespace BoilerMonitorManager; [NetDaemonApp] @@ -45,17 +49,17 @@ public sealed class BoilerMonitorInit IOptions options, TimeProvider timeProvider) : this( - haContext, - logger, - scheduler, - mqttEntityManager, - boilerControlService, - tracker, - entityService, - waterReadyService, - options, - timeProvider, - true) + haContext, + logger, + scheduler, + mqttEntityManager, + boilerControlService, + tracker, + entityService, + waterReadyService, + options, + timeProvider, + true) { } @@ -83,7 +87,10 @@ public sealed class BoilerMonitorInit _options = options.Value; _timeProvider = timeProvider; - if (startBackgroundScheduling) _ = InitializeAndScheduleAsync(); + if (startBackgroundScheduling) + { + _ = InitializeAndScheduleAsync(); + } } private async Task InitializeAndScheduleAsync() @@ -130,14 +137,18 @@ public sealed class BoilerMonitorInit { _tracker.RestoreFromSnapshot(); - if (persistedCooldown.HasValue) _waterReadyService.RestoreCooldownState(persistedCooldown.Value); + if (persistedCooldown.HasValue) + { + _waterReadyService.RestoreCooldownState(persistedCooldown.Value); + } await _entityService.ResetTransientEntitiesAsync(); + if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation( - "BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", - persisted.AccumulatedRunTime, persisted.SessionCount); + "BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", + persisted.AccumulatedRunTime, persisted.SessionCount); } } else @@ -156,6 +167,7 @@ public sealed class BoilerMonitorInit catch (Exception ex) { _logger.LogError(ex, "Error initializing BoilerMonitor"); + throw; } } @@ -171,105 +183,126 @@ public sealed class BoilerMonitorInit if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", - DefaultPollIntervalSeconds, nextPollTime); + DefaultPollIntervalSeconds, nextPollTime); } _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, - () => _ = PollAndUpdateAsync()); + () => _ = PollAndUpdateAsync()); } private void ScheduleMidnightReset() { _scheduler.ScheduleCron("0 0 * * *", () => - { - try - { - _logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown"); - _tracker.Reset(); - _waterReadyService.ResetCooldown(); - _lastWaterReadyNotificationSentAt = null; - _ = _entityService.ResetEntitiesAsync(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error during midnight reset"); - } - }); + { + try + { + _logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown"); + _tracker.Reset(); + _waterReadyService.ResetCooldown(); + _lastWaterReadyNotificationSentAt = null; + _ = _entityService.ResetEntitiesAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during midnight reset"); + } + }); } private void ScheduleEndOfDayReminder() { _scheduler.ScheduleCron("0 22 * * *", () => - { - try - { - var switchState = _haContext.GetState(SkipPriceCapEntityId); - if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return; + { + try + { + var switchState = _haContext.GetState(SkipPriceCapEntityId); - _haContext.CallService("notify", "mobile_app_marius_phone", null, new - { - message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", - title = "Boiler reminder" - }); - _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error checking skip price cap reminder"); - } - }); + if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + _haContext.CallService("notify", "mobile_app_marius_phone", null, new + { + message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", + title = "Boiler reminder" + }); + + _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error checking skip price cap reminder"); + } + }); } private void SubscribeToSkipPriceCapChanges() { var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId); - skipPriceCapSwitch.StateChanges() - .Subscribe(e => - { - if (e.Old?.State == e.New?.State) return; - _logger.LogInformation("Skip price cap switch changed, triggering poll"); - _ = PollAndUpdateAsync(); - }); + skipPriceCapSwitch.StateChanges() + .Subscribe(e => + { + if (e.Old?.State == e.New?.State) + { + return; + } + + _logger.LogInformation("Skip price cap switch changed, triggering poll"); + _ = PollAndUpdateAsync(); + }); } private void SubscribeToAutoManagementChanges() { var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId); - autoManagementSwitch.StateChanges() - .Subscribe(e => - { - if (e.Old?.State == e.New?.State) return; - _logger.LogInformation("Automatic boiler control switch changed, triggering poll"); - _ = PollAndUpdateAsync(); - }); + autoManagementSwitch.StateChanges() + .Subscribe(e => + { + if (e.Old?.State == e.New?.State) + { + return; + } + + _logger.LogInformation("Automatic boiler control switch changed, triggering poll"); + _ = PollAndUpdateAsync(); + }); } private void SubscribeToShowerState() { var showerStateSensor = new Entity(_haContext, ShowerStateEntityId); + showerStateSensor.StateChanges() - .Subscribe(e => - { - if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) return; + .Subscribe(e => + { + if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) + { + return; + } - if (!_waterReadyService.IsInCooldown) return; + if (!_waterReadyService.IsInCooldown) + { + return; + } - _logger.LogInformation("Shower detected as active, resetting water ready cooldown"); - _waterReadyService.ResetCooldown(); - }); + _logger.LogInformation("Shower detected as active, resetting water ready cooldown"); + _waterReadyService.ResetCooldown(); + }); } private void SubscribeToCleanupButton() { var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); + cleanupButton.StateChanges() - .Subscribe(_ => - { - _logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities"); - Task.Run(HandleCleanupAsync); - }); + .Subscribe(_ => + { + _logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities"); + Task.Run(HandleCleanupAsync); + }); } private async Task SubscribeToConfigCommandsAsync() @@ -359,6 +392,7 @@ public sealed class BoilerMonitorInit if (_cleanedUp) { _logger.LogDebug("BoilerMonitor is cleaned up, skipping poll"); + return; } @@ -369,21 +403,27 @@ public sealed class BoilerMonitorInit if (!config.IsFullyConfigured) { await _entityService.SetStatusAsync(StatusAwaitingConfiguration); + _logger.LogWarning( - "BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration", - config.BoilerPowerEntityId, config.BoilerSwitchEntityId, - config.PollIntervalSeconds, config.HeatingPowerThresholdWatts); + "BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration", + config.BoilerPowerEntityId, config.BoilerSwitchEntityId, + config.PollIntervalSeconds, config.HeatingPowerThresholdWatts); return; } var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!); var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State; + var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value; + _tracker.RecordPollResult(); - if (isHeating) _waterReadyService.RecordHeatingObserved(); + if (isHeating) + { + _waterReadyService.RecordHeatingObserved(); + } var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); @@ -397,7 +437,7 @@ public sealed class BoilerMonitorInit var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0; var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, - config.HeatingPowerThresholdWatts!.Value); + config.HeatingPowerThresholdWatts!.Value); if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown()) { @@ -406,6 +446,7 @@ public sealed class BoilerMonitorInit message = "Hot water is ready.", title = "Boiler" }); + _lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow(); _logger.LogInformation("Water ready notification sent"); } @@ -416,24 +457,28 @@ public sealed class BoilerMonitorInit var budgetTimeSpan = TimeSpan.FromHours(dailyHours); var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime; - if (remainingTime < TimeSpan.Zero) remainingTime = TimeSpan.Zero; + if (remainingTime < TimeSpan.Zero) + { + remainingTime = TimeSpan.Zero; + } var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 - ? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0 - : 0.0; + ? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0 + : 0.0; var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan; var effectiveIsNowCheap = isNowCheap || skipPriceCap; var boilerAction = _boilerControlService.DetermineAction( - effectiveIsNowCheap, - waterReady, - boilerSwitchState, - budgetExhausted, - budgetOverride); + effectiveIsNowCheap, + waterReady, + boilerSwitchState, + budgetExhausted, + budgetOverride); var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State; + var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase); @@ -468,8 +513,8 @@ public sealed class BoilerMonitorInit if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug( - "Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", - boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage); + "Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", + boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage); } } catch (Exception ex) @@ -485,12 +530,17 @@ public sealed class BoilerMonitorInit case BoilerAction.TurnOn: _haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId)); _waterReadyService.NotifyTurnedOn(); + break; + case BoilerAction.TurnOff: _haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId)); + break; + case BoilerAction.NoChange: break; + default: throw new ArgumentOutOfRangeException(nameof(action), action, null); } @@ -504,9 +554,7 @@ public sealed class BoilerMonitorInit int? pollInterval = null; var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State; - if (!string.IsNullOrWhiteSpace(pollIntervalState) - && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) - && pollIntervalValue > 0) + if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0) { pollInterval = (int)pollIntervalValue; } @@ -514,9 +562,7 @@ public sealed class BoilerMonitorInit double? heatingThreshold = null; var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State; - if (!string.IsNullOrWhiteSpace(thresholdState) - && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) - && thresholdValue > 0) + if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0) { heatingThreshold = thresholdValue; } @@ -534,14 +580,20 @@ public sealed class BoilerMonitorInit { var state = _haContext.GetState(entityId); - if (state?.State is null or "unavailable" or "unknown") return null; + if (state?.State is null or "unavailable" or "unknown") + { + return null; + } return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; } private static bool ReadAttributeBool(EntityState? entityState, string attributeName) { - if (entityState?.Attributes is not IDictionary attributes) return false; + if (entityState?.Attributes is not IDictionary attributes) + { + return false; + } try { @@ -569,9 +621,13 @@ public sealed class BoilerMonitorInit private bool IsWithinNotificationCooldown() { - if (_lastWaterReadyNotificationSentAt is null) return false; + if (_lastWaterReadyNotificationSentAt is null) + { + return false; + } var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value; + return elapsed < WaterReadyNotificationCooldown; } } \ No newline at end of file diff --git a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs index 4014d63..4e4996d 100644 --- a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs +++ b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs @@ -1,9 +1,13 @@ +#region + using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; +#endregion + namespace BoilerMonitorManager; public static class BoilerMonitorServiceRegistration @@ -11,17 +15,21 @@ public static class BoilerMonitorServiceRegistration public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration) { var options = configuration - .GetSection(BoilerMonitorOptions.SectionName) - .Get() ?? new BoilerMonitorOptions(); + .GetSection(BoilerMonitorOptions.SectionName) + .Get() ?? + new BoilerMonitorOptions(); - if (!options.Enabled) return services; + if (!options.Enabled) + { + return services; + } services - .AddNetDaemonApp() - .AddSingleton() - .AddTransient() - .AddSingleton() - .AddSingleton(); + .AddNetDaemonApp() + .AddSingleton() + .AddTransient() + .AddSingleton() + .AddSingleton(); return services; } diff --git a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs index 820f908..f04a7ea 100644 --- a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs +++ b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs @@ -1,6 +1,10 @@ +#region + using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; +#endregion + namespace BoilerMonitorManager; public class BoilerRunTimeTracker : IBoilerRunTimeTracker diff --git a/BoilerMonitor.Manager/Interface/IBoilerControlService.cs b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs index 685942a..9dad47a 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerControlService.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs @@ -1,5 +1,9 @@ +#region + using BoilerMonitor.Models.Enums; +#endregion + namespace BoilerMonitorManager.Interface; public interface IBoilerControlService diff --git a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs index 48a7f74..d560024 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs @@ -1,5 +1,9 @@ +#region + using BoilerMonitorManager.Models; +#endregion + namespace BoilerMonitorManager.Interface; public interface IBoilerMonitorEntityService diff --git a/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs index f71ff71..b3031cb 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs @@ -1,5 +1,9 @@ +#region + using BoilerMonitorManager.Models; +#endregion + namespace BoilerMonitorManager.Interface; public interface IBoilerRunTimeTracker diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs b/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs index cc388ab..cf69275 100644 --- a/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs +++ b/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs @@ -7,9 +7,8 @@ public record BoilerMonitorConfig public int? PollIntervalSeconds { get; init; } public double? HeatingPowerThresholdWatts { get; init; } - public bool IsFullyConfigured => - !string.IsNullOrWhiteSpace(BoilerPowerEntityId) && - !string.IsNullOrWhiteSpace(BoilerSwitchEntityId) && - PollIntervalSeconds is > 0 && - HeatingPowerThresholdWatts is > 0; + public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) && + !string.IsNullOrWhiteSpace(BoilerSwitchEntityId) && + PollIntervalSeconds is > 0 && + HeatingPowerThresholdWatts is > 0; } \ No newline at end of file diff --git a/BoilerMonitor.Manager/WaterReadyService.cs b/BoilerMonitor.Manager/WaterReadyService.cs index 829e91c..57ed8a9 100644 --- a/BoilerMonitor.Manager/WaterReadyService.cs +++ b/BoilerMonitor.Manager/WaterReadyService.cs @@ -1,13 +1,17 @@ +#region + using BoilerMonitor.Models; using BoilerMonitorManager.Interface; using Microsoft.Extensions.Logging; +#endregion + namespace BoilerMonitorManager; public sealed class WaterReadyService(ILogger logger, TimeProvider timeProvider) : IWaterReadyService { private const string SwitchOnState = "on"; - private readonly Lock _lock = new(); + private readonly Lock _lock = new Lock(); private int _consecutiveBelowThresholdCount; private bool _hasObservedHeating; private DateTimeOffset? _waterReadySince; @@ -43,16 +47,22 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", - _waterReadySince); + _waterReadySince); } return true; } } - if (switchState is null || powerWatts is null) return false; + if (switchState is null || powerWatts is null) + { + return false; + } - if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return false; + if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) + { + return false; + } lock (_lock) { @@ -61,7 +71,7 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", - powerWatts.Value); + powerWatts.Value); } return false; @@ -70,6 +80,7 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (powerWatts.Value >= heatingThresholdWatts) { _consecutiveBelowThresholdCount = 0; + return false; } @@ -80,9 +91,9 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug( - "Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", - _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, - powerWatts.Value); + "Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", + _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, + powerWatts.Value); } return false; @@ -93,8 +104,8 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", - _consecutiveBelowThresholdCount); + "Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", + _consecutiveBelowThresholdCount); } return true; @@ -110,14 +121,17 @@ public sealed class WaterReadyService(ILogger logger, TimePro } logger.LogDebug( - "Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled"); + "Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled"); } public void RecordHeatingObserved() { lock (_lock) { - if (_hasObservedHeating) return; + if (_hasObservedHeating) + { + return; + } _hasObservedHeating = true; } @@ -141,18 +155,20 @@ public sealed class WaterReadyService(ILogger logger, TimePro lock (_lock) { var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero); + if (waterReadySince < todayMidnightUtc) { if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", - waterReadySince); + waterReadySince); } return; } _waterReadySince = waterReadySince; + if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince); diff --git a/BoilerMonitor.Models/BoilerMonitorEntity.cs b/BoilerMonitor.Models/BoilerMonitorEntity.cs index 8b69b07..0441487 100644 --- a/BoilerMonitor.Models/BoilerMonitorEntity.cs +++ b/BoilerMonitor.Models/BoilerMonitorEntity.cs @@ -1,6 +1,10 @@ +#region + using HomeAssistant.Models; using NetDaemon.Extensions.MqttEntityManager; +#endregion + namespace BoilerMonitor.Models; public class BoilerMonitorEntity : EntityCreateModel diff --git a/HomeAssistant.Entities/EntityManager.cs b/HomeAssistant.Entities/EntityManager.cs index baa435c..1ba7372 100644 --- a/HomeAssistant.Entities/EntityManager.cs +++ b/HomeAssistant.Entities/EntityManager.cs @@ -1,10 +1,14 @@ -using HomeAssistant.Entities.Interfaces; +#region + +using HomeAssistant.Entities.Interfaces; using HomeAssistant.Models; using HomeAssistantGenerated; using Microsoft.Extensions.Options; using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.HassModel; +#endregion + namespace HomeAssistant.Entities; public class EntityManager( @@ -53,12 +57,14 @@ public class EntityManager( var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix); foreach (var suffix in CleanupTopicSuffixes) + { haContext.CallService("mqtt", "publish", null, new MqttPublishParameters { Topic = $"{rootTopic}/{suffix}", Payload = string.Empty, Retain = true }); + } // IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket. return Task.CompletedTask; @@ -67,11 +73,12 @@ public class EntityManager( private static string BuildRootTopic(string entityId, string discoveryPrefix) { var separatorIndex = entityId.IndexOf('.'); + if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1) { throw new ArgumentException( - $"Entity id '{entityId}' is not in the 'domain.object_id' format.", - nameof(entityId)); + $"Entity id '{entityId}' is not in the 'domain.object_id' format.", + nameof(entityId)); } var domain = entityId[..separatorIndex]; diff --git a/HomeAssistant.Entities/Interfaces/IEntityManager.cs b/HomeAssistant.Entities/Interfaces/IEntityManager.cs index d666f75..72c92b0 100644 --- a/HomeAssistant.Entities/Interfaces/IEntityManager.cs +++ b/HomeAssistant.Entities/Interfaces/IEntityManager.cs @@ -1,4 +1,8 @@ -using HomeAssistant.Models; +#region + +using HomeAssistant.Models; + +#endregion namespace HomeAssistant.Entities.Interfaces; diff --git a/HomeAssistant.Models/EntityCreateModel.cs b/HomeAssistant.Models/EntityCreateModel.cs index 5dca19f..b719d6a 100644 --- a/HomeAssistant.Models/EntityCreateModel.cs +++ b/HomeAssistant.Models/EntityCreateModel.cs @@ -1,10 +1,14 @@ -using NetDaemon.Extensions.MqttEntityManager; +#region + +using NetDaemon.Extensions.MqttEntityManager; + +#endregion namespace HomeAssistant.Models; public class EntityCreateModel { public string? EntityId { get; protected init; } - public EntityCreationOptions? Options { get; init; } = new(); + public EntityCreationOptions? Options { get; init; } = new EntityCreationOptions(); public object? AdditionalConfig { get; init; } } \ No newline at end of file diff --git a/HomeAssistant.Server/CustomLoggingProvider.cs b/HomeAssistant.Server/CustomLoggingProvider.cs index 4c52623..72c117a 100644 --- a/HomeAssistant.Server/CustomLoggingProvider.cs +++ b/HomeAssistant.Server/CustomLoggingProvider.cs @@ -1,8 +1,12 @@ +#region + using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; +#endregion + namespace HomeAssistantServer; public static class CustomLoggingProvider @@ -10,14 +14,14 @@ public static class CustomLoggingProvider public static IHostBuilder UseCustomLogging(this IHostBuilder builder) { var configuration = new ConfigurationBuilder() - .AddJsonFile("appsettings.json") - .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", - true) - .Build(); + .AddJsonFile("appsettings.json") + .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", + true) + .Build(); var logger = new LoggerConfiguration() - .ReadFrom.Configuration(configuration) - .CreateLogger(); + .ReadFrom.Configuration(configuration) + .CreateLogger(); return builder.UseSerilog(logger); } diff --git a/HomeAssistant.Server/MqttRecreateApp.cs b/HomeAssistant.Server/MqttRecreateApp.cs index b6c4683..4b85d06 100644 --- a/HomeAssistant.Server/MqttRecreateApp.cs +++ b/HomeAssistant.Server/MqttRecreateApp.cs @@ -1,3 +1,5 @@ +#region + using System; using System.Collections.Generic; using System.Text.Json; @@ -13,6 +15,8 @@ using NordPoolManager.Interface; using PowerMonitorManager.Interface; using ShowerMonitorManager.Interface; +#endregion + namespace HomeAssistantServer; [NetDaemonApp] @@ -50,23 +54,24 @@ public sealed class MqttRecreateApp await Task.Delay(TimeSpan.FromSeconds(5)); await _mqttEntityManager.CreateAsync( - RecreateButtonEntityId, - new EntityCreationOptions - { - UniqueId = RecreateButtonEntityId, - Name = "Recreate all MQTT entities" - }, - new - { - icon = "mdi:refresh", - device = new - { - identifiers = AppDaemonIdentifiers, - name = "AppDaemon", - model = "AppDaemon", - manufacturer = "HomeAssistant App Daemon" - } - }).ConfigureAwait(false); + RecreateButtonEntityId, + new EntityCreationOptions + { + UniqueId = RecreateButtonEntityId, + Name = "Recreate all MQTT entities" + }, + new + { + icon = "mdi:refresh", + device = new + { + identifiers = AppDaemonIdentifiers, + name = "AppDaemon", + model = "AppDaemon", + manufacturer = "HomeAssistant App Daemon" + } + }) + .ConfigureAwait(false); if (_logger.IsEnabled(LogLevel.Information)) { @@ -74,12 +79,13 @@ public sealed class MqttRecreateApp } var button = new Entity(_haContext, RecreateButtonEntityId); + button.StateChanges() - .Subscribe(_ => - { - _logger.LogInformation("Recreate-all button pressed, recreating all MQTT entities"); - Task.Run(HandleRecreateAsync); - }); + .Subscribe(_ => + { + _logger.LogInformation("Recreate-all button pressed, recreating all MQTT entities"); + Task.Run(HandleRecreateAsync); + }); } catch (Exception ex) { @@ -107,9 +113,11 @@ public sealed class MqttRecreateApp private async Task RecreateNordPoolAsync() { var entityService = _serviceProvider.GetService(); + if (entityService is null) { _logger.LogDebug("NordPool entity service not registered (disabled), skipping"); + return; } @@ -132,9 +140,11 @@ public sealed class MqttRecreateApp private async Task RecreateBoilerMonitorAsync() { var entityService = _serviceProvider.GetService(); + if (entityService is null) { _logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping"); + return; } @@ -155,9 +165,11 @@ public sealed class MqttRecreateApp private async Task RecreateShowerMonitorAsync() { var entityService = _serviceProvider.GetService(); + if (entityService is null) { _logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping"); + return; } @@ -177,9 +189,11 @@ public sealed class MqttRecreateApp private async Task RecreatePowerMonitorAsync() { var entityService = _serviceProvider.GetService(); + if (entityService is null) { _logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping"); + return; } @@ -202,14 +216,13 @@ public sealed class MqttRecreateApp try { var state = _haContext.GetState(NordPoolPriceEntityId); + if (state?.Attributes is IDictionary attributes && attributes.TryGetValue("unit_of_measurement", out var value)) { return value switch { - string s => s, - JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), - _ => null + string s => s, JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), _ => null }; } } diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 05809fe..387d631 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -1,3 +1,5 @@ +#region + using System; using System.Reflection; using BatteryMonitorManager; @@ -28,47 +30,50 @@ using PowerMonitorManager.Models; using ShowerMonitorManager; using ShowerMonitorManager.Models; +#endregion + try { var app = Host.CreateDefaultBuilder(args) - .UseNetDaemonAppSettings() - .UseCustomLogging() - .UseNetDaemonRuntime() - .UseNetDaemonTextToSpeech() - .ConfigureServices((context, services) => - { - services - .AddNetDaemonMqttEntityManagement() - .AddAppsFromAssembly(Assembly.GetExecutingAssembly()) - .AddNetDaemonStateManager() - .AddNetDaemonScheduler() - .AddHomeAssistantGenerated() - .AddAutoMapper(config => - { - config.LicenseKey = - "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g"; - config.AddProfile(); - config.AddProfile(); - }) - .AddTransient() - .AddSingleton(TimeProvider.System) - .AddScoped() - .Configure(context.Configuration.GetSection(NordPoolOptions.SectionName)) - .AddNordPool() - .Configure(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) - .AddPowerMonitor() - .Configure(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) - .AddBoilerMonitor(context.Configuration) - .Configure(context.Configuration.GetSection(ShowerMonitorOptions.SectionName)) - .AddShowerMonitor(context.Configuration) - .Configure(context.Configuration.GetSection(LightMonitorOptions.SectionName)) - .AddLightMonitor(context.Configuration) - .Configure(context.Configuration.GetSection(BatteryMonitorOptions.SectionName)) - .AddBatteryMonitor(context.Configuration) - .Configure(context.Configuration.GetSection(LeakMonitorOptions.SectionName)) - .AddLeakMonitor(context.Configuration); - }) - .Build(); + .UseNetDaemonAppSettings() + .UseCustomLogging() + .UseNetDaemonRuntime() + .UseNetDaemonTextToSpeech() + .ConfigureServices((context, services) => + { + services + .AddNetDaemonMqttEntityManagement() + .AddAppsFromAssembly(Assembly.GetExecutingAssembly()) + .AddNetDaemonStateManager() + .AddNetDaemonScheduler() + .AddHomeAssistantGenerated() + .AddAutoMapper(config => + { + config.LicenseKey = + "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g"; + + config.AddProfile(); + config.AddProfile(); + }) + .AddTransient() + .AddSingleton(TimeProvider.System) + .AddScoped() + .Configure(context.Configuration.GetSection(NordPoolOptions.SectionName)) + .AddNordPool() + .Configure(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) + .AddPowerMonitor() + .Configure(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) + .AddBoilerMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(ShowerMonitorOptions.SectionName)) + .AddShowerMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(LightMonitorOptions.SectionName)) + .AddLightMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(BatteryMonitorOptions.SectionName)) + .AddBatteryMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(LeakMonitorOptions.SectionName)) + .AddLeakMonitor(context.Configuration); + }) + .Build(); await app.RunAsync().ConfigureAwait(false); } diff --git a/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs index 0531597..2c11938 100644 --- a/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs +++ b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs @@ -1,3 +1,5 @@ +#region + using FluentAssertions; using LeakMonitor.Models; using LeakMonitorManager; @@ -9,14 +11,16 @@ using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LeakMonitor.Manager.Tests; public class LeakMonitorInitTests { - private readonly Mock _haContextMock = new(); - private readonly Mock> _loggerMock = new(); - private readonly Mock _notificationServiceMock = new(); - private readonly LeakMonitorTestData.TrackingObservable _stateChanges = new(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock> _loggerMock = new Mock>(); + private readonly Mock _notificationServiceMock = new Mock(); + private readonly LeakMonitorTestData.TrackingObservable _stateChanges = new LeakMonitorTestData.TrackingObservable(); public LeakMonitorInitTests() { @@ -27,10 +31,10 @@ public class LeakMonitorInitTests private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null) { return new LeakMonitorInit( - _haContextMock.Object, - _notificationServiceMock.Object, - _loggerMock.Object, - Options.Create(options ?? LeakMonitorTestData.CreateOptions())); + _haContextMock.Object, + _notificationServiceMock.Object, + _loggerMock.Object, + Options.Create(options ?? LeakMonitorTestData.CreateOptions())); } private void VerifyNotifications(Times expected) @@ -42,9 +46,9 @@ public class LeakMonitorInitTests private void VerifyLogged(LogLevel level, Times times) { var logCount = _loggerMock.Invocations.Count(invocation => - invocation.Method.Name == nameof(ILogger.Log) && - invocation.Arguments[0] is LogLevel loggedLevel && - loggedLevel == level); + invocation.Method.Name == nameof(ILogger.Log) && + invocation.Arguments[0] is LogLevel loggedLevel && + loggedLevel == level); times.Validate(logCount); } @@ -56,11 +60,12 @@ public class LeakMonitorInitTests public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState) { var sut = CreateSut(); + var change = LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - sensorEntityId, - LeakMonitorConsts.WaterClearedState, - newState); + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + newState); sut.HandleStateChange(sensorEntityId, change); @@ -73,11 +78,12 @@ public class LeakMonitorInitTests public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState) { var sut = CreateSut(); + var change = LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - sensorEntityId, - LeakMonitorConsts.WaterDetectedState, - newState); + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterDetectedState, + newState); sut.HandleStateChange(sensorEntityId, change); @@ -90,11 +96,12 @@ public class LeakMonitorInitTests public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState) { var sut = CreateSut(); + var change = LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - LeakMonitorTestData.AquariumSensorId, - LeakMonitorConsts.WaterDetectedState, - newState); + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + newState); sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); @@ -107,18 +114,20 @@ public class LeakMonitorInitTests // Deduplication is the notification service's job (cooldown); the init handler // forwards each "on" event it receives. var sut = CreateSut(); + var change = LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - LeakMonitorTestData.AquariumSensorId, - LeakMonitorConsts.WaterDetectedState, - LeakMonitorConsts.WaterDetectedState); + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + LeakMonitorConsts.WaterDetectedState); sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); _notificationServiceMock.Verify( - n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), - Times.Exactly(2)); + n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Exactly(2)); + _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny()), Times.Never()); } @@ -127,11 +136,12 @@ public class LeakMonitorInitTests public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId) { var sut = CreateSut(); + var change = LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - sensorEntityId, - LeakMonitorConsts.WaterClearedState, - LeakMonitorConsts.WaterDetectedState); + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState); sut.HandleStateChange(sensorEntityId, change); @@ -160,9 +170,10 @@ public class LeakMonitorInitTests CreateSut(); _stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length); + _haContextMock.Verify( - h => h.StateAllChanges(), - Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); + h => h.StateAllChanges(), + Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); } [Theory] @@ -174,10 +185,10 @@ public class LeakMonitorInitTests _stateChanges.SubscriptionCount.Should().Be(1); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - sensorEntityId, - LeakMonitorConsts.WaterClearedState, - LeakMonitorConsts.WaterDetectedState)); + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); } @@ -186,22 +197,23 @@ public class LeakMonitorInitTests public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors() { CreateSut(LeakMonitorTestData.CreateOptions( - [null!, LeakMonitorTestData.BoilerSensorId])); + [null!, LeakMonitorTestData.BoilerSensorId])); _stateChanges.SubscriptionCount.Should().Be(2); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - LeakMonitorTestData.BoilerSensorId, - LeakMonitorConsts.WaterClearedState, - LeakMonitorConsts.WaterDetectedState)); + _haContextMock.Object, + LeakMonitorTestData.BoilerSensorId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); _notificationServiceMock.Verify( - n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId), - Times.Once()); + n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId), + Times.Once()); + _notificationServiceMock.Verify( - n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), - Times.Never()); + n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Never()); } [Theory] @@ -213,15 +225,16 @@ public class LeakMonitorInitTests CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - sensorEntityId, - LeakMonitorConsts.WaterClearedState, - newState)); + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + newState)); _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); + _notificationServiceMock.Verify( - n => n.SendLeakAlert(It.Is(id => id != sensorEntityId)), - Times.Never()); + n => n.SendLeakAlert(It.Is(id => id != sensorEntityId)), + Times.Never()); } [Theory] @@ -233,10 +246,10 @@ public class LeakMonitorInitTests CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - sensorEntityId, - LeakMonitorConsts.WaterDetectedState, - newState)); + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterDetectedState, + newState)); _notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once()); _notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny()), Times.Never()); @@ -249,10 +262,10 @@ public class LeakMonitorInitTests CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - LeakMonitorTestData.AquariumSensorId, - LeakMonitorConsts.WaterDetectedState, - newState)); + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + newState)); VerifyNotifications(Times.Never()); } @@ -263,10 +276,10 @@ public class LeakMonitorInitTests CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - LeakMonitorTestData.AquariumSensorId, - LeakMonitorConsts.WaterDetectedState, - LeakMonitorConsts.WaterDetectedState)); + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + LeakMonitorConsts.WaterDetectedState)); VerifyNotifications(Times.Never()); } @@ -277,10 +290,10 @@ public class LeakMonitorInitTests CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - "binary_sensor.unrelated_motion", - LeakMonitorConsts.WaterClearedState, - LeakMonitorConsts.WaterDetectedState)); + _haContextMock.Object, + "binary_sensor.unrelated_motion", + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); VerifyNotifications(Times.Never()); } @@ -291,55 +304,58 @@ public class LeakMonitorInitTests CreateSut(); foreach (var change in LeakMonitorTestData.CreateStateChangeSequence( - _haContextMock.Object, - LeakMonitorTestData.AquariumSensorId, - LeakMonitorTestData.DetectionSequence)) + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorTestData.DetectionSequence)) + { _stateChanges.Publish(change); + } _notificationServiceMock.Verify( - n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), - Times.Exactly(2)); + n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Exactly(2)); + _notificationServiceMock.Verify( - n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), - Times.Exactly(2)); + n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Exactly(2)); } [Fact] public void InitializeAsync_WhenNotificationServiceThrows_ShouldLogErrorAndKeepMonitoring() { _notificationServiceMock - .Setup(n => n.SendLeakAlert(It.IsAny())) - .Throws(new InvalidOperationException("notification failed")); + .Setup(n => n.SendLeakAlert(It.IsAny())) + .Throws(new InvalidOperationException("notification failed")); CreateSut(); var act = () => _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - LeakMonitorTestData.AquariumSensorId, - LeakMonitorConsts.WaterClearedState, - LeakMonitorConsts.WaterDetectedState)); + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); act.Should().NotThrow(); VerifyLogged(LogLevel.Error, Times.Once()); // The failed event must not tear down the subscription. _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( - _haContextMock.Object, - LeakMonitorTestData.AquariumSensorId, - LeakMonitorConsts.WaterDetectedState, - LeakMonitorConsts.WaterClearedState)); + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + LeakMonitorConsts.WaterClearedState)); _notificationServiceMock.Verify( - n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), - Times.Once()); + n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Once()); } [Fact] public void InitializeAsync_WhenSubscriptionFails_ShouldSwallowAndLogError() { _haContextMock - .Setup(h => h.StateAllChanges()) - .Throws(new InvalidOperationException("home assistant offline")); + .Setup(h => h.StateAllChanges()) + .Throws(new InvalidOperationException("home assistant offline")); var act = () => CreateSut(); diff --git a/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs b/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs index 434af6b..627aa64 100644 --- a/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs +++ b/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs @@ -1,3 +1,5 @@ +#region + using System.Text.Json; using LeakMonitor.Models; using LeakMonitorManager.Models; @@ -5,6 +7,8 @@ using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LeakMonitor.Manager.Tests; /// @@ -20,12 +24,12 @@ internal static class LeakMonitorTestData public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId]; - private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset DefaultStart = new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); /// /// Every casing of the "water detected" state, across both configured sensors. /// - public static TheoryData WaterDetectedCases { get; } = new() + public static TheoryData WaterDetectedCases { get; } = new TheoryData { { AquariumSensorId, LeakMonitorConsts.WaterDetectedState }, { AquariumSensorId, "ON" }, @@ -37,7 +41,7 @@ internal static class LeakMonitorTestData /// /// Every casing of the "water cleared" state, across both configured sensors. /// - public static TheoryData WaterClearedCases { get; } = new() + public static TheoryData WaterClearedCases { get; } = new TheoryData { { AquariumSensorId, LeakMonitorConsts.WaterClearedState }, { AquariumSensorId, "OFF" }, @@ -83,7 +87,7 @@ internal static class LeakMonitorTestData /// (sensor id, expected notification id) rows for the id sanitising rules: /// dots become underscores, other characters and blanks are preserved. /// - public static TheoryData NotificationIdCases { get; } = new() + public static TheoryData NotificationIdCases { get; } = new TheoryData { { AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" }, { BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" }, @@ -100,7 +104,7 @@ internal static class LeakMonitorTestData /// rows straddling the strict elapsed < cooldown boundary, plus zero, negative /// and int-max cooldowns. /// - public static TheoryData CooldownBoundaryCases { get; } = new() + public static TheoryData CooldownBoundaryCases { get; } = new TheoryData { { 5, 0, 1 }, { 5, 299, 1 }, @@ -172,7 +176,7 @@ internal static class LeakMonitorTestData string? newState) { return new StateChange(new Entity(haContext, entityId), CreateOptionalState(oldState), - CreateOptionalState(newState)); + CreateOptionalState(newState)); } public static IReadOnlyList CreateStateChangeSequence( @@ -183,7 +187,7 @@ internal static class LeakMonitorTestData return [ .. transitions.Select(transition => - CreateStateChange(haContext, entityId, transition.OldState, transition.NewState)) + CreateStateChange(haContext, entityId, transition.OldState, transition.NewState)) ]; } @@ -196,13 +200,13 @@ internal static class LeakMonitorTestData var calls = new List(); haContextMock - .Setup(h => h.CallService( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback((domain, service, target, data) => - calls.Add(new ServiceCall(domain, service, target, data))); + .Setup(h => h.CallService( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Callback((domain, service, target, data) => + calls.Add(new ServiceCall(domain, service, target, data))); return calls; } @@ -258,7 +262,10 @@ internal static class LeakMonitorTestData public void Publish(T value) { - foreach (var observer in _observers.ToArray()) observer.OnNext(value); + foreach (var observer in _observers.ToArray()) + { + observer.OnNext(value); + } } private sealed class Subscription(List> observers, IObserver observer) : IDisposable diff --git a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs index 2ce52ae..824614d 100644 --- a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs +++ b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs @@ -1,3 +1,5 @@ +#region + using FluentAssertions; using LeakMonitor.Models; using LeakMonitorManager; @@ -8,59 +10,61 @@ using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LeakMonitor.Manager.Tests; public class LeakNotificationServiceTests { - private readonly Mock _haContextMock = new(); - private readonly Mock> _loggerMock = new(); - private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock> _loggerMock = new Mock>(); + private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new LeakMonitorTestData.ManualTimeProvider(); private LeakNotificationService CreateSut(LeakMonitorOptions? options = null) { return new LeakNotificationService( - _haContextMock.Object, - _loggerMock.Object, - Options.Create(options ?? LeakMonitorTestData.CreateOptions()), - _timeProvider); + _haContextMock.Object, + _loggerMock.Object, + Options.Create(options ?? LeakMonitorTestData.CreateOptions()), + _timeProvider); } private void VerifyMobilePush(Times times) { _haContextMock.Verify( - h => h.CallService( - LeakMonitorConsts.NotifyDomain, - LeakMonitorConsts.MobileAppService, - It.IsAny(), - It.IsAny()), - times); + h => h.CallService( + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + It.IsAny(), + It.IsAny()), + times); } private void VerifyPersistentCreate(Times times) { _haContextMock.Verify( - h => h.CallService( - LeakMonitorConsts.PersistentNotificationDomain, - LeakMonitorConsts.PersistentNotificationCreateService, - It.IsAny(), - It.IsAny()), - times); + h => h.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationCreateService, + It.IsAny(), + It.IsAny()), + times); } private void VerifyPersistentDismiss(Times times) { _haContextMock.Verify( - h => h.CallService( - LeakMonitorConsts.PersistentNotificationDomain, - LeakMonitorConsts.PersistentNotificationDismissService, - It.IsAny(), - It.IsAny()), - times); + h => h.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationDismissService, + It.IsAny(), + It.IsAny()), + times); } #region SendLeakAlert - public static TheoryData SendAlertServiceCalls { get; } = new() + public static TheoryData SendAlertServiceCalls { get; } = new TheoryData { { LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService }, { LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService } @@ -75,8 +79,8 @@ public class LeakNotificationServiceTests sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId); _haContextMock.Verify( - h => h.CallService(domain, service, It.IsAny(), It.IsAny()), - Times.Once()); + h => h.CallService(domain, service, It.IsAny(), It.IsAny()), + Times.Once()); } [Fact] @@ -110,8 +114,11 @@ public class LeakNotificationServiceTests var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data); persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle); persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage); - persistentPayload.GetProperty("notification_id").GetString().Should() - .Be(LeakNotificationService.BuildNotificationId(sensorId)); + + persistentPayload.GetProperty("notification_id") + .GetString() + .Should() + .Be(LeakNotificationService.BuildNotificationId(sensorId)); } [Fact] @@ -136,17 +143,17 @@ public class LeakNotificationServiceTests sut.SendLeakAlert(sensorId); var persistentCall = calls.Single(c => - c is - { - Domain: LeakMonitorConsts.PersistentNotificationDomain, - Service: LeakMonitorConsts.PersistentNotificationCreateService - }); + c is + { + Domain: LeakMonitorConsts.PersistentNotificationDomain, + Service: LeakMonitorConsts.PersistentNotificationCreateService + }); LeakMonitorTestData.SerializePayload(persistentCall.Data) - .GetProperty("notification_id") - .GetString() - .Should() - .Be(expectedNotificationId); + .GetProperty("notification_id") + .GetString() + .Should() + .Be(expectedNotificationId); } [Theory] @@ -156,7 +163,10 @@ public class LeakNotificationServiceTests var sut = CreateSut(); const string sensorId = LeakMonitorTestData.AquariumSensorId; - for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId); + for (var i = 0; i < repeats; i++) + { + sut.SendLeakAlert(sensorId); + } VerifyMobilePush(Times.Once()); VerifyPersistentCreate(Times.Once()); @@ -169,7 +179,10 @@ public class LeakNotificationServiceTests var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0)); const string sensorId = LeakMonitorTestData.AquariumSensorId; - for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId); + for (var i = 0; i < repeats; i++) + { + sut.SendLeakAlert(sensorId); + } VerifyMobilePush(Times.Exactly(repeats)); VerifyPersistentCreate(Times.Exactly(repeats)); @@ -214,7 +227,10 @@ public class LeakNotificationServiceTests { var sut = CreateSut(); - foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds) sut.SendLeakAlert(sensorId); + foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds) + { + sut.SendLeakAlert(sensorId); + } VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); @@ -236,11 +252,11 @@ public class LeakNotificationServiceTests VerifyMobilePush(Times.Exactly(2)); var boilerNotifications = calls - .Where(c => c.Domain == LeakMonitorConsts.NotifyDomain) - .Where(c => LeakMonitorTestData.SerializePayload(c.Data) - .GetProperty("message") - .GetString()! - .Contains(LeakMonitorTestData.BoilerSensorId, StringComparison.Ordinal)); + .Where(c => c.Domain == LeakMonitorConsts.NotifyDomain) + .Where(c => LeakMonitorTestData.SerializePayload(c.Data) + .GetProperty("message") + .GetString()! + .Contains(LeakMonitorTestData.BoilerSensorId, StringComparison.Ordinal)); boilerNotifications.Should().ContainSingle(); } @@ -286,11 +302,12 @@ public class LeakNotificationServiceTests dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain); dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService); dismissCall.Target.Should().BeNull(); + LeakMonitorTestData.SerializePayload(dismissCall.Data) - .GetProperty("notification_id") - .GetString() - .Should() - .Be(expectedNotificationId); + .GetProperty("notification_id") + .GetString() + .Should() + .Be(expectedNotificationId); } [Fact] diff --git a/LeakMonitor.Manager/LeakMonitorInit.cs b/LeakMonitor.Manager/LeakMonitorInit.cs index cba4f9b..e84f3c8 100644 --- a/LeakMonitor.Manager/LeakMonitorInit.cs +++ b/LeakMonitor.Manager/LeakMonitorInit.cs @@ -1,3 +1,5 @@ +#region + using LeakMonitor.Models; using LeakMonitorManager.Interface; using LeakMonitorManager.Models; @@ -7,6 +9,8 @@ using NetDaemon.AppModel; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LeakMonitorManager; [NetDaemonApp] @@ -42,12 +46,15 @@ public sealed class LeakMonitorInit return Task.CompletedTask; } - foreach (var sensorEntityId in _options.SensorEntityIds) SubscribeToLeakSensor(sensorEntityId); + foreach (var sensorEntityId in _options.SensorEntityIds) + { + SubscribeToLeakSensor(sensorEntityId); + } if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)", - _options.SensorEntityIds.Length); + _options.SensorEntityIds.Length); } } catch (Exception ex) @@ -63,17 +70,17 @@ public sealed class LeakMonitorInit var entity = new Entity(_haContext, sensorEntityId); entity.StateChanges() - .Subscribe(change => - { - try - { - HandleStateChange(sensorEntityId, change); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error handling state change for {SensorId}", sensorEntityId); - } - }); + .Subscribe(change => + { + try + { + HandleStateChange(sensorEntityId, change); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling state change for {SensorId}", sensorEntityId); + } + }); if (_logger.IsEnabled(LogLevel.Information)) { diff --git a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs index ea0b71f..98685df 100644 --- a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs +++ b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs @@ -1,9 +1,13 @@ +#region + using LeakMonitorManager.Interface; using LeakMonitorManager.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; +#endregion + namespace LeakMonitorManager; public static class LeakMonitorServiceRegistration @@ -11,10 +15,14 @@ public static class LeakMonitorServiceRegistration public static void AddLeakMonitor(this IServiceCollection services, IConfiguration configuration) { var options = configuration - .GetSection(LeakMonitorOptions.SectionName) - .Get() ?? new LeakMonitorOptions(); + .GetSection(LeakMonitorOptions.SectionName) + .Get() ?? + new LeakMonitorOptions(); - if (!options.Enabled) return; + if (!options.Enabled) + { + return; + } services.AddNetDaemonApp().AddScoped(); } diff --git a/LeakMonitor.Manager/LeakNotificationService.cs b/LeakMonitor.Manager/LeakNotificationService.cs index c39c65e..480d2b5 100644 --- a/LeakMonitor.Manager/LeakNotificationService.cs +++ b/LeakMonitor.Manager/LeakNotificationService.cs @@ -1,3 +1,5 @@ +#region + using System.Collections.Concurrent; using LeakMonitor.Models; using LeakMonitorManager.Interface; @@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.HassModel; +#endregion + namespace LeakMonitorManager; public sealed class LeakNotificationService( @@ -14,7 +18,7 @@ public sealed class LeakNotificationService( IOptions options, TimeProvider timeProvider) : ILeakNotificationService { - private readonly ConcurrentDictionary _lastNotificationTimes = new(); + private readonly ConcurrentDictionary _lastNotificationTimes = new ConcurrentDictionary(); private readonly LeakMonitorOptions _options = options.Value; public void SendLeakAlert(string sensorEntityId) @@ -24,8 +28,8 @@ public sealed class LeakNotificationService( if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug( - "Skipping leak notification for {SensorId} -- within cooldown period", - sensorEntityId); + "Skipping leak notification for {SensorId} -- within cooldown period", + sensorEntityId); } return; @@ -47,9 +51,9 @@ public sealed class LeakNotificationService( var notificationId = BuildNotificationId(sensorEntityId); haContext.CallService( - LeakMonitorConsts.PersistentNotificationDomain, - LeakMonitorConsts.PersistentNotificationDismissService, - data: new { notification_id = notificationId }); + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationDismissService, + data: new { notification_id = notificationId }); if (logger.IsEnabled(LogLevel.Information)) { @@ -60,50 +64,55 @@ public sealed class LeakNotificationService( private void SendMobilePushNotification(string message) { haContext.CallService( - LeakMonitorConsts.NotifyDomain, - LeakMonitorConsts.MobileAppService, - data: new - { - message, - title = LeakMonitorConsts.NotificationTitle, - data = new - { - push = new - { - sound = new - { - critical = 1, - volume = 1.0 - } - } - } - }); + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + data: new + { + message, + title = LeakMonitorConsts.NotificationTitle, + data = new + { + push = new + { + sound = new + { + critical = 1, + volume = 1.0 + } + } + } + }); } private void CreatePersistentNotification(string notificationId, string message) { haContext.CallService( - LeakMonitorConsts.PersistentNotificationDomain, - LeakMonitorConsts.PersistentNotificationCreateService, - data: new - { - title = LeakMonitorConsts.NotificationTitle, - message, - notification_id = notificationId - }); + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationCreateService, + data: new + { + title = LeakMonitorConsts.NotificationTitle, + message, + notification_id = notificationId + }); } private bool IsWithinCooldown(string sensorEntityId) { - if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime)) return false; + if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime)) + { + return false; + } var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes); + return timeProvider.GetUtcNow() - lastTime < cooldown; } internal static string BuildNotificationId(string sensorEntityId) { var sanitized = sensorEntityId.Replace('.', '_'); + return $"{LeakMonitorConsts.NotificationIdPrefix}{sanitized}"; } } \ No newline at end of file diff --git a/LeakMonitor.Manager/Models/LeakMonitorOptions.cs b/LeakMonitor.Manager/Models/LeakMonitorOptions.cs index d94e4a0..c080d08 100644 --- a/LeakMonitor.Manager/Models/LeakMonitorOptions.cs +++ b/LeakMonitor.Manager/Models/LeakMonitorOptions.cs @@ -1,5 +1,9 @@ +#region + using LeakMonitor.Models; +#endregion + namespace LeakMonitorManager.Models; public sealed class LeakMonitorOptions diff --git a/LightMonitor.Manager.Tests/LightControlServiceTests.cs b/LightMonitor.Manager.Tests/LightControlServiceTests.cs index 15151cf..7bc951a 100644 --- a/LightMonitor.Manager.Tests/LightControlServiceTests.cs +++ b/LightMonitor.Manager.Tests/LightControlServiceTests.cs @@ -1,3 +1,5 @@ +#region + using LightMonitor.Models; using LightMonitorManager; using Microsoft.Extensions.Logging; @@ -6,6 +8,8 @@ using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LightMonitor.Manager.Tests; public class LightControlServiceTests @@ -15,20 +19,20 @@ public class LightControlServiceTests private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); - private readonly Mock _haContextMock = new(); + private readonly Mock _haContextMock = new Mock(); private LightControlService CreateService(LightMonitorOptions? options = null) { return new LightControlService( - _haContextMock.Object, - Mock.Of>(), - Options.Create(options ?? _defaultOptions)); + _haContextMock.Object, + Mock.Of>(), + Options.Create(options ?? _defaultOptions)); } private void SetupState(string entityId, string? state) { _haContextMock.Setup(x => x.GetState(entityId)) - .Returns(LightMonitorTestData.CreateOptionalState(state)); + .Returns(LightMonitorTestData.CreateOptionalState(state)); } private void VerifyTurnOn(string entityId, bool shouldTurnOn) @@ -36,17 +40,17 @@ public class LightControlServiceTests if (!shouldTurnOn) { _haContextMock.Verify(x => x.CallService( - It.IsAny(), It.IsAny(), - It.IsAny(), It.IsAny()), - Times.Never); + It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), + Times.Never); return; } _haContextMock.Verify(x => x.CallService("light", "turn_on", - It.Is(target => target.EntityIds != null && target.EntityIds.Contains(entityId)), - It.IsAny()), - Times.Once); + It.Is(target => target.EntityIds != null && target.EntityIds.Contains(entityId)), + It.IsAny()), + Times.Once); } [Theory] diff --git a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs index fea24db..092b5af 100644 --- a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs +++ b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs @@ -1,3 +1,5 @@ +#region + using System.Reactive.Subjects; using FluentAssertions; using LightMonitor.Models; @@ -9,6 +11,8 @@ using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LightMonitor.Manager.Tests; public class LightMonitorInitTests @@ -18,30 +22,30 @@ public class LightMonitorInitTests private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); - private readonly Mock _haContextMock = new(); - private readonly Mock _lightControlServiceMock = new(); - private readonly Mock _presenceServiceMock = new(); - private readonly Subject _stateChangesSubject = new(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock _lightControlServiceMock = new Mock(); + private readonly Mock _presenceServiceMock = new Mock(); + private readonly Subject _stateChangesSubject = new Subject(); private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null) { if (subscriptionException is null) { _haContextMock.Setup(x => x.StateAllChanges()) - .Returns(_stateChangesSubject); + .Returns(_stateChangesSubject); } else { _haContextMock.Setup(x => x.StateAllChanges()) - .Throws(subscriptionException); + .Throws(subscriptionException); } return new LightMonitorInit( - _haContextMock.Object, - Mock.Of>(), - _presenceServiceMock.Object, - _lightControlServiceMock.Object, - Options.Create(options ?? _defaultOptions)); + _haContextMock.Object, + Mock.Of>(), + _presenceServiceMock.Object, + _lightControlServiceMock.Object, + Options.Create(options ?? _defaultOptions)); } private void EmitStateChange(string entityId, string? oldState, string? newState) @@ -49,9 +53,9 @@ public class LightMonitorInitTests var entity = new Entity(_haContextMock.Object, entityId); _stateChangesSubject.OnNext(new StateChange( - entity, - LightMonitorTestData.CreateOptionalState(oldState), - LightMonitorTestData.CreateOptionalState(newState))); + entity, + LightMonitorTestData.CreateOptionalState(oldState), + LightMonitorTestData.CreateOptionalState(newState))); } private void VerifyTurnOn(bool shouldTurnOn) @@ -107,9 +111,9 @@ public class LightMonitorInitTests CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: [PersonEntityId])); EmitStateChange( - LightMonitorTestData.SecondaryPersonEntityId, - "not_home", - LightMonitorConsts.PersonHomeState); + LightMonitorTestData.SecondaryPersonEntityId, + "not_home", + LightMonitorConsts.PersonHomeState); VerifyTurnOn(false); } @@ -180,14 +184,15 @@ public class LightMonitorInitTests public void SunStateChange_WhenPresenceCheckThrows_ShouldKeepListening() { _presenceServiceMock.SetupSequence(x => x.IsAnyoneHome()) - .Throws(new InvalidOperationException("presence failed")) - .Returns(true); + .Throws(new InvalidOperationException("presence failed")) + .Returns(true); + CreateSut(); var act = () => EmitStateChange( - SunEntityId, - LightMonitorConsts.SunAboveHorizon, - LightMonitorConsts.SunBelowHorizon); + SunEntityId, + LightMonitorConsts.SunAboveHorizon, + LightMonitorConsts.SunBelowHorizon); act.Should().NotThrow(); VerifyTurnOn(false); @@ -200,8 +205,9 @@ public class LightMonitorInitTests public void PersonStateChange_WhenTurnOnLightThrows_ShouldKeepListening() { _lightControlServiceMock.SetupSequence(x => x.TurnOnLight()) - .Throws(new InvalidOperationException("light failed")) - .Pass(); + .Throws(new InvalidOperationException("light failed")) + .Pass(); + CreateSut(); var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState); @@ -238,7 +244,7 @@ public class LightMonitorInitTests CreateSut(); EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState, - LightMonitorConsts.SunBelowHorizon); + LightMonitorConsts.SunBelowHorizon); VerifyTurnOn(false); } diff --git a/LightMonitor.Manager.Tests/LightMonitorTestData.cs b/LightMonitor.Manager.Tests/LightMonitorTestData.cs index 057400c..f182598 100644 --- a/LightMonitor.Manager.Tests/LightMonitorTestData.cs +++ b/LightMonitor.Manager.Tests/LightMonitorTestData.cs @@ -1,6 +1,10 @@ +#region + using LightMonitor.Models; using NetDaemon.HassModel.Entities; +#endregion + namespace LightMonitor.Manager.Tests; /// @@ -37,7 +41,7 @@ internal static class LightMonitorTestData /// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and /// missing states must never turn the light on. /// - public static TheoryData SunStateTurnOnCases { get; } = new() + public static TheoryData SunStateTurnOnCases { get; } = new TheoryData { { LightMonitorConsts.SunBelowHorizon, true }, { LightMonitorConsts.SunBelowHorizon.ToUpperInvariant(), true }, @@ -55,7 +59,7 @@ internal static class LightMonitorTestData /// Light states evaluated while the sun is below the horizon. Only "on" (any casing) /// suppresses the turn on call; everything else, including missing state, turns it on. /// - public static TheoryData LightStateTurnOnCases { get; } = new() + public static TheoryData LightStateTurnOnCases { get; } = new TheoryData { { LightMonitorConsts.LightOnState, false }, { LightMonitorConsts.LightOnState.ToUpperInvariant(), false }, @@ -73,7 +77,7 @@ internal static class LightMonitorTestData /// Person states checked against the "arrived home" transition. /// Only "home" in any casing counts. /// - public static TheoryData PersonNewStateCases { get; } = new() + public static TheoryData PersonNewStateCases { get; } = new TheoryData { { LightMonitorConsts.PersonHomeState, true }, { "HOME", true }, @@ -92,7 +96,7 @@ internal static class LightMonitorTestData /// Old person states for a transition to "home". Recovery from unavailable, unknown or /// missing state must be ignored; every other old state is a real arrival. /// - public static TheoryData PersonArrivalTransitions { get; } = new() + public static TheoryData PersonArrivalTransitions { get; } = new TheoryData { { "not_home", true }, { "work", true }, @@ -106,7 +110,7 @@ internal static class LightMonitorTestData /// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown /// or missing state must be ignored. /// - public static TheoryData SunBelowHorizonTransitions { get; } = new() + public static TheoryData SunBelowHorizonTransitions { get; } = new TheoryData { { LightMonitorConsts.SunAboveHorizon, true }, { string.Empty, true }, @@ -171,9 +175,15 @@ internal static class LightMonitorTestData var matrix = new TheoryData(); foreach (var first in PresenceStates) - foreach (var second in PresenceStates) - foreach (var third in PresenceStates) - matrix.Add([first, second, third]); + { + foreach (var second in PresenceStates) + { + foreach (var third in PresenceStates) + { + matrix.Add([first, second, third]); + } + } + } return matrix; } diff --git a/LightMonitor.Manager.Tests/PresenceServiceTests.cs b/LightMonitor.Manager.Tests/PresenceServiceTests.cs index fe86ccf..2b933a1 100644 --- a/LightMonitor.Manager.Tests/PresenceServiceTests.cs +++ b/LightMonitor.Manager.Tests/PresenceServiceTests.cs @@ -1,3 +1,5 @@ +#region + using FluentAssertions; using LightMonitor.Models; using LightMonitorManager; @@ -6,19 +8,21 @@ using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; +#endregion + namespace LightMonitor.Manager.Tests; public class PresenceServiceTests { private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); - private readonly Mock _haContextMock = new(); + private readonly Mock _haContextMock = new Mock(); private PresenceService CreateService(LightMonitorOptions? options = null) { return new PresenceService( - _haContextMock.Object, - Mock.Of>(), - Options.Create(options ?? _defaultOptions)); + _haContextMock.Object, + Mock.Of>(), + Options.Create(options ?? _defaultOptions)); } private void SetupStates(string?[] personStates) @@ -29,7 +33,7 @@ public class PresenceServiceTests var state = LightMonitorTestData.CreateOptionalState(personStates[index]); _haContextMock.Setup(x => x.GetState(entityId)) - .Returns(state); + .Returns(state); } } @@ -40,7 +44,7 @@ public class PresenceServiceTests SetupStates(personStates); var expected = personStates.Any(state => - string.Equals(state, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)); + string.Equals(state, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)); CreateService().IsAnyoneHome().Should().Be(expected); } @@ -50,10 +54,10 @@ public class PresenceServiceTests public void IsAnyoneHome_ShouldOnlyTreatHomeStateAsPresent(string? state, bool expected) { _haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId)) - .Returns(LightMonitorTestData.CreateOptionalState(state)); + .Returns(LightMonitorTestData.CreateOptionalState(state)); var options = LightMonitorTestData.CreateOptions( - personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]); + personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]); CreateService(options).IsAnyoneHome().Should().Be(expected); } @@ -81,7 +85,7 @@ public class PresenceServiceTests public void IsAnyoneHome_ShouldStopCheckingAfterTheFirstHomePerson() { _haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId)) - .Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState)); + .Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState)); CreateService().IsAnyoneHome().Should().BeTrue(); @@ -95,17 +99,19 @@ public class PresenceServiceTests CreateService().IsAnyoneHome().Should().BeFalse(); foreach (var personEntityId in LightMonitorTestData.PersonEntityIds) + { _haContextMock.Verify(x => x.GetState(personEntityId), Times.Once); + } } [Fact] public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured() { _haContextMock.Setup(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId)) - .Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState)); + .Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState)); var options = LightMonitorTestData.CreateOptions( - personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]); + personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]); CreateService(options).IsAnyoneHome().Should().BeFalse(); @@ -120,6 +126,8 @@ public class PresenceServiceTests service.IsAnyoneHome().Should().BeFalse(); foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds) + { _haContextMock.Verify(x => x.GetState(personEntityId), Times.Once); + } } } \ No newline at end of file diff --git a/LightMonitor.Manager/LightControlService.cs b/LightMonitor.Manager/LightControlService.cs index 289204b..3809eec 100644 --- a/LightMonitor.Manager/LightControlService.cs +++ b/LightMonitor.Manager/LightControlService.cs @@ -1,3 +1,5 @@ +#region + using LightMonitor.Models; using LightMonitorManager.Interface; using Microsoft.Extensions.Logging; @@ -5,6 +7,8 @@ using Microsoft.Extensions.Options; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LightMonitorManager; public sealed class LightControlService( diff --git a/LightMonitor.Manager/LightMonitorInit.cs b/LightMonitor.Manager/LightMonitorInit.cs index d259f85..c08b4e4 100644 --- a/LightMonitor.Manager/LightMonitorInit.cs +++ b/LightMonitor.Manager/LightMonitorInit.cs @@ -1,3 +1,5 @@ +#region + using LightMonitor.Models; using LightMonitorManager.Interface; using Microsoft.Extensions.Logging; @@ -6,6 +8,8 @@ using NetDaemon.AppModel; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +#endregion + namespace LightMonitorManager; [NetDaemonApp] @@ -43,7 +47,7 @@ public sealed class LightMonitorInit if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", - _options.PersonEntityIds.Length); + _options.PersonEntityIds.Length); } } catch (Exception ex) @@ -57,36 +61,40 @@ public sealed class LightMonitorInit private void SubscribeToSunStateChanges() { var sunEntity = new Entity(_haContext, _options.SunEntityId); + sunEntity.StateChanges() - .Subscribe(e => - { - try - { - if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon, - StringComparison.OrdinalIgnoreCase)) - { - return; - } + .Subscribe(e => + { + try + { + if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon, + StringComparison.OrdinalIgnoreCase)) + { + return; + } - if (IsRecoveryTransition(e.Old?.State)) - { - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State); - } + if (IsRecoveryTransition(e.Old?.State)) + { + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State); + } - return; - } + return; + } - _logger.LogInformation("Sun went below horizon, checking if anyone is home"); + _logger.LogInformation("Sun went below horizon, checking if anyone is home"); - if (_presenceService.IsAnyoneHome()) _lightControlService.TurnOnLight(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error handling sun state change"); - } - }); + if (_presenceService.IsAnyoneHome()) + { + _lightControlService.TurnOnLight(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling sun state change"); + } + }); } private void SubscribeToPersonStateChanges() @@ -94,41 +102,42 @@ public sealed class LightMonitorInit foreach (var personEntityId in _options.PersonEntityIds) { var personEntity = new Entity(_haContext, personEntityId); + personEntity.StateChanges() - .Subscribe(e => - { - try - { - if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState, - StringComparison.OrdinalIgnoreCase)) - { - return; - } + .Subscribe(e => + { + try + { + if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState, + StringComparison.OrdinalIgnoreCase)) + { + return; + } - if (IsRecoveryTransition(e.Old?.State)) - { - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", - personEntityId, e.Old?.State); - } + if (IsRecoveryTransition(e.Old?.State)) + { + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", + personEntityId, e.Old?.State); + } - return; - } + return; + } - if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", - personEntityId); - } + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", + personEntityId); + } - _lightControlService.TurnOnLight(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId); - } - }); + _lightControlService.TurnOnLight(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId); + } + }); } } diff --git a/LightMonitor.Manager/LightMonitorServiceRegistration.cs b/LightMonitor.Manager/LightMonitorServiceRegistration.cs index 939a208..6b7de8e 100644 --- a/LightMonitor.Manager/LightMonitorServiceRegistration.cs +++ b/LightMonitor.Manager/LightMonitorServiceRegistration.cs @@ -1,9 +1,13 @@ +#region + using LightMonitor.Models; using LightMonitorManager.Interface; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; +#endregion + namespace LightMonitorManager; public static class LightMonitorServiceRegistration @@ -11,14 +15,18 @@ public static class LightMonitorServiceRegistration public static IServiceCollection AddLightMonitor(this IServiceCollection services, IConfiguration configuration) { var options = configuration - .GetSection(LightMonitorOptions.SectionName) - .Get() ?? new LightMonitorOptions(); + .GetSection(LightMonitorOptions.SectionName) + .Get() ?? + new LightMonitorOptions(); - if (!options.Enabled) return services; + if (!options.Enabled) + { + return services; + } services.AddNetDaemonApp() - .AddScoped() - .AddScoped(); + .AddScoped() + .AddScoped(); return services; } diff --git a/LightMonitor.Manager/PresenceService.cs b/LightMonitor.Manager/PresenceService.cs index 1022f82..ba60b06 100644 --- a/LightMonitor.Manager/PresenceService.cs +++ b/LightMonitor.Manager/PresenceService.cs @@ -1,9 +1,13 @@ +#region + using LightMonitor.Models; using LightMonitorManager.Interface; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.HassModel; +#endregion + namespace LightMonitorManager; public sealed class PresenceService( @@ -25,12 +29,15 @@ public sealed class PresenceService( } if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState, - StringComparison.OrdinalIgnoreCase)) + StringComparison.OrdinalIgnoreCase)) { continue; } - if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Person {EntityId} is home", personEntityId); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Person {EntityId} is home", personEntityId); + } return true; } diff --git a/LightMonitor.Models/LightMonitorOptions.cs b/LightMonitor.Models/LightMonitorOptions.cs index d4e2837..616d3db 100644 --- a/LightMonitor.Models/LightMonitorOptions.cs +++ b/LightMonitor.Models/LightMonitorOptions.cs @@ -1,5 +1,9 @@ +#region + using static LightMonitor.Models.LightMonitorConsts; +#endregion + namespace LightMonitor.Models; public sealed class LightMonitorOptions diff --git a/Mappings/Converters/DateTimeTypeConverter.cs b/Mappings/Converters/DateTimeTypeConverter.cs index 2efcb17..11a88ff 100644 --- a/Mappings/Converters/DateTimeTypeConverter.cs +++ b/Mappings/Converters/DateTimeTypeConverter.cs @@ -1,6 +1,10 @@ -using System.Globalization; +#region + +using System.Globalization; using AutoMapper; +#endregion + namespace Mappings.Converters; public class DateTimeTypeConverter : ITypeConverter diff --git a/Mappings/GlobalMappingProfile.cs b/Mappings/GlobalMappingProfile.cs index bb4d975..4d8871e 100644 --- a/Mappings/GlobalMappingProfile.cs +++ b/Mappings/GlobalMappingProfile.cs @@ -1,6 +1,10 @@ -using AutoMapper; +#region + +using AutoMapper; using Mappings.Converters; +#endregion + namespace Mappings; public class GlobalMappingProfile : Profile diff --git a/Mappings/NordPoolMappingProfile.cs b/Mappings/NordPoolMappingProfile.cs index 60f3cf6..565a2be 100644 --- a/Mappings/NordPoolMappingProfile.cs +++ b/Mappings/NordPoolMappingProfile.cs @@ -1,7 +1,11 @@ -using AutoMapper; +#region + +using AutoMapper; using NordPool.Models; using NordPool.Models.Dtos; +#endregion + namespace Mappings; public class NordPoolMappingProfile : Profile @@ -9,7 +13,8 @@ public class NordPoolMappingProfile : Profile public NordPoolMappingProfile() { CreateMap() - .ForMember(destination => destination.Price, options => options.MapFrom(source => source.Price)); + .ForMember(destination => destination.Price, options => options.MapFrom(source => source.Price)); + CreateMap(); } } \ No newline at end of file diff --git a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs index dcdc57b..db97e43 100644 --- a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs +++ b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs @@ -1,9 +1,13 @@ +#region + using FluentAssertions; using Microsoft.Extensions.Logging; using Moq; using NordPool.Models; using NordPoolManager; +#endregion + namespace NordPool.Manager.Tests; public class CheapestIntervalsFinderTests @@ -13,7 +17,7 @@ public class CheapestIntervalsFinderTests private static readonly DateTime DayStart = NordPoolTestData.DayStart; private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1); - private readonly Mock> _loggerMock = new(); + private readonly Mock> _loggerMock = new Mock>(); private CheapestIntervalsFinder CreateSut() { @@ -26,7 +30,7 @@ public class CheapestIntervalsFinderTests } private static NordPoolPrice CreatePricesForDay(DateTime dayStart, - int intervalCount = NordPoolConsts.MaxDailyIntervals) + int intervalCount = NordPoolConsts.MaxDailyIntervals) { return new NordPoolPrice { @@ -55,7 +59,7 @@ public class CheapestIntervalsFinderTests #region FindCheapestIntervals - public static TheoryData FilteringCases => new() + public static TheoryData FilteringCases => new TheoryData { { "deadline includes interval ending exactly at it", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_800.0, 2 }, { "deadline excludes interval ending one second late", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_799.0, 1 }, @@ -236,12 +240,13 @@ public class CheapestIntervalsFinderTests { // Arrange — duplicate payload entries are not deduplicated var sut = CreateSut(); + var prices = new NordPoolPrice { Prices = new List { - new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }, - new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 } + new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }, + new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 } } }; @@ -258,15 +263,16 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); + var prices = new NordPoolPrice { Prices = new List { - new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 }, - new() { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null }, - new() { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 }, - new() { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 }, - new() { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 } + new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 }, + new NordPoolDayPrice { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null }, + new NordPoolDayPrice { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 }, + new NordPoolDayPrice { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 }, + new NordPoolDayPrice { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 } } }; @@ -287,12 +293,12 @@ public class CheapestIntervalsFinderTests const double priceCap = 12.0; var expected = prices.Prices! - .Where(p => p.Price <= priceCap) - .OrderBy(p => p.Price) - .ThenBy(p => p.Start) - .Take(requestedIntervals) - .OrderBy(p => p.Start) - .ToList(); + .Where(p => p.Price <= priceCap) + .OrderBy(p => p.Price) + .ThenBy(p => p.Start) + .Take(requestedIntervals) + .OrderBy(p => p.Start) + .ToList(); // Act var result = sut.FindCheapestIntervals(prices, requestedIntervals, priceCap, DeadlineEndOfDay); @@ -315,30 +321,31 @@ public class CheapestIntervalsFinderTests { // Arrange - xUnit cannot serialize CheapestIntervalResult rows, so the matrix is exercised in one test var sut = CreateSut(); + (string Scenario, int NowSeconds, CheapestIntervalResult[] Intervals, bool Expected)[] cases = [ ("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true), ("exactly at start", 10 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter)], true), ("exactly at end", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter)], false), ("outside all intervals", 12 * Hour, - [Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false), + [Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false), ("boundary between adjacent intervals", 10 * Hour + Quarter, - [ - Interval(10 * Hour, 10 * Hour + Quarter, 8.96), - Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, 6.20, 2) - ], true), + [ + Interval(10 * Hour, 10 * Hour + Quarter, 8.96), + Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, 6.20, 2) + ], true), ("unsorted intervals", 14 * Hour + 5 * 60, - [Interval(14 * Hour, 14 * Hour + Quarter, 4.93, 2), Interval(10 * Hour, 10 * Hour + Quarter, 6.20)], - true), + [Interval(14 * Hour, 14 * Hour + Quarter, 4.93, 2), Interval(10 * Hour, 10 * Hour + Quarter, 6.20)], + true), ("before first interval", 10 * Hour - 1, [Interval(10 * Hour, 10 * Hour + Quarter)], false), ("in gap between intervals", 10 * Hour + 2 * Quarter, - [Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false), + [Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false), ("middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60, - [ - Interval(10 * Hour, 10 * Hour + Quarter, rank: 1), - Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2), - Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3) - ], true), + [ + Interval(10 * Hour, 10 * Hour + Quarter, rank: 1), + Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2), + Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3) + ], true), ("empty interval list", 12 * Hour, [], false) ]; diff --git a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs index 54b440a..2ab0754 100644 --- a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs +++ b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs @@ -1,21 +1,25 @@ +#region + using System.Text; using System.Text.Json; using FluentAssertions; using NordPool.Models; using static NordPool.Models.NordPoolConsts; +#endregion + namespace NordPool.Manager.Tests; public class CompactNordPoolDayPriceTests { private const int IntervalDurationSeconds = MinutesPerInterval * 60; - private static readonly DateTime TestStart = new(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc); + private static readonly DateTime TestStart = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc); private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval); private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds(); private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds(); - public static TheoryData InvalidJsonPayloads => new() + public static TheoryData InvalidJsonPayloads => new TheoryData { { "empty array", "[]" }, { "too few elements", "[1,2]" }, @@ -157,8 +161,8 @@ public class CompactNordPoolDayPriceTests { var prices = new List { - new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 }, - new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 } + new CompactNordPoolDayPrice { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 }, + new CompactNordPoolDayPrice { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 } }; var json = JsonSerializer.Serialize(prices); @@ -198,8 +202,8 @@ public class CompactNordPoolDayPriceTests { var prices = new List { - new() { Start = TestStart, End = TestEnd, Price = 12.50 }, - new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 } + new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.50 }, + new NordPoolDayPrice { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 } }; var result = prices.ToCompact(); @@ -240,8 +244,11 @@ public class CompactNordPoolDayPriceTests result.Should().HaveCount(96); result.Should().BeInAscendingOrder(p => p.Start); result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds()); - result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval)) - .ToUnixTimeSeconds()); + + result[95] + .Start.Should() + .Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval)) + .ToUnixTimeSeconds()); } [Fact] @@ -262,7 +269,7 @@ public class CompactNordPoolDayPriceTests { var prices = new List { - new() { Start = null, End = null, Price = null } + new NordPoolDayPrice { Start = null, End = null, Price = null } }; var result = prices.ToCompact(); @@ -280,6 +287,7 @@ public class CompactNordPoolDayPriceTests var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22); var compactPrices = prices.ToCompact(); + var attributePayload = new { prices = compactPrices, @@ -287,10 +295,12 @@ public class CompactNordPoolDayPriceTests friendly_name = "NordPool today and tomorrow prices", last_updated = DateTime.UtcNow.ToString("O") }; + var json = JsonSerializer.Serialize(attributePayload); var byteCount = Encoding.UTF8.GetByteCount(json); - byteCount.Should().BeLessThan(haAttributeByteLimitBytes, - $"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit"); + byteCount.Should() + .BeLessThan(haAttributeByteLimitBytes, + $"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit"); } } \ No newline at end of file diff --git a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs index 128790c..fe10f52 100644 --- a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs @@ -1,3 +1,5 @@ +#region + using System.Text; using System.Text.Json; using FluentAssertions; @@ -8,6 +10,8 @@ using NordPool.Models; using NordPoolManager; using NordPoolManager.Models; +#endregion + namespace NordPool.Manager.Tests; public class NordPoolEntityServiceTests @@ -99,7 +103,7 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.CreateEntitiesAsync("EUR/kWh"); @@ -113,14 +117,16 @@ public class NordPoolEntityServiceTests { // Arrange var callCount = 0; + _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(() => - { - callCount++; - return callCount == 2 - ? throw new InvalidOperationException("Entity creation failed") - : Task.CompletedTask; - }); + .Returns(() => + { + callCount++; + + return callCount == 2 + ? throw new InvalidOperationException("Entity creation failed") + : Task.CompletedTask; + }); // Act await _sut.CreateEntitiesAsync("EUR/kWh"); @@ -134,7 +140,7 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.CreateEntitiesAsync(null); @@ -152,7 +158,7 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.CleanupEntitiesAsync(); @@ -172,7 +178,7 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Remove failed")); + .ThrowsAsync(new InvalidOperationException("Remove failed")); // Act var act = () => _sut.CleanupEntitiesAsync(); @@ -190,7 +196,7 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.SetEntityStateSafe("sensor.test", "42"); @@ -204,7 +210,7 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("State update failed")); + .ThrowsAsync(new InvalidOperationException("State update failed")); // Act var act = () => _sut.SetEntityStateSafe("sensor.test", "42"); @@ -222,8 +228,9 @@ public class NordPoolEntityServiceTests { // Arrange var attributes = new { unit_of_measurement = "EUR/kWh" }; + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.SetEntityAttributesSafe("sensor.test", attributes); @@ -237,8 +244,9 @@ public class NordPoolEntityServiceTests { // Arrange var attributes = new { unit_of_measurement = "EUR/kWh" }; + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Attributes update failed")); + .ThrowsAsync(new InvalidOperationException("Attributes update failed")); // Act var act = () => _sut.SetEntityAttributesSafe("sensor.test", attributes); @@ -256,20 +264,23 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.ResetEntitiesAsync(); // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", string.Empty), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("button.nordpool_fetch_prices", "unknown"), Times.Once); } @@ -279,28 +290,35 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.ResetEntitiesAsync(); // Assert _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); + em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); + _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); + em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny()), - Times.Once); + Times.Once); } [Fact] @@ -308,12 +326,14 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny())) - .ThrowsAsync(new InvalidOperationException("State update failed")); + .ThrowsAsync(new InvalidOperationException("State update failed")); + _entityManagerMock.Setup(em => - em.SetEntityState(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) - .Returns(Task.CompletedTask); + em.SetEntityState(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act var act = () => _sut.ResetEntitiesAsync(); @@ -327,17 +347,19 @@ public class NordPoolEntityServiceTests { // Arrange - 7 entities get state and attributes _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.ResetEntitiesAsync(); // Assert _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(7)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), - Times.Exactly(7)); + Times.Exactly(7)); } #endregion @@ -356,14 +378,16 @@ public class NordPoolEntityServiceTests DayQuartersIndex = 5, LastApiUpdateDate = DateTime.UtcNow, UsingCachedData = false, - TodayNordPoolPrice = todayPrice ?? new NordPoolPrice - { - Prices = new List { new() { Price = 12.50 } } - }, - TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice - { - Prices = new List { new() { Price = 18.71 } } - }, + TodayNordPoolPrice = todayPrice ?? + new NordPoolPrice + { + Prices = new List { new NordPoolDayPrice { Price = 12.50 } } + }, + TomorrowNordPoolPrice = tomorrowPrice ?? + new NordPoolPrice + { + Prices = new List { new NordPoolDayPrice { Price = 18.71 } } + }, CheapestIntervals = [], ConfiguredHours = 2.0, ConfiguredIntervalCount = 4, @@ -382,24 +406,28 @@ public class NordPoolEntityServiceTests var context = CreateDefaultContext(); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once); + _entityManagerMock.Verify( - em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", - It.Is(s => s.Contains('-') && s.Contains(':'))), Times.Once); + em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", + It.Is(s => s.Contains('-') && s.Contains(':'))), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny()), - Times.Once); + Times.Once); } [Fact] @@ -409,22 +437,26 @@ public class NordPoolEntityServiceTests var context = CreateDefaultContext(); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); // Assert _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), - Times.Once); + Times.Once); + _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); + em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); } [Fact] @@ -432,13 +464,14 @@ public class NordPoolEntityServiceTests { // Arrange var context = CreateDefaultContext( - todayPrice: new NordPoolPrice { Prices = null }, - tomorrowPrice: new NordPoolPrice { Prices = null }); + todayPrice: new NordPoolPrice { Prices = null }, + tomorrowPrice: new NordPoolPrice { Prices = null }); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); @@ -446,12 +479,12 @@ public class NordPoolEntityServiceTests // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once); - _entityManagerMock.Verify( - em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => - s.Length > 0 && s != "0" && s.Contains('-'))), - Times.Once); - } + _entityManagerMock.Verify( + em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => + s.Length > 0 && s != "0" && s.Contains('-'))), + Times.Once); + } [Fact] public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices() @@ -519,16 +552,19 @@ public class NordPoolEntityServiceTests { // Arrange object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) - .Callback((_, attrs) => capturedAttributes = attrs) - .Returns(Task.CompletedTask); + em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), - It.IsAny())) - .Returns(Task.CompletedTask); + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), + It.IsAny())) + .Returns(Task.CompletedTask); var context = CreateDefaultContext() with { @@ -566,21 +602,23 @@ public class NordPoolEntityServiceTests } ] }; + var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] }); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); // Assert _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => - o.GetType().GetProperty("prices")!.GetValue(o) is List)), - Times.Once); + em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => + o.GetType().GetProperty("prices")!.GetValue(o) is List)), + Times.Once); } [Fact] @@ -592,35 +630,42 @@ public class NordPoolEntityServiceTests var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc); - var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice - { - Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), - End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), - Price = 4.93 + i * 0.22 - }).ToList(); + var todayPrices = Enumerable.Range(0, intervalsPerDay) + .Select(i => new NordPoolDayPrice + { + Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), + End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), + Price = 4.93 + i * 0.22 + }) + .ToList(); - var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice - { - Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), - End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), - Price = 5.50 + i * 0.22 - }).ToList(); + var tomorrowPrices = Enumerable.Range(0, intervalsPerDay) + .Select(i => new NordPoolDayPrice + { + Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), + End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), + Price = 5.50 + i * 0.22 + }) + .ToList(); object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) - .Callback((_, attrs) => capturedAttributes = attrs) - .Returns(Task.CompletedTask); + em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), - It.IsAny())) - .Returns(Task.CompletedTask); + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), + It.IsAny())) + .Returns(Task.CompletedTask); var context = CreateDefaultContext( - todayPrice: new NordPoolPrice { Prices = todayPrices }, - tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices }); + todayPrice: new NordPoolPrice { Prices = todayPrices }, + tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices }); // Act await _sut.UpdateEntitiesAsync(context); @@ -629,8 +674,10 @@ public class NordPoolEntityServiceTests capturedAttributes.Should().NotBeNull(); var json = JsonSerializer.Serialize(capturedAttributes); var byteCount = Encoding.UTF8.GetByteCount(json); - byteCount.Should().BeLessThan(haAttributeByteLimitBytes, - $"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit"); + + byteCount.Should() + .BeLessThan(haAttributeByteLimitBytes, + $"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit"); } [Theory] @@ -640,15 +687,16 @@ public class NordPoolEntityServiceTests [InlineData(1234.5, "1234.50")] [InlineData(17.916, "17.92")] public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, - string expected) + string expected) { // Arrange var context = CreateDefaultContext(price); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); @@ -662,14 +710,17 @@ public class NordPoolEntityServiceTests { // Arrange object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny())) - .Callback((_, attrs) => capturedAttributes = attrs) - .Returns(Task.CompletedTask); + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) - .Returns(Task.CompletedTask); + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) + .Returns(Task.CompletedTask); var context = CreateDefaultContext() with { @@ -700,15 +751,18 @@ public class NordPoolEntityServiceTests { // Arrange object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) - .Callback((_, attrs) => capturedAttributes = attrs) - .Returns(Task.CompletedTask); + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), - It.IsAny())) - .Returns(Task.CompletedTask); + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), + It.IsAny())) + .Returns(Task.CompletedTask); var first = new CheapestIntervalResult { @@ -717,6 +771,7 @@ public class NordPoolEntityServiceTests Price = 4.93, Rank = 1 }; + var second = new CheapestIntervalResult { Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc), @@ -746,8 +801,10 @@ public class NordPoolEntityServiceTests capturedAttributes.Should().NotBeNull(); var attributes = capturedAttributes!; var type = attributes.GetType(); + ((IEnumerable)type.GetProperty("intervals")!.GetValue(attributes)!).Should() - .HaveCount(2); + .HaveCount(2); + type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30); type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true); type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O")); @@ -763,15 +820,18 @@ public class NordPoolEntityServiceTests { // Arrange object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) - .Callback((_, attrs) => capturedAttributes = attrs) - .Returns(Task.CompletedTask); + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), - It.IsAny())) - .Returns(Task.CompletedTask); + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), + It.IsAny())) + .Returns(Task.CompletedTask); var context = CreateDefaultContext() with { CheapestIntervals = null }; @@ -794,18 +854,22 @@ public class NordPoolEntityServiceTests { // Arrange object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) - .Callback((_, attrs) => capturedAttributes = attrs) - .Returns(Task.CompletedTask); + em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => - em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), - It.IsAny())) - .Returns(Task.CompletedTask); + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), + It.IsAny())) + .Returns(Task.CompletedTask); var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); + var todayPrice = new NordPoolPrice { Prices = @@ -815,6 +879,7 @@ public class NordPoolEntityServiceTests new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 } ] }; + var tomorrowPrice = new NordPoolPrice { Prices = @@ -823,6 +888,7 @@ public class NordPoolEntityServiceTests { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 } ] }; + var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice); // Act @@ -843,42 +909,49 @@ public class NordPoolEntityServiceTests { // Arrange _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc); - var todayPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice - { - Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), - End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), - Price = 10.0 - }).ToList(); - var tomorrowPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice - { - Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), - End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), - Price = 10.0 - }).ToList(); + + var todayPrices = Enumerable.Range(0, 100) + .Select(i => new NordPoolDayPrice + { + Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), + End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), + Price = 10.0 + }) + .ToList(); + + var tomorrowPrices = Enumerable.Range(0, 100) + .Select(i => new NordPoolDayPrice + { + Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), + End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), + Price = 10.0 + }) + .ToList(); var context = CreateDefaultContext( - todayPrice: new NordPoolPrice { Prices = todayPrices }, - tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices }); + todayPrice: new NordPoolPrice { Prices = todayPrices }, + tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices }); // Act await _sut.UpdateEntitiesAsync(context); // Assert _loggerMock.Verify( - l => l.Log( - LogLevel.Warning, - It.IsAny(), - It.Is((state, _) => - state != null && state.ToString()!.Contains("exceeds expected maximum")), - It.IsAny(), - It.IsAny>()), - Times.Once); + l => l.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => + state != null && state.ToString()!.Contains("exceeds expected maximum")), + It.IsAny(), + It.IsAny>()), + Times.Once); } #endregion @@ -895,6 +968,7 @@ public class NordPoolEntityServiceTests data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled)); data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled)); data.Add("cleanup entities", sut => sut.CleanupEntitiesAsync(cancelled)); + return data; } diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index e6da622..2a39fb3 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -1,3 +1,5 @@ +#region + using System.Reactive.Concurrency; using BoilerMonitor.Models; using FluentAssertions; @@ -11,6 +13,8 @@ using NordPoolManager; using NordPoolManager.Interface; using NordPoolManager.Models; +#endregion + namespace NordPool.Manager.Tests; public class NordPoolInitTests @@ -39,14 +43,18 @@ public class NordPoolInitTests _services = new Services(_haContextMock.Object); _priceServiceMock - .Setup(p => p.FetchPricesAsync(It.IsAny>>())) - .Returns(Task.CompletedTask); + .Setup(p => p.FetchPricesAsync(It.IsAny>>())) + .Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); _entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0); _priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny())).Returns(false); _priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0); @@ -54,36 +62,39 @@ public class NordPoolInitTests _priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null); _priceServiceMock.SetupGet(p => p.CurrentPrice).Returns(0.0); _priceServiceMock.SetupGet(p => p.LastUpdatedDate).Returns((DateTime?)null); + _cheapestIntervalsFinderMock - .Setup(c => c.IsCurrentIntervalCheap(It.IsAny>(), - It.IsAny())) - .Returns(false); - _boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig - { - IntervalCount = 4, - PriceCap = double.MaxValue, - Deadline = DateTime.Today.AddDays(1), - SkipPriceCap = false - }); + .Setup(c => c.IsCurrentIntervalCheap(It.IsAny>(), + It.IsAny())) + .Returns(false); + + _boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()) + .Returns(new BoilerConfig + { + IntervalCount = 4, + PriceCap = double.MaxValue, + Deadline = DateTime.Today.AddDays(1), + SkipPriceCap = false + }); } private NordPoolInit CreateSut(NordPoolOptions? nordPoolOptions = null) { var options = Options.Create( - nordPoolOptions ?? new NordPoolOptions { CleanupEntitiesOnStartup = false }); + nordPoolOptions ?? new NordPoolOptions { CleanupEntitiesOnStartup = false }); return new NordPoolInit( - _entities, - _services, - _haContextMock.Object, - _loggerMock.Object, - _priceServiceMock.Object, - _entityServiceMock.Object, - _schedulerMock.Object, - _cheapestIntervalsFinderMock.Object, - _boilerConfigProviderMock.Object, - options, - TimeProvider.System); + _entities, + _services, + _haContextMock.Object, + _loggerMock.Object, + _priceServiceMock.Object, + _entityServiceMock.Object, + _schedulerMock.Object, + _cheapestIntervalsFinderMock.Object, + _boilerConfigProviderMock.Object, + options, + TimeProvider.System); } [Fact] @@ -107,29 +118,34 @@ public class NordPoolInitTests // The constructor also starts the same init flow in the background, so calls may happen more than once. _entityServiceMock.Verify( - es => es.CleanupEntitiesAsync(It.IsAny()), - cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never()); + es => es.CleanupEntitiesAsync(It.IsAny()), + cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never()); + _entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny(), It.IsAny()), - Times.AtLeastOnce); + Times.AtLeastOnce); + _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny()), Times.AtLeastOnce); + _entityServiceMock.Verify( - es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), - Times.AtLeastOnce); + es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), + Times.AtLeastOnce); } [Fact] public async Task InitializeAsync_WhenCreatingEntitiesFails_ShouldRethrow() { var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false }); + _entityServiceMock - .Setup(es => es.CreateEntitiesAsync(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("create failed")); + .Setup(es => es.CreateEntitiesAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("create failed")); var act = sut.InitializeAsync; await act.Should().ThrowAsync().WithMessage("create failed"); _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny()), Times.Never); + _entityServiceMock.Verify( - es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), Times.Never); + es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), Times.Never); } } \ No newline at end of file diff --git a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs index ebdd8cf..afcc0d4 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -1,4 +1,6 @@ -using System.Globalization; +#region + +using System.Globalization; using System.Text.Json; using AutoMapper; using FluentAssertions; @@ -8,6 +10,8 @@ using NordPool.Models; using NordPool.Models.Dtos; using NordPoolManager; +#endregion + namespace NordPool.Manager.Tests; public class NordPoolPriceServiceTests @@ -110,12 +114,15 @@ public class NordPoolPriceServiceTests { // Arrange & Act — iterate over a full UTC day; CET conversion produces 96 unique quarter indices var indices = new HashSet(); + for (var hour = 0; hour < 24; hour++) - for (var minute = 0; minute < 60; minute += 15) { - var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); - var index = NordPoolPriceService.GetTimeQuarterIndex(date); - indices.Add(index); + for (var minute = 0; minute < 60; minute += 15) + { + var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); + var index = NordPoolPriceService.GetTimeQuarterIndex(date); + indices.Add(index); + } } // Assert @@ -127,8 +134,12 @@ public class NordPoolPriceServiceTests [Theory] [InlineData(2026, 1, 15, 8, 0, 36)] // CET winter (UTC+1): UTC 08:00 = CET 09:00 -> index 36 [InlineData(2026, 7, 15, 8, 0, 40)] // CEST summer (UTC+2): UTC 08:00 = CEST 10:00 -> index 40 - public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, int month, int day, int hour, - int minute, int expectedIndex) + public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, + int month, + int day, + int hour, + int minute, + int expectedIndex) { // Arrange var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc); @@ -245,7 +256,7 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() + new NordPoolDayPrice { Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture), End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0 @@ -254,7 +265,7 @@ public class NordPoolPriceServiceTests }; _mapperMock.Setup(m => m.Map(It.IsAny())) - .Returns(expectedPrice); + .Returns(expectedPrice); // Act var result = _sut.ParseNordPoolResult(jsonElement); @@ -285,7 +296,7 @@ public class NordPoolPriceServiceTests var jsonElement = JsonSerializer.Deserialize(jsonString); _mapperMock.Setup(m => m.Map(It.IsAny())) - .Returns((NordPoolPrice)null!); + .Returns((NordPoolPrice)null!); // Act var result = _sut.ParseNordPoolResult(jsonElement); @@ -301,7 +312,7 @@ public class NordPoolPriceServiceTests var jsonElement = JsonSerializer.Deserialize("{}"); _mapperMock.Setup(m => m.Map(It.IsAny())) - .Returns(new NordPoolPrice()); + .Returns(new NordPoolPrice()); // Act var result = _sut.ParseNordPoolResult(jsonElement); @@ -322,9 +333,9 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, - new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 }, - new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } + new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, + new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 }, + new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } } }; @@ -347,9 +358,9 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, - new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }, - new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } + new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, + new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }, + new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } } }; @@ -388,7 +399,7 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = startTime, End = endTime, Price = 81.0 } + new NordPoolDayPrice { Start = startTime, End = endTime, Price = 81.0 } } }; @@ -424,8 +435,8 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null }, - new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null } + new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null }, + new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null } } }; @@ -445,7 +456,7 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 } + new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 } } }; @@ -469,12 +480,14 @@ public class NordPoolPriceServiceTests var prices = new List(); for (var i = 0; i < 96; i++) + { prices.Add(new NordPoolDayPrice { Start = now.AddMinutes(i * 15), End = now.AddMinutes((i + 1) * 15), Price = 5.0 + i * 0.22 }); + } _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; @@ -532,8 +545,11 @@ public class NordPoolPriceServiceTests var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var prices = new List(); + for (var i = 0; i < 96; i++) + { prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 }); + } _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.DayQuartersIndex = expectedIndex; @@ -552,8 +568,11 @@ public class NordPoolPriceServiceTests { // Arrange var prices = new List(); + for (var i = 0; i < 96; i++) + { prices.Add(new NordPoolDayPrice { Price = null }); + } _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.CurrentPrice = 17.91; @@ -572,8 +591,11 @@ public class NordPoolPriceServiceTests { // Arrange var prices = new List(); + for (var i = 0; i < 96; i++) + { prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 }); + } _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.DayQuartersIndex = -1; @@ -595,9 +617,10 @@ public class NordPoolPriceServiceTests { // Arrange — negative and zero spot prices are valid NordPool scenarios var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = NordPoolTestData.CreateIntervals( - NordPoolConsts.MaxDailyIntervals, - i => i == index ? expectedPrice : 10.0); + NordPoolConsts.MaxDailyIntervals, + i => i == index ? expectedPrice : 10.0); _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.CurrentPrice = 17.91; @@ -616,9 +639,10 @@ public class NordPoolPriceServiceTests { // Arrange — fewer prices than the current quarter index (e.g. partial day payload) var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = Enumerable.Range(0, index) - .Select(i => new NordPoolDayPrice { Price = 10.0 + i }) - .ToList(); + .Select(i => new NordPoolDayPrice { Price = 10.0 + i }) + .ToList(); _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.CurrentPrice = 17.91; @@ -637,9 +661,10 @@ public class NordPoolPriceServiceTests { // Arrange var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) - .Select(_ => new NordPoolDayPrice { Price = 99.0 }) - .ToList(); + .Select(_ => new NordPoolDayPrice { Price = 99.0 }) + .ToList(); _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.DayQuartersIndex = index; @@ -658,9 +683,10 @@ public class NordPoolPriceServiceTests { // Arrange var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) - .Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 }) - .ToList(); + .Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 }) + .ToList(); _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.CurrentPrice = 17.91; @@ -687,6 +713,7 @@ public class NordPoolPriceServiceTests Task Fetch(DateOnly date) { requestedDates.Add(date); + return Task.FromResult(CreatePrices(1.5)); } @@ -718,10 +745,11 @@ public class NordPoolPriceServiceTests // Act await _sut.FetchPricesAsync(_ => - { - delegateCalled = true; - return Task.FromResult(CreatePrices(3.0)); - }); + { + delegateCalled = true; + + return Task.FromResult(CreatePrices(3.0)); + }); // Assert delegateCalled.Should().BeFalse(); @@ -761,7 +789,7 @@ public class NordPoolPriceServiceTests ("today prices are empty", today, new NordPoolPrice { Prices = [] }, CreatePrices(18.71), true), ("today and tomorrow prices present", today, CreatePrices(12.50), CreatePrices(18.71), false), ("price values are null but entries exist", today, CreatePrices((double?)null), - CreatePrices((double?)null), false), + CreatePrices((double?)null), false), ("all price payloads are null", today, null, null, true) ]; @@ -786,10 +814,12 @@ public class NordPoolPriceServiceTests // Arrange — tomorrow's prices are not published before 13:00, so cached data is acceptable until then var today = DateOnly.FromDateTime(DateTime.Now); _sut.LastFetchedDate = today; + _sut.TodayNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 12.50 } } + Prices = new List { new NordPoolDayPrice { Price = 12.50 } } }; + _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null }; // Act @@ -805,10 +835,12 @@ public class NordPoolPriceServiceTests // Arrange var today = DateOnly.FromDateTime(DateTime.Now); _sut.LastFetchedDate = today; + _sut.TodayNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 12.50 } } + Prices = new List { new NordPoolDayPrice { Price = 12.50 } } }; + _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List() }; // Act @@ -828,13 +860,14 @@ public class NordPoolPriceServiceTests // Arrange var tomorrow = new NordPoolPrice { - Prices = new List { new() { Price = 18.71 } } + Prices = new List { new NordPoolDayPrice { Price = 18.71 } } }; _sut.TodayNordPoolPrice = new NordPoolPrice { - Prices = new List { new() { Price = 12.50 } } + Prices = new List { new NordPoolDayPrice { Price = 12.50 } } }; + _sut.TomorrowNordPoolPrice = tomorrow; _sut.DayQuartersIndex = 48; var today = new DateOnly(2026, 4, 1); @@ -855,7 +888,7 @@ public class NordPoolPriceServiceTests [Fact] public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice() { - NordPoolPrice?[] unusablePrices = [null, new() { Prices = null }, new() { Prices = [] }]; + NordPoolPrice?[] unusablePrices = [null, new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = [] }]; foreach (var tomorrow in unusablePrices) { @@ -900,11 +933,12 @@ public class NordPoolPriceServiceTests // Arrange var previousToday = new NordPoolPrice { - Prices = new List { new() { Price = 12.50 } } + Prices = new List { new NordPoolDayPrice { Price = 12.50 } } }; + var tomorrow = new NordPoolPrice { - Prices = new List { new() { Price = 18.71 } } + Prices = new List { new NordPoolDayPrice { Price = 18.71 } } }; _sut.TodayNordPoolPrice = previousToday; diff --git a/NordPool.Manager.Tests/NordPoolTestData.cs b/NordPool.Manager.Tests/NordPoolTestData.cs index 163aa1d..30b4c6e 100644 --- a/NordPool.Manager.Tests/NordPoolTestData.cs +++ b/NordPool.Manager.Tests/NordPoolTestData.cs @@ -1,5 +1,9 @@ +#region + using NordPool.Models; +#endregion + namespace NordPool.Manager.Tests; /// @@ -8,7 +12,7 @@ namespace NordPool.Manager.Tests; /// internal static class NordPoolTestData { - public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); + public static readonly DateTime DayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); /// /// Builds a contiguous set of 15-minute intervals starting at . @@ -23,12 +27,12 @@ internal static class NordPoolTestData return [ .. Enumerable.Range(0, count) - .Select(i => new NordPoolDayPrice - { - Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval), - End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), - Price = priceFactory(i) - }) + .Select(i => new NordPoolDayPrice + { + Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval), + End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), + Price = priceFactory(i) + }) ]; } @@ -41,8 +45,8 @@ internal static class NordPoolTestData var start = dayStart ?? DayStart; return CreateIntervals( - NordPoolConsts.MaxDailyIntervals, - i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2), - start); + NordPoolConsts.MaxDailyIntervals, + i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2), + start); } } \ No newline at end of file diff --git a/NordPool.Manager/CheapestIntervalsFinder.cs b/NordPool.Manager/CheapestIntervalsFinder.cs index f205cdf..04e3ab5 100644 --- a/NordPool.Manager/CheapestIntervalsFinder.cs +++ b/NordPool.Manager/CheapestIntervalsFinder.cs @@ -1,7 +1,11 @@ +#region + using Microsoft.Extensions.Logging; using NordPool.Models; using NordPoolManager.Interface; +#endregion + namespace NordPoolManager; public class CheapestIntervalsFinder(ILogger logger) : ICheapestIntervalsFinder @@ -23,24 +27,24 @@ public class CheapestIntervalsFinder(ILogger logger) : } var eligible = prices.Prices - .Where(p => p is { Start: not null, End: not null, Price: not null }) - .Where(p => p.End!.Value <= deadline) - .Where(p => p.Price!.Value <= priceCap) - .OrderBy(p => p.Price!.Value) - .ThenBy(p => p.Start!.Value) - .Take(numberOfIntervals) - .ToList(); + .Where(p => p is { Start: not null, End: not null, Price: not null }) + .Where(p => p.End!.Value <= deadline) + .Where(p => p.Price!.Value <= priceCap) + .OrderBy(p => p.Price!.Value) + .ThenBy(p => p.Start!.Value) + .Take(numberOfIntervals) + .ToList(); var ranked = eligible - .Select((p, index) => new CheapestIntervalResult - { - Start = p.Start!.Value, - End = p.End!.Value, - Price = p.Price!.Value, - Rank = index + 1 - }) - .OrderBy(r => r.Start) - .ToList(); + .Select((p, index) => new CheapestIntervalResult + { + Start = p.Start!.Value, + End = p.End!.Value, + Price = p.Price!.Value, + Rank = index + 1 + }) + .OrderBy(r => r.Start) + .ToList(); return ranked; } diff --git a/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs b/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs index cfed1a7..c80f59d 100644 --- a/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs +++ b/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs @@ -1,11 +1,17 @@ +#region + using NordPool.Models; +#endregion + namespace NordPoolManager.Interface; public interface ICheapestIntervalsFinder { - IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, - double priceCap, DateTime deadline); + IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, + int numberOfIntervals, + double priceCap, + DateTime deadline); bool IsCurrentIntervalCheap(IReadOnlyList cheapestIntervals, DateTime utcNow); } \ No newline at end of file diff --git a/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs b/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs index 7c9b23e..4ea6836 100644 --- a/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs +++ b/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs @@ -1,5 +1,9 @@ +#region + using BoilerMonitor.Models; +#endregion + namespace NordPoolManager.Interface; /// diff --git a/NordPool.Manager/Interface/INordPoolEntityService.cs b/NordPool.Manager/Interface/INordPoolEntityService.cs index 0ff21b0..398ae85 100644 --- a/NordPool.Manager/Interface/INordPoolEntityService.cs +++ b/NordPool.Manager/Interface/INordPoolEntityService.cs @@ -1,5 +1,9 @@ +#region + using NordPoolManager.Models; +#endregion + namespace NordPoolManager.Interface; public interface INordPoolEntityService diff --git a/NordPool.Manager/Interface/INordPoolPriceService.cs b/NordPool.Manager/Interface/INordPoolPriceService.cs index 97195d1..b9e172f 100644 --- a/NordPool.Manager/Interface/INordPoolPriceService.cs +++ b/NordPool.Manager/Interface/INordPoolPriceService.cs @@ -1,6 +1,10 @@ +#region + using System.Text.Json; using NordPool.Models; +#endregion + namespace NordPoolManager.Interface; public interface INordPoolPriceService diff --git a/NordPool.Manager/Models/EntityUpdateContext.cs b/NordPool.Manager/Models/EntityUpdateContext.cs index fb4b7be..e68315a 100644 --- a/NordPool.Manager/Models/EntityUpdateContext.cs +++ b/NordPool.Manager/Models/EntityUpdateContext.cs @@ -1,5 +1,9 @@ +#region + using NordPool.Models; +#endregion + namespace NordPoolManager.Models; public record EntityUpdateContext diff --git a/NordPool.Manager/NordPoolBoilerConfigProvider.cs b/NordPool.Manager/NordPoolBoilerConfigProvider.cs index d961be9..3ffa2df 100644 --- a/NordPool.Manager/NordPoolBoilerConfigProvider.cs +++ b/NordPool.Manager/NordPoolBoilerConfigProvider.cs @@ -1,6 +1,10 @@ +#region + using BoilerMonitor.Models; using NordPoolManager.Interface; +#endregion + namespace NordPoolManager; /// diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index 916383c..00875f6 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; @@ -6,6 +8,8 @@ using NordPool.Models; using NordPoolManager.Interface; using NordPoolManager.Models; +#endregion + namespace NordPoolManager; public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger logger) @@ -35,16 +39,16 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< var entitiesToCreate = GetInitEntitiesList(unitOfMeasurement); var createTasks = entitiesToCreate.Select(async nordPoolEntity => - { - try - { - await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", nordPoolEntity.EntityId); - } - }); + { + try + { + await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", nordPoolEntity.EntityId); + } + }); await Task.WhenAll(createTasks).ConfigureAwait(false); } @@ -54,14 +58,15 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< cancellationToken.ThrowIfCancellationRequested(); await Task.WhenAll( - ResetLastUpdateTimeAsync(), - ResetCurrentPriceAsync(), - ResetTodayPricesAsync(), - ResetTomorrowPricesAsync(), - ResetTodayTomorrowPricesAsync(), - ResetCheapestIntervalsAsync(), - ResetFetchPricesButtonAsync() - ).ConfigureAwait(false); + ResetLastUpdateTimeAsync(), + ResetCurrentPriceAsync(), + ResetTodayPricesAsync(), + ResetTomorrowPricesAsync(), + ResetTodayTomorrowPricesAsync(), + ResetCheapestIntervalsAsync(), + ResetFetchPricesButtonAsync() + ) + .ConfigureAwait(false); } public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default) @@ -79,8 +84,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries) { logger.LogWarning( - "Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", - mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries); + "Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", + mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries); } var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; @@ -88,8 +93,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", - cheapestCount, ctx.IsNowCheap); + "Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", + cheapestCount, ctx.IsNowCheap); } var updateTasks = new[] @@ -117,6 +122,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< catch (Exception ex) { logger.LogError(ex, "Error cleaning up NordPool entities"); + throw; } } @@ -124,87 +130,101 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< private async Task ResetLastUpdateTimeAsync() { await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false); + await SetEntityAttributesSafe(LastUpdateTimeEntityId, new - { - friendly_name = "NordPool last update time" - }).ConfigureAwait(false); + { + friendly_name = "NordPool last update time" + }) + .ConfigureAwait(false); } private async Task ResetCurrentPriceAsync() { await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false); + await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new - { - unit_of_measurement = (string?)null, - device_class = "monetary", - state_class = "measurement", - friendly_name = "NordPool current price", - last_updated = (string?)null, - last_api_fetch = (string?)null, - using_cached_data = false, - current_quarter_index = 0 - }).ConfigureAwait(false); + { + unit_of_measurement = (string?)null, + device_class = "monetary", + state_class = "measurement", + friendly_name = "NordPool current price", + last_updated = (string?)null, + last_api_fetch = (string?)null, + using_cached_data = false, + current_quarter_index = 0 + }) + .ConfigureAwait(false); } private async Task ResetTodayPricesAsync() { await SetEntityStateSafe(TodayPricesEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(TodayPricesEntityId, new - { - prices = Array.Empty(), - friendly_name = "NordPool today prices", - last_updated = (string?)null - }).ConfigureAwait(false); + { + prices = Array.Empty(), + friendly_name = "NordPool today prices", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetTomorrowPricesAsync() { await SetEntityStateSafe(TomorrowPricesEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(TomorrowPricesEntityId, new - { - prices = Array.Empty(), - friendly_name = "NordPool tomorrow prices", - last_updated = (string?)null - }).ConfigureAwait(false); + { + prices = Array.Empty(), + friendly_name = "NordPool tomorrow prices", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetTodayTomorrowPricesAsync() { await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown").ConfigureAwait(false); + await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new - { - prices = Array.Empty(), - prices_count = 0, - friendly_name = "NordPool today and tomorrow prices", - last_updated = (string?)null - }).ConfigureAwait(false); + { + prices = Array.Empty(), + prices_count = 0, + friendly_name = "NordPool today and tomorrow prices", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetCheapestIntervalsAsync() { await SetEntityStateSafe(CheapestIntervalsEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(CheapestIntervalsEntityId, new - { - intervals = Array.Empty(), - configured_hours = 0.0, - configured_interval_count = 0, - configured_price_cap = 0.0, - configured_ready_by = "", - total_heating_minutes = 0, - is_now_cheap = false, - next_cheap_interval = (string?)null, - friendly_name = "NordPool cheapest boiler intervals", - last_updated = (string?)null - }).ConfigureAwait(false); + { + intervals = Array.Empty(), + configured_hours = 0.0, + configured_interval_count = 0, + configured_price_cap = 0.0, + configured_ready_by = string.Empty, + total_heating_minutes = 0, + is_now_cheap = false, + next_cheap_interval = (string?)null, + friendly_name = "NordPool cheapest boiler intervals", + last_updated = (string?)null + }) + .ConfigureAwait(false); } private async Task ResetFetchPricesButtonAsync() { await SetEntityStateSafe(NordPoolConsts.FetchPricesButtonEntityId, "unknown").ConfigureAwait(false); + await SetEntityAttributesSafe(NordPoolConsts.FetchPricesButtonEntityId, new - { - friendly_name = "NordPool fetch prices" - }).ConfigureAwait(false); + { + friendly_name = "NordPool fetch prices" + }) + .ConfigureAwait(false); } private async Task UpdateLastUpdateTimeAsync(string updateTimeState) @@ -215,71 +235,82 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp) { await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false); + await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new - { - unit_of_measurement = ctx.UnitOfMeasurement, - device_class = "monetary", - state_class = "measurement", - friendly_name = "NordPool current price", - last_updated = timestamp, - last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture), - using_cached_data = ctx.UsingCachedData, - current_quarter_index = ctx.DayQuartersIndex - }).ConfigureAwait(false); + { + unit_of_measurement = ctx.UnitOfMeasurement, + device_class = "monetary", + state_class = "measurement", + friendly_name = "NordPool current price", + last_updated = timestamp, + last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture), + using_cached_data = ctx.UsingCachedData, + current_quarter_index = ctx.DayQuartersIndex + }) + .ConfigureAwait(false); } private async Task UpdateTodayPricesAsync(EntityUpdateContext ctx, int todayPricesCount, string timestamp) { await SetEntityStateSafe(TodayPricesEntityId, todayPricesCount.ToString()).ConfigureAwait(false); + await SetEntityAttributesSafe(TodayPricesEntityId, new - { - prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(), - friendly_name = "NordPool today prices", - last_updated = timestamp - }).ConfigureAwait(false); + { + prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(), + friendly_name = "NordPool today prices", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateTomorrowPricesAsync(EntityUpdateContext ctx, int tomorrowPricesCount, string timestamp) { await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()).ConfigureAwait(false); + await SetEntityAttributesSafe(TomorrowPricesEntityId, new - { - prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(), - friendly_name = "NordPool tomorrow prices", - last_updated = timestamp - }).ConfigureAwait(false); + { + prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(), + friendly_name = "NordPool tomorrow prices", + last_updated = timestamp + }) + .ConfigureAwait(false); } - private async Task UpdateTodayTomorrowPricesAsync(List mergedPrices, string updateTimeState, - string timestamp) + private async Task UpdateTodayTomorrowPricesAsync(List mergedPrices, + string updateTimeState, + string timestamp) { await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false); + await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new - { - prices = mergedPrices.ToCompact(), - prices_count = mergedPrices.Count, - friendly_name = "NordPool today and tomorrow prices", - last_updated = timestamp - }).ConfigureAwait(false); + { + prices = mergedPrices.ToCompact(), + prices_count = mergedPrices.Count, + friendly_name = "NordPool today and tomorrow prices", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateCheapestIntervalsAsync(EntityUpdateContext ctx, int cheapestCount, string timestamp) { await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()).ConfigureAwait(false); + await SetEntityAttributesSafe(CheapestIntervalsEntityId, new - { - intervals = ctx.CheapestIntervals ?? [], - configured_hours = ctx.ConfiguredHours, - configured_interval_count = ctx.ConfiguredIntervalCount, - configured_price_cap = ctx.ConfiguredPriceCap, - skip_price_cap = ctx.SkipPriceCap, - configured_ready_by = ctx.ConfiguredReadyBy, - total_heating_minutes = cheapestCount * NordPoolConsts.MinutesPerInterval, - is_now_cheap = ctx.IsNowCheap, - next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture), - friendly_name = "NordPool cheapest boiler intervals", - last_updated = timestamp - }).ConfigureAwait(false); + { + intervals = ctx.CheapestIntervals ?? [], + configured_hours = ctx.ConfiguredHours, + configured_interval_count = ctx.ConfiguredIntervalCount, + configured_price_cap = ctx.ConfiguredPriceCap, + skip_price_cap = ctx.SkipPriceCap, + configured_ready_by = ctx.ConfiguredReadyBy, + total_heating_minutes = cheapestCount * NordPoolConsts.MinutesPerInterval, + is_now_cheap = ctx.IsNowCheap, + next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture), + friendly_name = "NordPool cheapest boiler intervals", + last_updated = timestamp + }) + .ConfigureAwait(false); } internal static ICollection GetInitEntitiesList(string? unitOfMeasurement) @@ -321,9 +352,9 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< return [ .. todayList - .Concat(tomorrowList) - .Where(p => p is { Start: not null }) - .OrderBy(p => p.Start!.Value) + .Concat(tomorrowList) + .Where(p => p is { Start: not null }) + .OrderBy(p => p.Start!.Value) ]; } diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index 133c2f8..9122af7 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using System.Reactive.Concurrency; using BoilerMonitor.Models; @@ -12,6 +14,8 @@ using NordPool.Models; using NordPoolManager.Interface; using NordPoolManager.Models; +#endregion + namespace NordPoolManager; [NetDaemonApp] @@ -67,7 +71,10 @@ public class NordPoolInit { await Task.Delay(TimeSpan.FromSeconds(3)); - if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync(); + if (_options.CleanupEntitiesOnStartup) + { + await _entityService.CleanupEntitiesAsync(); + } await _entityService.CreateEntitiesAsync(UnitOfMeasurement); await _entityService.ResetEntitiesAsync(); @@ -78,6 +85,7 @@ public class NordPoolInit catch (Exception ex) { _logger.LogError(ex, "Error initializing NordPool prices"); + throw; } } @@ -123,7 +131,7 @@ public class NordPoolInit } await _priceService.FetchPricesAsync(FetchPricesForDateAsync); - + _priceService.UpdateCurrentPrice(); var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration(); @@ -139,13 +147,13 @@ public class NordPoolInit private async Task FetchPricesForDateAsync(DateOnly date) { var nordPoolPricesDto = await _services.Nordpool.GetPricesForDateAsync( - new NordpoolGetPricesForDateParameters - { - Areas = "LT", - ConfigEntry = NordPoolConsts.ConfigEntry, - Currency = "EUR", - Date = date - }); + new NordpoolGetPricesForDateParameters + { + Areas = "LT", + ConfigEntry = NordPoolConsts.ConfigEntry, + Currency = "EUR", + Date = date + }); return _priceService.ParseAndAdjust(nordPoolPricesDto); } @@ -153,12 +161,13 @@ public class NordPoolInit private void SubscribeToFetchPricesButton() { var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId); + button.StateChanges() - .Subscribe(_ => - { - _logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update"); - Task.Run(UpdatePricesAsync); - }); + .Subscribe(_ => + { + _logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update"); + Task.Run(UpdatePricesAsync); + }); } private void UpdateCheapestIntervals(BoilerConfig config) @@ -198,9 +207,9 @@ public class NordPoolInit _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); var nextCheapInterval = CheapestIntervals? - .Where(i => i.Start > currentDateTime) - .OrderBy(i => i.Start) - .FirstOrDefault(); + .Where(i => i.Start > currentDateTime) + .OrderBy(i => i.Start) + .FirstOrDefault(); var context = new EntityUpdateContext { diff --git a/NordPool.Manager/NordPoolPriceService.cs b/NordPool.Manager/NordPoolPriceService.cs index bc573fb..e7c0319 100644 --- a/NordPool.Manager/NordPoolPriceService.cs +++ b/NordPool.Manager/NordPoolPriceService.cs @@ -1,3 +1,5 @@ +#region + using System.Text.Json; using AutoMapper; using Microsoft.Extensions.Logging; @@ -6,6 +8,8 @@ using NordPool.Models.Dtos; using NordPoolManager.Interface; using NordPoolManager.Models.Consts; +#endregion + namespace NordPoolManager; /// @@ -61,7 +65,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0); } - if (DayQuartersIndex == index) return; + if (DayQuartersIndex == index) + { + return; + } if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index) { @@ -91,13 +98,25 @@ public class NordPoolPriceService(IMapper mapper, ILogger public bool ShouldFetchNewPrices(DateOnly date) { - if (!LastFetchedDate.HasValue) return true; + if (!LastFetchedDate.HasValue) + { + return true; + } - if (LastFetchedDate.Value < date) return true; + if (LastFetchedDate.Value < date) + { + return true; + } - if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true; + if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) + { + return true; + } - if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false; + if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) + { + return false; + } var currentHour = DateTime.Now.Hour; @@ -107,8 +126,8 @@ public class NordPoolPriceService(IMapper mapper, ILogger public void RollOverPrices(DateOnly date) { TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } - ? TomorrowNordPoolPrice - : new NordPoolPrice(); + ? TomorrowNordPoolPrice + : new NordPoolPrice(); TomorrowNordPoolPrice = null; @@ -125,13 +144,16 @@ public class NordPoolPriceService(IMapper mapper, ILogger internal NordPoolPrice ParseNordPoolResult(JsonElement? element) { - if (!element.HasValue) return new NordPoolPrice(); + if (!element.HasValue) + { + return new NordPoolPrice(); + } var priceResult = element.Value.Deserialize(); return priceResult != null - ? mapper.Map(priceResult) - : new NordPoolPrice(); + ? mapper.Map(priceResult) + : new NordPoolPrice(); } internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice) @@ -141,11 +163,17 @@ public class NordPoolPriceService(IMapper mapper, ILogger Prices = new List() }; - if (todayNordPoolPrice.Prices is null) return recalculatedPrice; + if (todayNordPoolPrice.Prices is null) + { + return recalculatedPrice; + } foreach (var price in todayNordPoolPrice.Prices) { - if (price.Price is null) continue; + if (price.Price is null) + { + continue; + } recalculatedPrice.Prices.Add(new NordPoolDayPrice { @@ -179,6 +207,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger private async Task FetchPricesForDateWithRetryAsync(DateOnly date, Func> fetchPricesForDate) { for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++) + { try { return await fetchPricesForDate(date); @@ -193,8 +222,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger catch (Exception ex) { logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt); + break; } + } logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date); diff --git a/NordPool.Manager/NordPoolServiceRegistration.cs b/NordPool.Manager/NordPoolServiceRegistration.cs index 1814adb..dd2ed9c 100644 --- a/NordPool.Manager/NordPoolServiceRegistration.cs +++ b/NordPool.Manager/NordPoolServiceRegistration.cs @@ -1,7 +1,11 @@ +#region + using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; using NordPoolManager.Interface; +#endregion + namespace NordPoolManager; public static class NordPoolServiceRegistration @@ -9,13 +13,14 @@ public static class NordPoolServiceRegistration public static IServiceCollection AddNordPool(this IServiceCollection services) { services - .AddNetDaemonApp() + .AddNetDaemonApp() + // Singleton is safe: NordPoolPriceService holds no IHaContext/generated // entity dependency. The HA price fetch call lives in NordPoolInit. - .AddSingleton() - .AddTransient() - .AddTransient() - .AddScoped(); + .AddSingleton() + .AddTransient() + .AddTransient() + .AddScoped(); return services; } diff --git a/NordPool.Models/CheapestIntervalResult.cs b/NordPool.Models/CheapestIntervalResult.cs index 6555e0d..a7d9e9a 100644 --- a/NordPool.Models/CheapestIntervalResult.cs +++ b/NordPool.Models/CheapestIntervalResult.cs @@ -1,14 +1,22 @@ +#region + using System.Text.Json.Serialization; +#endregion + namespace NordPool.Models; public class CheapestIntervalResult { - [JsonPropertyName("start")] public DateTime Start { get; init; } + [JsonPropertyName("start")] + public DateTime Start { get; init; } - [JsonPropertyName("end")] public DateTime End { get; init; } + [JsonPropertyName("end")] + public DateTime End { get; init; } - [JsonPropertyName("price")] public double Price { get; init; } + [JsonPropertyName("price")] + public double Price { get; init; } - [JsonPropertyName("rank")] public int Rank { get; init; } + [JsonPropertyName("rank")] + public int Rank { get; init; } } \ No newline at end of file diff --git a/NordPool.Models/CompactNordPoolDayPrice.cs b/NordPool.Models/CompactNordPoolDayPrice.cs index 57f96e1..bf862d2 100644 --- a/NordPool.Models/CompactNordPoolDayPrice.cs +++ b/NordPool.Models/CompactNordPoolDayPrice.cs @@ -1,6 +1,10 @@ +#region + using System.Text.Json; using System.Text.Json.Serialization; +#endregion + namespace NordPool.Models; [JsonConverter(typeof(CompactNordPoolDayPriceConverter))] @@ -19,11 +23,11 @@ public readonly struct CompactNordPoolDayPrice return new CompactNordPoolDayPrice { Start = dayPrice.Start.HasValue - ? ToUnixSeconds(dayPrice.Start.Value) - : NullTimestampSentinel, + ? ToUnixSeconds(dayPrice.Start.Value) + : NullTimestampSentinel, End = dayPrice.End.HasValue - ? ToUnixSeconds(dayPrice.End.Value) - : NullTimestampSentinel, + ? ToUnixSeconds(dayPrice.End.Value) + : NullTimestampSentinel, Price = dayPrice.Price }; } @@ -31,8 +35,8 @@ public readonly struct CompactNordPoolDayPrice private static long ToUnixSeconds(DateTime dateTime) { var utc = dateTime.Kind == DateTimeKind.Utc - ? dateTime - : dateTime.ToUniversalTime(); + ? dateTime + : dateTime.ToUniversalTime(); return new DateTimeOffset(utc, TimeSpan.Zero).ToUnixTimeSeconds(); } @@ -40,10 +44,14 @@ public readonly struct CompactNordPoolDayPrice internal sealed class CompactNordPoolDayPriceConverter : JsonConverter { - public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert, - JsonSerializerOptions options) + public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) { - if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("Expected start of array."); + if (reader.TokenType != JsonTokenType.StartArray) + { + throw new JsonException("Expected start of array."); + } if (!reader.Read() || reader.TokenType != JsonTokenType.Number) { @@ -69,8 +77,8 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter? Prices { get; init; } + [JsonPropertyName("LT")] + public List? Prices { get; init; } } \ No newline at end of file diff --git a/NordPool.Models/NordPoolDayPriceExtensions.cs b/NordPool.Models/NordPoolDayPriceExtensions.cs index 71c3df9..6d7297b 100644 --- a/NordPool.Models/NordPoolDayPriceExtensions.cs +++ b/NordPool.Models/NordPoolDayPriceExtensions.cs @@ -5,7 +5,7 @@ public static class NordPoolDayPriceExtensions public static List ToCompact(this IEnumerable? prices) { return prices is null - ? [] - : [.. prices.Select(CompactNordPoolDayPrice.FromDayPrice)]; + ? [] + : [.. prices.Select(CompactNordPoolDayPrice.FromDayPrice)]; } } \ No newline at end of file diff --git a/NordPool.Models/NordPoolEntities.cs b/NordPool.Models/NordPoolEntities.cs index 5054423..bc5a5b9 100644 --- a/NordPool.Models/NordPoolEntities.cs +++ b/NordPool.Models/NordPoolEntities.cs @@ -1,6 +1,10 @@ +#region + using HomeAssistant.Models; using NetDaemon.Extensions.MqttEntityManager; +#endregion + namespace NordPool.Models; public class NordPoolEntity : EntityCreateModel @@ -39,8 +43,9 @@ public class NordPoolEntity : EntityCreateModel /// public static object CreateAdditionalConfig(object extraProperties) { - var extras = extraProperties.GetType().GetProperties() - .ToDictionary(p => p.Name, p => p.GetValue(extraProperties)); + var extras = extraProperties.GetType() + .GetProperties() + .ToDictionary(p => p.Name, p => p.GetValue(extraProperties)); extras["device"] = DeviceBlock; diff --git a/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs b/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs index b8c759b..fcaf9e7 100644 --- a/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs +++ b/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs @@ -1,6 +1,10 @@ +#region + using FluentAssertions; using PowerMonitorManager.Models; +#endregion + namespace PowerMonitor.Manager.Tests; public class CostAccumulatorTests @@ -27,11 +31,14 @@ public class CostAccumulatorTests // Act var tasks = Enumerable.Range(0, threadCount) - .Select(_ => Task.Run(() => - { - for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1)); - })) - .ToArray(); + .Select(_ => Task.Run(() => + { + for (var i = 0; i < callsPerThread; i++) + { + sut.AddCost(incrementPerCall, now.AddSeconds(1)); + } + })) + .ToArray(); await Task.WhenAll(tasks); @@ -47,11 +54,7 @@ public class CostAccumulatorTests { return window switch { - CostWindow.FifteenMinutes => snapshot.Cost15Min, - CostWindow.Hour => snapshot.Cost1Hour, - CostWindow.Day => snapshot.CostDaily, - CostWindow.Month => snapshot.CostMonthly, - _ => throw new ArgumentOutOfRangeException(nameof(window)) + CostWindow.FifteenMinutes => snapshot.Cost15Min, CostWindow.Hour => snapshot.Cost1Hour, CostWindow.Day => snapshot.CostDaily, CostWindow.Month => snapshot.CostMonthly, _ => throw new ArgumentOutOfRangeException(nameof(window)) }; } @@ -116,12 +119,16 @@ public class CostAccumulatorTests // Arrange var now = PowerMonitorTestData.FixedNow; var sut = new CostAccumulator(now); + var increments = PowerMonitorTestData.CreatePowerSampleSeries(50) - .Select(watts => watts / 100_000.0) - .ToArray(); + .Select(watts => watts / 100_000.0) + .ToArray(); // Act - foreach (var increment in increments) sut.AddCost(increment, now.AddSeconds(1)); + foreach (var increment in increments) + { + sut.AddCost(increment, now.AddSeconds(1)); + } // Assert var expected = increments.Sum(); @@ -191,7 +198,7 @@ public class CostAccumulatorTests #region Window rollovers - public static TheoryData WindowRolloverCases => new() + public static TheoryData WindowRolloverCases => new TheoryData { { "15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), @@ -323,7 +330,7 @@ public class CostAccumulatorTests #region Window boundary detection (static methods) - public static TheoryData FifteenMinuteBoundaryCases => new() + public static TheoryData FifteenMinuteBoundaryCases => new TheoryData { { "same slot, first second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false }, { "same slot, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false }, @@ -344,7 +351,7 @@ public class CostAccumulatorTests CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); } - public static TheoryData HourBoundaryCases => new() + public static TheoryData HourBoundaryCases => new TheoryData { { "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false }, { @@ -366,7 +373,7 @@ public class CostAccumulatorTests CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); } - public static TheoryData DayBoundaryCases => new() + public static TheoryData DayBoundaryCases => new TheoryData { { "same timestamp", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 0, 0, 0), false }, { "same day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false }, @@ -385,7 +392,7 @@ public class CostAccumulatorTests CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); } - public static TheoryData MonthBoundaryCases => new() + public static TheoryData MonthBoundaryCases => new TheoryData { { "same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false }, { "same month, last day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 59), false }, diff --git a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs index 16f4cfe..8caca69 100644 --- a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs @@ -1,8 +1,12 @@ +#region + using FluentAssertions; using Microsoft.Extensions.Options; using PowerMonitorManager; using PowerMonitorManager.Models; +#endregion + namespace PowerMonitor.Manager.Tests; public class OtherPowerCalculationServiceTests @@ -13,12 +17,13 @@ public class OtherPowerCalculationServiceTests { SmoothingWindowSize = smoothingWindowSize }); + return new OtherPowerCalculationService(options); } #region Basic calculation - public static TheoryData CalculationCases => new() + public static TheoryData CalculationCases => new TheoryData { { "two devices", 341.97, [8.55, 36.93], 296.49, "ok" }, { "no devices", 341.97, [], 341.97, "ok" }, @@ -42,9 +47,10 @@ public class OtherPowerCalculationServiceTests { // Arrange var sut = CreateSut(1); + var devices = deviceWatts - .Select((watts, index) => (entityId: $"sensor.device{index}_power", watts)) - .ToDictionary(entry => entry.entityId, entry => entry.watts); + .Select((watts, index) => (entityId: $"sensor.device{index}_power", watts)) + .ToDictionary(entry => entry.entityId, entry => entry.watts); // Act var result = sut.Calculate(totalPowerWatts, devices); @@ -166,7 +172,11 @@ public class OtherPowerCalculationServiceTests // Act PowerCalculationResult? result = null; - for (var i = 0; i < 200; i++) result = sut.Calculate(200.0, new Dictionary()); + + for (var i = 0; i < 200; i++) + { + result = sut.Calculate(200.0, new Dictionary()); + } // Assert result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1); diff --git a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs index fae838e..c81b406 100644 --- a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs @@ -1,7 +1,11 @@ +#region + using FluentAssertions; using PowerMonitorManager; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitor.Manager.Tests; public class PowerCostCalculationServiceTests @@ -12,7 +16,7 @@ public class PowerCostCalculationServiceTests Other } - private readonly PowerCostCalculationService _sut = new(); + private readonly PowerCostCalculationService _sut = new PowerCostCalculationService(); #region Snapshot defaults @@ -23,8 +27,8 @@ public class PowerCostCalculationServiceTests { // Act var snapshot = bucket == CostBucket.Total - ? _sut.GetTotalCostSnapshot() - : _sut.GetOtherCostSnapshot(); + ? _sut.GetTotalCostSnapshot() + : _sut.GetOtherCostSnapshot(); // Assert snapshot.Cost15Min.Should().Be(0); @@ -49,12 +53,14 @@ public class PowerCostCalculationServiceTests // Act var tasks = Enumerable.Range(0, threadCount) - .Select(_ => Task.Run(() => - { - for (var i = 0; i < callsPerThread; i++) - _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1)); - })) - .ToArray(); + .Select(_ => Task.Run(() => + { + for (var i = 0; i < callsPerThread; i++) + { + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1)); + } + })) + .ToArray(); await Task.WhenAll(tasks); @@ -73,14 +79,12 @@ public class PowerCostCalculationServiceTests double pricePerKwh, int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) { - return powerWatts / PowerMonitorConsts.WattsPerKilowatt - * pricePerKwh - * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); + return powerWatts / PowerMonitorConsts.WattsPerKilowatt * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); } #region CalculateCostIncrement - public static TheoryData CostIncrementCases => new() + public static TheoryData CostIncrementCases => new TheoryData { { "default polling interval", 341.97, 0.1791, 15, 0.0002551951125 }, { "one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0 }, @@ -121,14 +125,17 @@ public class PowerCostCalculationServiceTests // Act var costs = samples - .Select(watts => - PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds)) - .ToArray(); + .Select(watts => + PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds)) + .ToArray(); // Assert costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one"); + for (var i = 0; i < samples.Count; i++) + { costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15); + } } #endregion @@ -144,13 +151,14 @@ public class PowerCostCalculationServiceTests // Act _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, - now); + now); // Assert var expectedTotal = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, - PowerMonitorTestData.DefaultPricePerKwh); + PowerMonitorTestData.DefaultPricePerKwh); _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12); _sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12); @@ -168,7 +176,7 @@ public class PowerCostCalculationServiceTests // Act _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, - now); + now); // Assert var snapshot = _sut.GetDeviceCostSnapshot(entityId); @@ -187,7 +195,7 @@ public class PowerCostCalculationServiceTests // Act _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, - now); + now); // Assert var total = _sut.GetTotalCostSnapshot(); @@ -218,15 +226,16 @@ public class PowerCostCalculationServiceTests { // Arrange var now = PowerMonitorTestData.FixedNow; + var firstResult = PowerMonitorTestData.CreateCalculation( - deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); // Act _sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now); _sut.GetAllDeviceCostSnapshots().Should().HaveCount(1); _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, - now.AddSeconds(15)); + now.AddSeconds(15)); // Assert _sut.GetAllDeviceCostSnapshots().Should().HaveCount(2); @@ -242,7 +251,8 @@ public class PowerCostCalculationServiceTests // Act var singleDeviceResult = PowerMonitorTestData.CreateCalculation( - deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); + _sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15)); // Assert @@ -270,10 +280,11 @@ public class PowerCostCalculationServiceTests { // Arrange var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation( - 0, - 0, - PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0))); + 0, + 0, + PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0))); // Act _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); @@ -290,8 +301,9 @@ public class PowerCostCalculationServiceTests { // Arrange - a sensor glitch must flow through the pure cost math unchanged. var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation( - deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0))); + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0))); // Act _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); @@ -382,17 +394,19 @@ public class PowerCostCalculationServiceTests const double pricePerKwh = 0.2; var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96); var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries(); + var expectedPerSlot = timestamps - .Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh)) - .ToArray(); + .Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh)) + .ToArray(); // Act for (var slot = 0; slot < timestamps.Count; slot++) { var result = PowerMonitorTestData.CreateCalculation( - wattSamples[slot], - wattSamples[slot] / 2, - new Dictionary()); + wattSamples[slot], + wattSamples[slot] / 2, + new Dictionary()); + _sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]); } @@ -416,10 +430,12 @@ public class PowerCostCalculationServiceTests foreach (var (start, pricePerKwh) in windows) { var watts = 500.0 + start.Hour * 125.0; + var result = PowerMonitorTestData.CreateCalculation( - watts, - watts / 4, - PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2))); + watts, + watts / 4, + PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2))); + _sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start); expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds)); } @@ -476,8 +492,10 @@ public class PowerCostCalculationServiceTests // Assert _sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh); _sut.PriceSource.Should().Be("live"); + var expected = 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12); } diff --git a/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs index c620a68..8404c60 100644 --- a/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using FluentAssertions; using Microsoft.Extensions.Logging; @@ -9,6 +11,8 @@ using NetDaemon.HassModel.Entities; using PowerMonitorManager; using PowerMonitorManager.Models; +#endregion + namespace PowerMonitor.Manager.Tests; public class PowerLimitEnforcementServiceTests @@ -16,53 +20,53 @@ public class PowerLimitEnforcementServiceTests private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId; private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId; - private readonly Mock _haContextMock = new(); - private readonly Mock> _loggerMock = new(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock> _loggerMock = new Mock>(); private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions(); - private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow); + private readonly FakeTimeProvider _timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow); private PowerLimitEnforcementService CreateSut() { return new PowerLimitEnforcementService( - _haContextMock.Object, - _loggerMock.Object, - Options.Create(_options), - _timeProvider); + _haContextMock.Object, + _loggerMock.Object, + Options.Create(_options), + _timeProvider); } private void VerifyNoServiceCalls() { _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); + x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), + Times.Never); } private void VerifyTurnOff(string entityId, int expectedCalls) { _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(entityId)), null), - Times.Exactly(expectedCalls)); + x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(entityId)), null), + Times.Exactly(expectedCalls)); } private void VerifyTurnOn(string entityId, int expectedCalls) { _haContextMock.Verify( - x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(entityId)), null), - Times.Exactly(expectedCalls)); + x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(entityId)), null), + Times.Exactly(expectedCalls)); } private void VerifyNotificationCreated(int expectedCalls) { _haContextMock.Verify( - x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), - Times.Exactly(expectedCalls)); + x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), + Times.Exactly(expectedCalls)); } private void VerifyNotificationDismissed(int expectedCalls) { _haContextMock.Verify( - x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), - Times.Exactly(expectedCalls)); + x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), + Times.Exactly(expectedCalls)); } #region EnforceLimit @@ -131,11 +135,13 @@ public class PowerLimitEnforcementServiceTests { // Arrange var calls = new List<(string domain, string service, string? entityId)>(); + _haContextMock - .Setup(x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny())) - .Callback((d, s, t, _) => - calls.Add((d, s, t?.EntityIds?.FirstOrDefault()))); + .Setup(x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny())) + .Callback((d, s, t, _) => + calls.Add((d, s, t?.EntityIds?.FirstOrDefault()))); + var sut = CreateSut(); // Act @@ -144,8 +150,12 @@ public class PowerLimitEnforcementServiceTests // Assert var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList(); turnOffCalls.Should().HaveCount(2); - turnOffCalls[0].entityId.Should().Be(BoilerSwitch, - "boiler switch must be turned off before auto_management (race-safe order)"); + + turnOffCalls[0] + .entityId.Should() + .Be(BoilerSwitch, + "boiler switch must be turned off before auto_management (race-safe order)"); + turnOffCalls[1].entityId.Should().Be(AutoManagement); } @@ -156,10 +166,12 @@ public class PowerLimitEnforcementServiceTests _options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"]; _options.PauseAndRestoreEntityIds = ["switch.monitor_c"]; var calls = new List(); + _haContextMock - .Setup(x => x.CallService(It.IsAny(), "turn_off", It.IsAny(), It.IsAny())) - .Callback((_, _, target, _) => - calls.Add(target?.EntityIds?.FirstOrDefault())); + .Setup(x => x.CallService(It.IsAny(), "turn_off", It.IsAny(), It.IsAny())) + .Callback((_, _, target, _) => + calls.Add(target?.EntityIds?.FirstOrDefault())); + var sut = CreateSut(); // Act @@ -184,16 +196,17 @@ public class PowerLimitEnforcementServiceTests // Assert sut.IsLimitActive.Should().BeTrue(); VerifyNotificationCreated(1); + _haContextMock.Verify( - x => x.CallService("switch", It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); + x => x.CallService("switch", It.IsAny(), It.IsAny(), It.IsAny()), + Times.Never); } #endregion #region Recovery - public static TheoryData RecoveryCases => new() + public static TheoryData RecoveryCases => new TheoryData { { "not yet due", 300, 3000.0, true, 0 }, { "one second before due", 599, 3000.0, true, 0 }, @@ -268,7 +281,7 @@ public class PowerLimitEnforcementServiceTests [InlineData(31, true)] [InlineData(600, true)] public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, - bool expectedLimitActive) + bool expectedLimitActive) { // Arrange var sut = CreateSut(); @@ -379,9 +392,11 @@ public class PowerLimitEnforcementServiceTests // Assert sut.IsLimitActive.Should().BeTrue(); + _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Exactly(3)); + x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), + Times.Exactly(3)); + VerifyTurnOff(BoilerSwitch, 1); VerifyTurnOff(AutoManagement, 1); VerifyNotificationCreated(1); diff --git a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs index f272387..7988ba4 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs @@ -1,3 +1,5 @@ +#region + using FluentAssertions; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; @@ -5,6 +7,8 @@ using Moq; using PowerMonitor.Models; using PowerMonitorManager; +#endregion + namespace PowerMonitor.Manager.Tests; public class PowerMonitorEntityServiceTests @@ -27,18 +31,22 @@ public class PowerMonitorEntityServiceTests "button.powermonitor_trigger_limit_breach" ]; - private readonly Mock _entityManagerMock = new(); + private readonly Mock _entityManagerMock = new Mock(); private readonly PowerMonitorEntityService _sut; public PowerMonitorEntityServiceTests() { var loggerMock = new Mock>(); + _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())).Returns(Task.CompletedTask); _sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object); } @@ -56,6 +64,7 @@ public class PowerMonitorEntityServiceTests // Assert result.Should().HaveCount(4); + string[] expectedEntityIds = [ $"sensor.powermonitor_{deviceName}_cost_15min", @@ -63,6 +72,7 @@ public class PowerMonitorEntityServiceTests $"sensor.powermonitor_{deviceName}_cost_daily", $"sensor.powermonitor_{deviceName}_cost_monthly" ]; + result.Should().BeEquivalentTo(expectedEntityIds); } @@ -79,15 +89,15 @@ public class PowerMonitorEntityServiceTests { // Arrange var sensors = Enumerable.Range(0, sensorCount) - .Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}")) - .ToList(); + .Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}")) + .ToList(); // Act await _sut.CreateDeviceEntitiesAsync(sensors); // Assert _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), - Times.Exactly(expectedCreates)); + Times.Exactly(expectedCreates)); } #endregion @@ -152,7 +162,7 @@ public class PowerMonitorEntityServiceTests #region GetPowerDeviceEntitiesNames - public static TheoryData DeviceEntityCases => new() + public static TheoryData DeviceEntityCases => new TheoryData { { "sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32" }, { "simple device", "sensor.tv_power", "TV Power", "tv" }, @@ -176,6 +186,7 @@ public class PowerMonitorEntityServiceTests // Assert result.Should().HaveCount(4, $"scenario: {scenario}"); + string[] expectedEntityIds = [ $"sensor.powermonitor_{expectedDeviceName}_cost_15min", @@ -183,8 +194,10 @@ public class PowerMonitorEntityServiceTests $"sensor.powermonitor_{expectedDeviceName}_cost_daily", $"sensor.powermonitor_{expectedDeviceName}_cost_monthly" ]; + result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}"); result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}"); + string[] expectedNames = [ $"{friendlyName} cost (15 min)", @@ -192,6 +205,7 @@ public class PowerMonitorEntityServiceTests $"{friendlyName} cost (daily)", $"{friendlyName} cost (monthly)" ]; + result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"scenario: {scenario}"); } @@ -228,9 +242,9 @@ public class PowerMonitorEntityServiceTests { // Arrange - both 1h cost entities fail, the remaining twelve must still be created. _entityManagerMock - .Setup(em => - em.CreateEntityAsync(It.Is(entity => entity.Identifier.EndsWith("_cost_1h")))) - .ThrowsAsync(new InvalidOperationException("Entity creation failed")); + .Setup(em => + em.CreateEntityAsync(It.Is(entity => entity.Identifier.EndsWith("_cost_1h")))) + .ThrowsAsync(new InvalidOperationException("Entity creation failed")); // Act await _sut.CreateSystemEntitiesAsync(); @@ -282,8 +296,8 @@ public class PowerMonitorEntityServiceTests { // Arrange _entityManagerMock - .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Failed")); + .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Failed")); // Act var act = () => _sut.ResetEntitiesAsync(); @@ -305,7 +319,7 @@ public class PowerMonitorEntityServiceTests // Assert _entityManagerMock.Verify(em => em.RemoveEntity(It.Is(id => SystemEntityIds.Contains(id))), - Times.Exactly(14)); + Times.Exactly(14)); } [Fact] @@ -313,8 +327,8 @@ public class PowerMonitorEntityServiceTests { // Arrange _entityManagerMock - .Setup(em => em.RemoveEntity(It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Removal failed")); + .Setup(em => em.RemoveEntity(It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Removal failed")); // Act var act = () => _sut.RemoveSystemEntitiesAsync(); @@ -335,8 +349,8 @@ public class PowerMonitorEntityServiceTests { // Arrange var deviceNames = Enumerable.Range(0, deviceCount) - .Select(index => $"device_{index}") - .ToList(); + .Select(index => $"device_{index}") + .ToList(); // Act await _sut.RemoveDeviceEntitiesAsync(deviceNames); @@ -350,8 +364,8 @@ public class PowerMonitorEntityServiceTests { // Arrange _entityManagerMock - .Setup(em => em.RemoveEntity(It.Is(id => id.Contains("_cost_daily")))) - .ThrowsAsync(new InvalidOperationException("Removal failed")); + .Setup(em => em.RemoveEntity(It.Is(id => id.Contains("_cost_daily")))) + .ThrowsAsync(new InvalidOperationException("Removal failed")); // Act var act = () => _sut.RemoveDeviceEntitiesAsync(["device_a", "device_b"]); @@ -398,16 +412,18 @@ public class PowerMonitorEntityServiceTests { // Arrange var context = PowerMonitorTestData.CreateUpdateContext( - deviceReadings: PowerMonitorTestData.CreateReadings((entityId, 42.0))); + deviceReadings: PowerMonitorTestData.CreateReadings((entityId, 42.0))); // Act await _sut.UpdateEntitiesAsync(context); // Assert foreach (var window in new[] { "15min", "1h", "daily", "monthly" }) + { _entityManagerMock.Verify( - em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny()), - Times.Once); + em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny()), + Times.Once); + } } [Theory] @@ -423,7 +439,7 @@ public class PowerMonitorEntityServiceTests // Assert _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState), - Times.Once); + Times.Once); } [Theory] @@ -447,7 +463,7 @@ public class PowerMonitorEntityServiceTests { // Arrange var context = PowerMonitorTestData.CreateUpdateContext( - deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0))); + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0))); // Act await _sut.UpdateEntitiesAsync(context); @@ -455,8 +471,10 @@ public class PowerMonitorEntityServiceTests // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "342.0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "128.5"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"), - Times.Once); + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once); } @@ -465,8 +483,9 @@ public class PowerMonitorEntityServiceTests { // Arrange _entityManagerMock - .Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Failed")); + .Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Failed")); + var context = PowerMonitorTestData.CreateUpdateContext(); // Act @@ -475,8 +494,9 @@ public class PowerMonitorEntityServiceTests // Assert await act.Should().NotThrowAsync(); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny()), - Times.Once); + Times.Once); } #endregion @@ -488,8 +508,8 @@ public class PowerMonitorEntityServiceTests { // Arrange _entityManagerMock - .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Failed")); + .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Failed")); // Act var act = () => _sut.SetEntityStateSafe("sensor.test", "42"); @@ -503,8 +523,8 @@ public class PowerMonitorEntityServiceTests { // Arrange _entityManagerMock - .Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Failed")); + .Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Failed")); // Act var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { }); diff --git a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs index 85e7c2e..3f82c17 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs @@ -1,7 +1,11 @@ +#region + using FluentAssertions; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitor.Manager.Tests; public class PowerMonitorOptionsTests diff --git a/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs b/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs index 3f2d236..8067e19 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs @@ -1,9 +1,13 @@ +#region + using System.Text.Json; using PowerMonitor.Models; using PowerMonitorManager; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitor.Manager.Tests; /// @@ -21,11 +25,11 @@ internal static class PowerMonitorTestData public const string AutoManagementEntityId = "switch.boilermonitor_auto_management"; public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power"; - public static readonly DateTime FixedNow = new(2026, 3, 17, 10, 0, 0); + public static readonly DateTime FixedNow = new DateTime(2026, 3, 17, 10, 0, 0); - public static readonly DateTime FixedDayStart = new(2026, 3, 17, 0, 0, 0); + public static readonly DateTime FixedDayStart = new DateTime(2026, 3, 17, 0, 0, 0); - public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero); + public static readonly DateTimeOffset FixedUtcNow = new DateTimeOffset(2026, 3, 17, 8, 0, 0, TimeSpan.Zero); /// /// Two-device reading set used by the cost calculation tests. @@ -107,13 +111,14 @@ internal static class PowerMonitorTestData string priceSource = "live") { var readings = deviceReadings ?? CreateDeviceReadings(); + var deviceCosts = readings - .Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot( - 0.0005 * (index + 1), - 0.002 * (index + 1), - 0.03 * (index + 1), - 0.9 * (index + 1)))) - .ToDictionary(entry => entry.Key, entry => entry.Snapshot); + .Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot( + 0.0005 * (index + 1), + 0.002 * (index + 1), + 0.03 * (index + 1), + 0.9 * (index + 1)))) + .ToDictionary(entry => entry.Key, entry => entry.Snapshot); return new PowerUpdateContext { @@ -143,21 +148,22 @@ internal static class PowerMonitorTestData }; configure?.Invoke(options); + return options; } public static PowerMonitorOptions CreateLimitEnforcementOptions(Action? configure = null) { return CreateOptions(options => - { - options.EnforceLimitEnabled = true; - options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts; - options.RecoverySeconds = PowerMonitorConsts.DefaultRecoverySeconds; - options.LimitCooldownSeconds = PowerMonitorConsts.DefaultLimitCooldownSeconds; - options.EnforceSwitchOffEntityIds = [BoilerSwitchEntityId]; - options.PauseAndRestoreEntityIds = [AutoManagementEntityId]; - configure?.Invoke(options); - }); + { + options.EnforceLimitEnabled = true; + options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts; + options.RecoverySeconds = PowerMonitorConsts.DefaultRecoverySeconds; + options.LimitCooldownSeconds = PowerMonitorConsts.DefaultLimitCooldownSeconds; + options.EnforceSwitchOffEntityIds = [BoilerSwitchEntityId]; + options.PauseAndRestoreEntityIds = [AutoManagementEntityId]; + configure?.Invoke(options); + }); } public static PowerSensorInfo CreateSensor( @@ -182,11 +188,20 @@ internal static class PowerMonitorTestData { var attributes = new Dictionary(); - if (deviceClass is not null) attributes["device_class"] = deviceClass; + if (deviceClass is not null) + { + attributes["device_class"] = deviceClass; + } - if (unitOfMeasurement is not null) attributes["unit_of_measurement"] = unitOfMeasurement; + if (unitOfMeasurement is not null) + { + attributes["unit_of_measurement"] = unitOfMeasurement; + } - if (friendlyName is not null) attributes["friendly_name"] = friendlyName; + if (friendlyName is not null) + { + attributes["friendly_name"] = friendlyName; + } return JsonSerializer.SerializeToElement(attributes); } @@ -200,7 +215,7 @@ internal static class PowerMonitorTestData return [ .. Enumerable.Range(0, count) - .Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2)) + .Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2)) ]; } @@ -212,7 +227,7 @@ internal static class PowerMonitorTestData return [ .. Enumerable.Range(0, count) - .Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4)) + .Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4)) ]; } @@ -223,7 +238,7 @@ internal static class PowerMonitorTestData return [ .. Enumerable.Range(0, prices.Count) - .Select(hour => (dayStart.AddHours(hour), prices[hour])) + .Select(hour => (dayStart.AddHours(hour), prices[hour])) ]; } @@ -232,7 +247,7 @@ internal static class PowerMonitorTestData return [ .. Enumerable.Range(0, count) - .Select(i => start.AddMinutes(i * intervalMinutes)) + .Select(i => start.AddMinutes(i * intervalMinutes)) ]; } } \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs index f5632f0..1035541 100644 --- a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs @@ -1,3 +1,5 @@ +#region + using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -6,22 +8,25 @@ using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using PowerMonitorManager; +#endregion + namespace PowerMonitor.Manager.Tests; public class PowerSensorDiscoveryServiceTests { - private readonly Mock _haContextMock = new(); - private readonly Mock> _loggerMock = new(); + private readonly Mock _haContextMock = new Mock(); + private readonly Mock> _loggerMock = new Mock>(); private PowerSensorDiscoveryService CreateSut( string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId, string[]? excludedPatterns = null) { var options = Options.Create(PowerMonitorTestData.CreateOptions(option => - { - option.MainMeterEntityId = mainMeterEntityId; - option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"]; - })); + { + option.MainMeterEntityId = mainMeterEntityId; + option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"]; + })); + return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object); } @@ -33,6 +38,7 @@ public class PowerSensorDiscoveryServiceTests }; _haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); + return new Entity(_haContextMock.Object, entityId); } @@ -40,18 +46,18 @@ public class PowerSensorDiscoveryServiceTests params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) { _haContextMock - .Setup(h => h.GetAllEntities()) - .Returns([ + .Setup(h => h.GetAllEntities()) + .Returns([ .. entities.Select(entity => - SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName)) + SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName)) ]); } private void SetupEntitiesWithoutState(params string[] entityIds) { _haContextMock - .Setup(h => h.GetAllEntities()) - .Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]); + .Setup(h => h.GetAllEntities()) + .Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]); } #region ExtractDeviceName @@ -102,10 +108,10 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), - ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), - ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"), - ("sensor.temperature", "temperature", "°C", "Temperature")); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), + ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"), + ("sensor.temperature", "temperature", "°C", "Temperature")); var sut = CreateSut(); @@ -123,8 +129,8 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), - ("sensor.tv_power", "power", "W", "TV Power")); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.tv_power", "power", "W", "TV Power")); var sut = CreateSut(); @@ -141,8 +147,8 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), - ("sensor.tv_power", "power", "W", "TV Power")); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.tv_power", "power", "W", "TV Power")); var sut = CreateSut(string.Empty); @@ -159,10 +165,10 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), - ("sensor.tv_power", "power", "W", "TV Power"), - ("sensor.nordpool_some_power", "power", "W", "NordPool"), - ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.tv_power", "power", "W", "TV Power"), + ("sensor.nordpool_some_power", "power", "W", "NordPool"), + ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")); var sut = CreateSut(); @@ -179,8 +185,8 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - ("sensor.tv_power", "power", "W", "TV Power"), - ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")); + ("sensor.tv_power", "power", "W", "TV Power"), + ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")); var sut = CreateSut(excludedPatterns: []); @@ -225,9 +231,9 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - ("sensor.temperature", "temperature", "°C", "Temp"), - ("switch.some_switch", null, null, "Switch"), - ("sensor.energy_usage", "energy", "kWh", "Energy")); + ("sensor.temperature", "temperature", "°C", "Temp"), + ("switch.some_switch", null, null, "Switch"), + ("sensor.energy_usage", "energy", "kWh", "Energy")); var sut = CreateSut(); @@ -243,9 +249,10 @@ public class PowerSensorDiscoveryServiceTests { // Arrange - HA can report entities whose state has not been published yet. var tv = SetupEntity("sensor.tv_power", "power", "W", "TV Power"); + _haContextMock - .Setup(h => h.GetAllEntities()) - .Returns(new List { new(_haContextMock.Object, "sensor.ghost_power"), tv }); + .Setup(h => h.GetAllEntities()) + .Returns(new List { new Entity(_haContextMock.Object, "sensor.ghost_power"), tv }); var sut = CreateSut(); @@ -262,8 +269,8 @@ public class PowerSensorDiscoveryServiceTests { // Arrange - discovery is a projection of HA's entity list; de-duplication is not its job. SetupEntities( - ("sensor.tv_power", "power", "W", "TV Power"), - ("sensor.tv_power", "power", "W", "TV Power")); + ("sensor.tv_power", "power", "W", "TV Power"), + ("sensor.tv_power", "power", "W", "TV Power")); var sut = CreateSut(); @@ -280,8 +287,8 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), - ("sensor.akvariumas_power", "power", "W", "Akvariumas Power")); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.akvariumas_power", "power", "W", "Akvariumas Power")); var sut = CreateSut(); sut.CurrentDeviceSensors.Should().BeEmpty(); @@ -298,17 +305,17 @@ public class PowerSensorDiscoveryServiceTests { // Arrange SetupEntities( - (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), - ("sensor.sonoff_100215c534_power", "power", "W", "AC Power")); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_100215c534_power", "power", "W", "AC Power")); var sut = CreateSut(); sut.DiscoverDeviceSensors(); sut.CurrentDeviceSensors.Should().HaveCount(1); SetupEntities( - (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), - ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), - ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power")); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), + ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power")); // Act sut.DiscoverDeviceSensors(); diff --git a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs b/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs index e24afef..69a4f9e 100644 --- a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs +++ b/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs @@ -1,5 +1,9 @@ +#region + using PowerMonitorManager.Models; +#endregion + namespace PowerMonitorManager.Interface; public interface IOtherPowerCalculationService diff --git a/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs b/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs index 820d046..b18c85c 100644 --- a/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs +++ b/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs @@ -1,5 +1,9 @@ +#region + using PowerMonitorManager.Models; +#endregion + namespace PowerMonitorManager.Interface; public interface IPowerCostCalculationService diff --git a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs b/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs index 0f0f0e7..d5b9cf6 100644 --- a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs @@ -1,6 +1,10 @@ +#region + using PowerMonitor.Models; using PowerMonitorManager.Models; +#endregion + namespace PowerMonitorManager.Interface; public interface IPowerMonitorEntityService @@ -8,12 +12,12 @@ public interface IPowerMonitorEntityService Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default); Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, - CancellationToken cancellationToken = default); + CancellationToken cancellationToken = default); Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default); Task ResetEntitiesAsync(CancellationToken cancellationToken = default); Task RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default); Task RemoveDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, - CancellationToken cancellationToken = default); + CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs b/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs index 0535d54..21453d2 100644 --- a/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs +++ b/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs @@ -1,5 +1,9 @@ +#region + using PowerMonitor.Models; +#endregion + namespace PowerMonitorManager.Interface; public interface IPowerSensorDiscoveryService diff --git a/PowerMonitor.Manager/Models/CostAccumulator.cs b/PowerMonitor.Manager/Models/CostAccumulator.cs index c1d7190..80b8b3c 100644 --- a/PowerMonitor.Manager/Models/CostAccumulator.cs +++ b/PowerMonitor.Manager/Models/CostAccumulator.cs @@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models; public sealed class CostAccumulator(DateTime now) { - private readonly Lock _lock = new(); + private readonly Lock _lock = new Lock(); private double _cost15Min; private double _cost1Hour; @@ -77,7 +77,10 @@ public sealed class CostAccumulator(DateTime now) _lastDailyReset = now; } - if (!IsNewMonthWindow(now, _lastMonthlyReset)) return; + if (!IsNewMonthWindow(now, _lastMonthlyReset)) + { + return; + } _previousMonthly = _costMonthly; _costMonthly = 0; @@ -88,6 +91,7 @@ public sealed class CostAccumulator(DateTime now) { var currentSlot = now.Minute / 15; var lastSlot = lastReset.Minute / 15; + return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot; } diff --git a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs index fa01fe5..cf024ce 100644 --- a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs +++ b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs @@ -1,5 +1,9 @@ +#region + using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitorManager.Models; public sealed class PowerMonitorOptions diff --git a/PowerMonitor.Manager/OtherPowerCalculationService.cs b/PowerMonitor.Manager/OtherPowerCalculationService.cs index 344ba08..5a12550 100644 --- a/PowerMonitor.Manager/OtherPowerCalculationService.cs +++ b/PowerMonitor.Manager/OtherPowerCalculationService.cs @@ -1,13 +1,17 @@ +#region + using Microsoft.Extensions.Options; using PowerMonitorManager.Interface; using PowerMonitorManager.Models; +#endregion + namespace PowerMonitorManager; public sealed class OtherPowerCalculationService : IOtherPowerCalculationService { private readonly double _alpha; - private readonly Lock _lock = new(); + private readonly Lock _lock = new Lock(); private double? _previousSmoothed; public OtherPowerCalculationService(IOptions options) @@ -29,11 +33,13 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService } double smoothed; + lock (_lock) { smoothed = _previousSmoothed.HasValue - ? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value - : rawOther; + ? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value + : rawOther; + _previousSmoothed = smoothed; } diff --git a/PowerMonitor.Manager/PowerCostCalculationService.cs b/PowerMonitor.Manager/PowerCostCalculationService.cs index 01a58a8..025316f 100644 --- a/PowerMonitor.Manager/PowerCostCalculationService.cs +++ b/PowerMonitor.Manager/PowerCostCalculationService.cs @@ -1,15 +1,19 @@ +#region + using System.Collections.Concurrent; using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitorManager; public sealed class PowerCostCalculationService : IPowerCostCalculationService { - private readonly Lock _accumulatorLock = new(); - private readonly ConcurrentDictionary _deviceAccumulators = new(); - private readonly Lock _priceLock = new(); + private readonly Lock _accumulatorLock = new Lock(); + private readonly ConcurrentDictionary _deviceAccumulators = new ConcurrentDictionary(); + private readonly Lock _priceLock = new Lock(); private double _lastKnownPrice; private CostAccumulator? _otherAccumulator; @@ -38,8 +42,10 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService } } - public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, - DateTime now) + public void RecordCosts(PowerCalculationResult calculation, + double nordPoolPrice, + int pollIntervalSeconds, + DateTime now) { lock (_priceLock) { @@ -57,6 +63,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService var otherCost = CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds); + GetOrCreateOtherAccumulator(now).AddCost(otherCost, now); foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings) @@ -86,8 +93,8 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService public IReadOnlyDictionary GetAllDeviceCostSnapshots() { return _deviceAccumulators.ToDictionary( - kvp => kvp.Key, - kvp => kvp.Value.GetSnapshot()); + kvp => kvp.Key, + kvp => kvp.Value.GetSnapshot()); } public void SetPrice(double price) @@ -102,13 +109,14 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService public CostSnapshot GetDeviceCostSnapshot(string entityId) { return _deviceAccumulators.TryGetValue(entityId, out var accumulator) - ? accumulator.GetSnapshot() - : CreateEmptySnapshot(); + ? accumulator.GetSnapshot() + : CreateEmptySnapshot(); } internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds) { var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt; + return powerKw * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); } diff --git a/PowerMonitor.Manager/PowerLimitEnforcementService.cs b/PowerMonitor.Manager/PowerLimitEnforcementService.cs index 089e717..0e51b0e 100644 --- a/PowerMonitor.Manager/PowerLimitEnforcementService.cs +++ b/PowerMonitor.Manager/PowerLimitEnforcementService.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -7,6 +9,8 @@ using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitorManager; public sealed class PowerLimitEnforcementService( @@ -25,13 +29,17 @@ public sealed class PowerLimitEnforcementService( public void EnforceLimit(double currentPowerWatts) { - if (!_options.EnforceLimitEnabled) return; + if (!_options.EnforceLimitEnabled) + { + return; + } var now = timeProvider.GetUtcNow(); if (!IsLimitActive) { TryEnforce(currentPowerWatts, now); + return; } @@ -43,6 +51,7 @@ public sealed class PowerLimitEnforcementService( if (IsLimitActive) { logger.LogInformation("Debug: trigger requested but limit already active"); + return; } @@ -55,6 +64,7 @@ public sealed class PowerLimitEnforcementService( if (!IsLimitActive) { logger.LogInformation("Debug: reset requested but limit not active"); + return; } @@ -64,9 +74,15 @@ public sealed class PowerLimitEnforcementService( private void ExecuteEnforce(double currentPowerWatts) { - foreach (var entityId in _options.EnforceSwitchOffEntityIds) TurnOff(entityId); + foreach (var entityId in _options.EnforceSwitchOffEntityIds) + { + TurnOff(entityId); + } - foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOff(entityId); + foreach (var entityId in _options.PauseAndRestoreEntityIds) + { + TurnOff(entityId); + } NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts); @@ -78,7 +94,10 @@ public sealed class PowerLimitEnforcementService( private void ExecuteRecover() { - foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId); + foreach (var entityId in _options.PauseAndRestoreEntityIds) + { + TurnOn(entityId); + } DismissLimitNotification(); @@ -88,22 +107,25 @@ public sealed class PowerLimitEnforcementService( private void TryEnforce(double currentPowerWatts, DateTimeOffset now) { - if (currentPowerWatts <= _options.PowerLimitWatts) return; + if (currentPowerWatts <= _options.PowerLimitWatts) + { + return; + } if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds)) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug( - "Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", - currentPowerWatts, _options.PowerLimitWatts); + "Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", + currentPowerWatts, _options.PowerLimitWatts); } return; } logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts, - _options.PowerLimitWatts); + _options.PowerLimitWatts); ExecuteEnforce(currentPowerWatts); } @@ -112,12 +134,16 @@ public sealed class PowerLimitEnforcementService( { var elapsed = now - _enforcedAt; - if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds)) return; + if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds)) + { + return; + } if (currentPowerWatts >= _options.PowerLimitWatts) { logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced", - currentPowerWatts, _options.PowerLimitWatts); + currentPowerWatts, _options.PowerLimitWatts); + _enforcedAt = now; return; @@ -126,11 +152,14 @@ public sealed class PowerLimitEnforcementService( if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( - "Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors", - currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds); + "Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors", + currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds); } - foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId); + foreach (var entityId in _options.PauseAndRestoreEntityIds) + { + TurnOn(entityId); + } DismissLimitNotification(); @@ -141,46 +170,46 @@ public sealed class PowerLimitEnforcementService( private void TurnOff(string entityId) { haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService, - ServiceTarget.FromEntity(entityId)); + ServiceTarget.FromEntity(entityId)); } private void TurnOn(string entityId) { haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService, - ServiceTarget.FromEntity(entityId)); + ServiceTarget.FromEntity(entityId)); } private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts) { var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt, - limitWatts / PowerMonitorConsts.WattsPerKilowatt); + limitWatts / PowerMonitorConsts.WattsPerKilowatt); haContext.CallService( - PowerMonitorConsts.PersistentNotificationDomain, - PowerMonitorConsts.PersistentNotificationCreateService, - data: new - { - title = PowerMonitorConsts.PowerLimitNotificationTitle, - message, - notification_id = PowerMonitorConsts.PowerLimitNotificationId - }); + PowerMonitorConsts.PersistentNotificationDomain, + PowerMonitorConsts.PersistentNotificationCreateService, + data: new + { + title = PowerMonitorConsts.PowerLimitNotificationTitle, + message, + notification_id = PowerMonitorConsts.PowerLimitNotificationId + }); } private void DismissLimitNotification() { haContext.CallService( - PowerMonitorConsts.PersistentNotificationDomain, - PowerMonitorConsts.PersistentNotificationDismissService, - data: new - { - notification_id = PowerMonitorConsts.PowerLimitNotificationId - }); + PowerMonitorConsts.PersistentNotificationDomain, + PowerMonitorConsts.PersistentNotificationDismissService, + data: new + { + notification_id = PowerMonitorConsts.PowerLimitNotificationId + }); } internal static string BuildLimitMessage(double currentKw, double limitKw) { return string.Format(CultureInfo.InvariantCulture, - "Home power usage **{0:F2} kW** exceeded the limit of **{1:F1} kW**.\n\nHigh-power appliances have been turned off and automatic control paused. Normal control resumes after power drops below the limit.", - currentKw, limitKw); + "Home power usage **{0:F2} kW** exceeded the limit of **{1:F1} kW**.\n\nHigh-power appliances have been turned off and automatic control paused. Normal control resumes after power drops below the limit.", + currentKw, limitKw); } } \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerMonitorEntityService.cs b/PowerMonitor.Manager/PowerMonitorEntityService.cs index 3bbded1..f6210c4 100644 --- a/PowerMonitor.Manager/PowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/PowerMonitorEntityService.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; @@ -6,6 +8,8 @@ using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitorManager; public sealed class PowerMonitorEntityService( @@ -44,48 +48,50 @@ public sealed class PowerMonitorEntityService( cancellationToken.ThrowIfCancellationRequested(); var entities = GetSystemEntitiesList(); - var tasks = entities.Select(async entity => - { - try - { - if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId); - } - await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId); - } - }); + var tasks = entities.Select(async entity => + { + try + { + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId); + } + + await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId); + } + }); await Task.WhenAll(tasks).ConfigureAwait(false); } public async Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var entities = sensors.SelectMany(GetPowerDeviceEntitiesNames).ToList(); - var tasks = entities.Select(async entity => - { - try - { - if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId); - } - await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to create device cost entity: {EntityId}", entity.EntityId); - } - }); + var tasks = entities.Select(async entity => + { + try + { + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId); + } + + await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create device cost entity: {EntityId}", entity.EntityId); + } + }); await Task.WhenAll(tasks).ConfigureAwait(false); } @@ -100,22 +106,22 @@ public sealed class PowerMonitorEntityService( { UpdateTotalPowerAsync(context, timestamp), UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost, - "Total cost (15 min)", timestamp), + "Total cost (15 min)", timestamp), UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost, - "Total cost (1h)", timestamp), + "Total cost (1h)", timestamp), UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost, - "Total cost (daily)", timestamp), + "Total cost (daily)", timestamp), UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost, - "Total cost (monthly)", timestamp), + "Total cost (monthly)", timestamp), UpdateOtherPowerAsync(context, timestamp), UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost, - "Other cost (15 min)", timestamp), + "Other cost (15 min)", timestamp), UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost, - "Other cost (1h)", timestamp), + "Other cost (1h)", timestamp), UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost, - "Other cost (daily)", timestamp), + "Other cost (daily)", timestamp), UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost, - "Other cost (monthly)", timestamp), + "Other cost (monthly)", timestamp), UpdateAnomalyAsync(context, timestamp), UpdateStatusAsync(context, timestamp) }; @@ -123,14 +129,18 @@ public sealed class PowerMonitorEntityService( foreach (var (entityId, costSnapshot) in context.DeviceCosts) { var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(entityId); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min, - costSnapshot, $"{deviceName} cost (15 min)", timestamp)); + costSnapshot, $"{deviceName} cost (15 min)", timestamp)); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour, - costSnapshot, $"{deviceName} cost (1h)", timestamp)); + costSnapshot, $"{deviceName} cost (1h)", timestamp)); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily, - costSnapshot, $"{deviceName} cost (daily)", timestamp)); + costSnapshot, $"{deviceName} cost (daily)", timestamp)); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly, - costSnapshot, $"{deviceName} cost (monthly)", timestamp)); + costSnapshot, $"{deviceName} cost (monthly)", timestamp)); } await Task.WhenAll(tasks).ConfigureAwait(false); @@ -175,40 +185,43 @@ public sealed class PowerMonitorEntityService( catch (Exception ex) { logger.LogError(ex, "Error cleaning up PowerMonitor entities"); + throw; } } public async Task RemoveDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var entityIds = removedDeviceNames.SelectMany(GetDeviceCostEntityIds).ToList(); var tasks = entityIds.Select(async id => - { - try - { - await entityManager.RemoveEntity(id).ConfigureAwait(false); + { + try + { + await entityManager.RemoveEntity(id).ConfigureAwait(false); - if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Entity removed: {EntityId}", id); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to remove device entity: {EntityId}", id); - } - }); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Entity removed: {EntityId}", id); + } + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to remove device entity: {EntityId}", id); + } + }); await Task.WhenAll(tasks).ConfigureAwait(false); } - internal static ICollection GetSystemEntitiesList() { return new List { - new("sensor", "powermonitor_total_power", "PowerMonitor total power") + new PowerMonitorEntity("sensor", "powermonitor_total_power", "PowerMonitor total power") { AdditionalConfig = new { @@ -221,7 +234,7 @@ public sealed class PowerMonitorEntityService( CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"), CreateCostEntity("powermonitor_total_cost_daily", "PowerMonitor total cost (daily)"), CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"), - new("sensor", "powermonitor_other_power", "PowerMonitor other power") + new PowerMonitorEntity("sensor", "powermonitor_other_power", "PowerMonitor other power") { AdditionalConfig = new { @@ -234,13 +247,13 @@ public sealed class PowerMonitorEntityService( CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"), CreateCostEntity("powermonitor_other_cost_daily", "PowerMonitor other cost (daily)"), CreateCostEntity("powermonitor_other_cost_monthly", "PowerMonitor other cost (monthly)"), - new("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"), - new("sensor", "powermonitor_status", "PowerMonitor status"), - new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors") + new PowerMonitorEntity("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"), + new PowerMonitorEntity("sensor", "powermonitor_status", "PowerMonitor status"), + new PowerMonitorEntity("button", "powermonitor_rediscover_sensors", "Rediscover power sensors") { AdditionalConfig = new { icon = "mdi:refresh" } }, - new("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)") + new PowerMonitorEntity("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)") { AdditionalConfig = new { icon = "mdi:flash-alert" } } @@ -263,6 +276,7 @@ public sealed class PowerMonitorEntityService( internal static IEnumerable GetPowerDeviceEntitiesNames(PowerSensorInfo sensor) { var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId); + return [ CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"), @@ -287,76 +301,89 @@ public sealed class PowerMonitorEntityService( { var value = context.Calculation.TotalPowerWatts.ToString("F1", CultureInfo.InvariantCulture); await SetEntityStateSafe(TotalPowerEntityId, value).ConfigureAwait(false); + await SetEntityAttributesSafe(TotalPowerEntityId, new - { - unit_of_measurement = PowerMonitorConsts.WattUnit, - device_class = PowerMonitorConsts.PowerDeviceClass, - state_class = PowerMonitorConsts.MeasurementStateClass, - friendly_name = "PowerMonitor total power", - last_updated = timestamp - }).ConfigureAwait(false); + { + unit_of_measurement = PowerMonitorConsts.WattUnit, + device_class = PowerMonitorConsts.PowerDeviceClass, + state_class = PowerMonitorConsts.MeasurementStateClass, + friendly_name = "PowerMonitor total power", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateOtherPowerAsync(PowerUpdateContext context, string timestamp) { var value = context.Calculation.SmoothedOtherPowerWatts.ToString("F1", CultureInfo.InvariantCulture); await SetEntityStateSafe(OtherPowerEntityId, value).ConfigureAwait(false); + await SetEntityAttributesSafe(OtherPowerEntityId, new - { - unit_of_measurement = PowerMonitorConsts.WattUnit, - device_class = PowerMonitorConsts.PowerDeviceClass, - state_class = PowerMonitorConsts.MeasurementStateClass, - friendly_name = "PowerMonitor other power", - raw_power = context.Calculation.RawOtherPowerWatts, - smoothed_power = context.Calculation.SmoothedOtherPowerWatts, - data_quality = context.Calculation.DataQuality, - last_updated = timestamp - }).ConfigureAwait(false); + { + unit_of_measurement = PowerMonitorConsts.WattUnit, + device_class = PowerMonitorConsts.PowerDeviceClass, + state_class = PowerMonitorConsts.MeasurementStateClass, + friendly_name = "PowerMonitor other power", + raw_power = context.Calculation.RawOtherPowerWatts, + smoothed_power = context.Calculation.SmoothedOtherPowerWatts, + data_quality = context.Calculation.DataQuality, + last_updated = timestamp + }) + .ConfigureAwait(false); } - private async Task UpdateCostEntityAsync(string entityId, double costValue, CostSnapshot snapshot, - string friendlyName, string timestamp) + private async Task UpdateCostEntityAsync(string entityId, + double costValue, + CostSnapshot snapshot, + string friendlyName, + string timestamp) { var value = costValue.ToString("F4", CultureInfo.InvariantCulture); await SetEntityStateSafe(entityId, value).ConfigureAwait(false); + await SetEntityAttributesSafe(entityId, new - { - unit_of_measurement = PowerMonitorConsts.EurUnit, - device_class = PowerMonitorConsts.MonetaryDeviceClass, - state_class = PowerMonitorConsts.TotalStateClass, - friendly_name = friendlyName, - partial_window = snapshot.PartialWindow, - last_updated = timestamp - }).ConfigureAwait(false); + { + unit_of_measurement = PowerMonitorConsts.EurUnit, + device_class = PowerMonitorConsts.MonetaryDeviceClass, + state_class = PowerMonitorConsts.TotalStateClass, + friendly_name = friendlyName, + partial_window = snapshot.PartialWindow, + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateAnomalyAsync(PowerUpdateContext context, string timestamp) { var state = context.IsAnomaly ? "on" : "off"; await SetEntityStateSafe(AnomalyEntityId, state).ConfigureAwait(false); + await SetEntityAttributesSafe(AnomalyEntityId, new - { - friendly_name = "PowerMonitor anomaly", - smoothed_watts = context.Calculation.SmoothedOtherPowerWatts, - threshold = context.AnomalyThresholdWatts, - duration_above = context.AnomalyDuration.TotalSeconds, - last_updated = timestamp - }).ConfigureAwait(false); + { + friendly_name = "PowerMonitor anomaly", + smoothed_watts = context.Calculation.SmoothedOtherPowerWatts, + threshold = context.AnomalyThresholdWatts, + duration_above = context.AnomalyDuration.TotalSeconds, + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateStatusAsync(PowerUpdateContext context, string timestamp) { await SetEntityStateSafe(StatusEntityId, context.SystemStatus).ConfigureAwait(false); + await SetEntityAttributesSafe(StatusEntityId, new - { - friendly_name = "PowerMonitor status", - tracked_sensors_count = context.TrackedSensorCount, - degraded_sensors = context.DegradedSensors, - price_source = context.PriceSource, - current_price = context.CurrentNordPoolPrice, - price_unit = context.PriceUnit, - last_updated = timestamp - }).ConfigureAwait(false); + { + friendly_name = "PowerMonitor status", + tracked_sensors_count = context.TrackedSensorCount, + degraded_sensors = context.DegradedSensors, + price_source = context.PriceSource, + current_price = context.CurrentNordPoolPrice, + price_unit = context.PriceUnit, + last_updated = timestamp + }) + .ConfigureAwait(false); } internal async Task SetEntityStateSafe(string entityId, string state) diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index 1cdf6b1..83a265e 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -10,6 +12,8 @@ using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitorManager; [NetDaemonApp] @@ -108,6 +112,7 @@ public sealed class PowerMonitorInit catch (Exception ex) { _logger.LogError(ex, "Error initializing PowerMonitor"); + throw; } } @@ -129,17 +134,22 @@ public sealed class PowerMonitorInit if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId)) { _logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes"); + return; } var meter = new Entity(_haContext, _options.MainMeterEntityId); - meter.StateChanges() - .Subscribe(e => - { - if (e.Old?.State == e.New?.State) return; - _ = PollAndUpdateAsync(); - }); + meter.StateChanges() + .Subscribe(e => + { + if (e.Old?.State == e.New?.State) + { + return; + } + + _ = PollAndUpdateAsync(); + }); if (_logger.IsEnabled(LogLevel.Information)) { @@ -150,31 +160,33 @@ public sealed class PowerMonitorInit private void SubscribeToRediscoverButton() { var button = new Entity(_haContext, "button.powermonitor_rediscover_sensors"); + button.StateChanges() - .Subscribe(change => - { - _logger.LogInformation("Re-discovery button pressed, scanning for power sensors"); - _ = HandleRediscoveryAsync(); - }); + .Subscribe(change => + { + _logger.LogInformation("Re-discovery button pressed, scanning for power sensors"); + _ = HandleRediscoveryAsync(); + }); } private void SubscribeToLimitBreachDebugButton() { var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach"); + button.StateChanges() - .Subscribe(_ => - { - if (_enforcementService.IsLimitActive) - { - _logger.LogInformation("Limit breach debug button pressed while active, resetting breach"); - _enforcementService.ResetLimitBreach(); - } - else - { - _logger.LogInformation("Limit breach debug button pressed, triggering fake breach"); - _enforcementService.TriggerLimitBreach(); - } - }); + .Subscribe(_ => + { + if (_enforcementService.IsLimitActive) + { + _logger.LogInformation("Limit breach debug button pressed while active, resetting breach"); + _enforcementService.ResetLimitBreach(); + } + else + { + _logger.LogInformation("Limit breach debug button pressed, triggering fake breach"); + _enforcementService.TriggerLimitBreach(); + } + }); } private async Task HandleRediscoveryAsync() @@ -193,18 +205,22 @@ public sealed class PowerMonitorInit if (added.Count > 0) { await _entityService.CreateDeviceEntitiesAsync(added); + if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Created entities for {Count} new sensors", added.Count); } } - if (removed.Count > 0) await RemoreDevicePriceEntities(removed); + if (removed.Count > 0) + { + await RemoreDevicePriceEntities(removed); + } if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", - newSensors.Count, added.Count, removed.Count); + newSensors.Count, added.Count, removed.Count); } } catch (Exception ex) @@ -229,11 +245,13 @@ public sealed class PowerMonitorInit try { var totalPower = ReadMainMeterPower(); + if (totalPower is null) { _mainMeterConsecutiveFailures++; + _logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, - PowerMonitorConsts.MainMeterMaxConsecutiveFailures); + PowerMonitorConsts.MainMeterMaxConsecutiveFailures); return; } @@ -251,8 +269,9 @@ public sealed class PowerMonitorInit var now = _timeProvider.GetLocalNow(); var elapsedSeconds = _lastPollTimestamp.HasValue - ? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10) - : _options.PollIntervalSeconds; + ? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10) + : _options.PollIntervalSeconds; + _lastPollTimestamp = now; _costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime); @@ -261,18 +280,16 @@ public sealed class PowerMonitorInit _anomalyStartTime = isAnomaly switch { - true when _anomalyStartTime is null => now, - false => null, - _ => _anomalyStartTime + true when _anomalyStartTime is null => now, false => null, _ => _anomalyStartTime }; var anomalyDuration = _anomalyStartTime.HasValue - ? now - _anomalyStartTime.Value - : TimeSpan.Zero; + ? now - _anomalyStartTime.Value + : TimeSpan.Zero; var systemStatus = _mainMeterConsecutiveFailures >= PowerMonitorConsts.MainMeterMaxConsecutiveFailures - ? "warning" - : "ok"; + ? "warning" + : "ok"; var context = new PowerUpdateContext { @@ -300,9 +317,9 @@ public sealed class PowerMonitorInit if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug( - "Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", - calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, - effectivePrice); + "Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", + calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, + effectivePrice); } } catch (Exception ex) @@ -318,10 +335,14 @@ public sealed class PowerMonitorInit if (state?.State is null or "unavailable" or "unknown") { _logger.LogDebug("NordPool price entity unavailable, using last known price"); + return 0; } - if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) return price; + if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) + { + return price; + } if (_logger.IsEnabled(LogLevel.Debug)) { @@ -340,11 +361,13 @@ public sealed class PowerMonitorInit case (true, false): _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); _highPowerNotificationActive = true; + break; case (false, true): _notificationService.DismissHighPowerNotification(); _highPowerNotificationActive = false; + break; } } @@ -352,11 +375,15 @@ public sealed class PowerMonitorInit private double? ReadMainMeterPower() { var state = _haContext.GetState(_options.MainMeterEntityId); - if (state?.State is null or "unavailable" or "unknown") return null; + + if (state?.State is null or "unavailable" or "unknown") + { + return null; + } return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) - ? value - : null; + ? value + : null; } private (IReadOnlyDictionary readings, List degraded) ReadDeviceSensors() @@ -367,19 +394,21 @@ public sealed class PowerMonitorInit foreach (var sensor in _discoveryService.CurrentDeviceSensors) { var state = _haContext.GetState(sensor.EntityId); + if (state?.State is null or "unavailable" or "unknown") { readings[sensor.EntityId] = 0; degraded.Add(sensor.EntityId); + continue; } if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)) { var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, - StringComparison.OrdinalIgnoreCase) - ? value * PowerMonitorConsts.WattsPerKilowatt - : value; + StringComparison.OrdinalIgnoreCase) + ? value * PowerMonitorConsts.WattsPerKilowatt + : value; readings[sensor.EntityId] = powerWatts; } diff --git a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs index 90aabaf..cba674c 100644 --- a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs +++ b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs @@ -1,7 +1,11 @@ +#region + using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; using PowerMonitorManager.Interface; +#endregion + namespace PowerMonitorManager; public static class PowerMonitorServiceRegistration @@ -9,13 +13,13 @@ public static class PowerMonitorServiceRegistration public static IServiceCollection AddPowerMonitor(this IServiceCollection services) { services - .AddNetDaemonApp() - .AddScoped() - .AddSingleton() - .AddSingleton() - .AddTransient() - .AddTransient() - .AddTransient(); + .AddNetDaemonApp() + .AddScoped() + .AddSingleton() + .AddSingleton() + .AddTransient() + .AddTransient() + .AddTransient(); return services; } diff --git a/PowerMonitor.Manager/PowerNotificationService.cs b/PowerMonitor.Manager/PowerNotificationService.cs index 6287939..d7a5316 100644 --- a/PowerMonitor.Manager/PowerNotificationService.cs +++ b/PowerMonitor.Manager/PowerNotificationService.cs @@ -1,9 +1,13 @@ +#region + using System.Globalization; using Microsoft.Extensions.Logging; using NetDaemon.HassModel; using PowerMonitorManager.Interface; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitorManager; public sealed class PowerNotificationService( @@ -18,28 +22,28 @@ public sealed class PowerNotificationService( var message = BuildHighPowerMessage(currentKw, thresholdKw); haContext.CallService( - PowerMonitorConsts.PersistentNotificationDomain, - PowerMonitorConsts.PersistentNotificationCreateService, - data: new - { - title = PowerMonitorConsts.HighPowerNotificationTitle, - message, - notification_id = PowerMonitorConsts.HighPowerNotificationId - }); + PowerMonitorConsts.PersistentNotificationDomain, + PowerMonitorConsts.PersistentNotificationCreateService, + data: new + { + title = PowerMonitorConsts.HighPowerNotificationTitle, + message, + notification_id = PowerMonitorConsts.HighPowerNotificationId + }); logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", - currentKw, thresholdKw); + currentKw, thresholdKw); } public void DismissHighPowerNotification() { haContext.CallService( - PowerMonitorConsts.PersistentNotificationDomain, - PowerMonitorConsts.PersistentNotificationDismissService, - data: new - { - notification_id = PowerMonitorConsts.HighPowerNotificationId - }); + PowerMonitorConsts.PersistentNotificationDomain, + PowerMonitorConsts.PersistentNotificationDismissService, + data: new + { + notification_id = PowerMonitorConsts.HighPowerNotificationId + }); logger.LogDebug("Dismissed high power usage notification"); } @@ -47,9 +51,9 @@ public sealed class PowerNotificationService( private static string BuildHighPowerMessage(double currentKw, double thresholdKw) { return string.Format( - CultureInfo.InvariantCulture, - "Total home power usage is **{0:F2} kW**, which exceeds the threshold of **{1:F1} kW**.\n\nConsider turning off high-power appliances to reduce consumption.", - currentKw, - thresholdKw); + CultureInfo.InvariantCulture, + "Total home power usage is **{0:F2} kW**, which exceeds the threshold of **{1:F1} kW**.\n\nConsider turning off high-power appliances to reduce consumption.", + currentKw, + thresholdKw); } } \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs index 354057b..f7d12d9 100644 --- a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs +++ b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs @@ -1,3 +1,5 @@ +#region + using System.Text.Json; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; @@ -9,6 +11,8 @@ using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; +#endregion + namespace PowerMonitorManager; public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService @@ -38,25 +42,25 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService var allEntities = _haContext.GetAllEntities(); var powerSensors = allEntities - .Where(IsPowerSensor) - .Where(e => !IsMainMeter(e.EntityId)) - .Where(e => !IsExcluded(e.EntityId)) - .Select(e => new PowerSensorInfo - { - EntityId = e.EntityId, - FriendlyName = GetFriendlyName(e), - DeviceName = ExtractDeviceName(e.EntityId), - UnitOfMeasurement = GetUnitOfMeasurement(e) - }) - .ToList(); + .Where(IsPowerSensor) + .Where(e => !IsMainMeter(e.EntityId)) + .Where(e => !IsExcluded(e.EntityId)) + .Select(e => new PowerSensorInfo + { + EntityId = e.EntityId, + FriendlyName = GetFriendlyName(e), + DeviceName = ExtractDeviceName(e.EntityId), + UnitOfMeasurement = GetUnitOfMeasurement(e) + }) + .ToList(); _currentDeviceSensors = powerSensors; if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation( - "Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", - powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); + "Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", + powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); } return powerSensors; @@ -64,10 +68,17 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService internal static bool IsPowerSensor(Entity entity) { - if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) return false; + if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) + { + return false; + } var attributes = entity.EntityState?.AttributesJson; - if (attributes is null) return false; + + if (attributes is null) + { + return false; + } var deviceClass = GetJsonStringProperty(attributes.Value, "device_class"); var unit = GetJsonStringProperty(attributes.Value, "unit_of_measurement"); @@ -90,38 +101,44 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService internal static string ExtractDeviceName(string entityId) { var withoutDomain = entityId.Contains('.') - ? entityId[(entityId.IndexOf('.') + 1)..] - : entityId; + ? entityId[(entityId.IndexOf('.') + 1)..] + : entityId; return withoutDomain.EndsWith("_power", StringComparison.OrdinalIgnoreCase) - ? withoutDomain[..^"_power".Length] - : withoutDomain; + ? withoutDomain[..^"_power".Length] + : withoutDomain; } private static string GetFriendlyName(Entity entity) { var name = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name"); + return name ?? entity.EntityId; } private static string GetUnitOfMeasurement(Entity entity) { var unit = GetJsonStringProperty(entity.EntityState?.AttributesJson, "unit_of_measurement"); + return unit ?? PowerMonitorConsts.WattUnit; } private static string? GetJsonStringProperty(JsonElement? element, string propertyName) { - if (element is null) return null; + if (element is null) + { + return null; + } return element.Value.TryGetProperty(propertyName, out var value) - ? value.GetString() - : null; + ? value.GetString() + : null; } internal static Regex GlobToRegex(string globPattern) { var regexPattern = "^" + Regex.Escape(globPattern).Replace("\\*", ".*") + "$"; + return new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); } } \ No newline at end of file diff --git a/PowerMonitor.Models/PowerMonitorEntity.cs b/PowerMonitor.Models/PowerMonitorEntity.cs index f348701..f26fcf4 100644 --- a/PowerMonitor.Models/PowerMonitorEntity.cs +++ b/PowerMonitor.Models/PowerMonitorEntity.cs @@ -1,6 +1,10 @@ +#region + using HomeAssistant.Models; using NetDaemon.Extensions.MqttEntityManager; +#endregion + namespace PowerMonitor.Models; public class PowerMonitorEntity : EntityCreateModel diff --git a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs index 98a3ea3..1d1ecc1 100644 --- a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs @@ -1,3 +1,5 @@ +#region + using FluentAssertions; using Microsoft.Extensions.Options; using Microsoft.Extensions.Time.Testing; @@ -8,6 +10,8 @@ using ShowerMonitor.Models.Enums; using ShowerMonitorManager; using ShowerMonitorManager.Models; +#endregion + namespace ShowerMonitor.Manager.Tests; public class ExhaustFanControlServiceTests @@ -15,19 +19,19 @@ public class ExhaustFanControlServiceTests private const string FanEntityId = "switch.exhaust_fan"; private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions(); - private readonly Mock _haContextMock = new(); + private readonly Mock _haContextMock = new Mock(); private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider(); private DateTimeOffset Now => _timeProvider.GetUtcNow(); - public static TheoryData ShowerProgressFanStateCases => new() + public static TheoryData ShowerProgressFanStateCases => new TheoryData { { "active while fan is off", ShowerState.Active, "off", true }, { "active while fan is on", ShowerState.Active, "on", false }, { "active while fan reports uppercase on", ShowerState.Active, "ON", false }, { "active while fan is unavailable", ShowerState.Active, "unavailable", true }, { "active while fan state is unknown", ShowerState.Active, "unknown", true }, - { "active while fan state is empty", ShowerState.Active, "", true }, + { "active while fan state is empty", ShowerState.Active, string.Empty, true }, { "active while fan state is missing", ShowerState.Active, null, true }, { "suspected while fan is off", ShowerState.Suspected, "off", true }, { "suspected while fan is on", ShowerState.Suspected, "on", false }, @@ -36,7 +40,7 @@ public class ExhaustFanControlServiceTests { "completed does not turn the fan on", ShowerState.Completed, "off", false } }; - public static TheoryData FanRunAfterCases => new() + public static TheoryData FanRunAfterCases => new TheoryData { { "well before run-after duration", 10, 60, false }, { "one second before run-after duration", 10, 599, false }, @@ -47,7 +51,7 @@ public class ExhaustFanControlServiceTests { "long run-after keeps fan running", 30, 300, false } }; - public static TheoryData ResetCases => new() + public static TheoryData ResetCases => new TheoryData { { "fan on after we turned it on", true, "on", true }, { "fan reports uppercase on", true, "ON", true }, @@ -83,8 +87,10 @@ public class ExhaustFanControlServiceTests bool expectTurnOff) { SetupFanState("off"); + var service = CreateService(ShowerMonitorTestData.CreateOptions( - fanRunAfterShowerMinutes: runAfterMinutes)); + fanRunAfterShowerMinutes: runAfterMinutes)); + var showerEnd = Now.AddMinutes(5); service.Evaluate(ShowerState.Active, Now); @@ -252,8 +258,8 @@ public class ExhaustFanControlServiceTests private void SetupFanState(string? state) { _haContextMock - .Setup(x => x.GetState(_defaultOptions.ExhaustFanEntityId)) - .Returns(ShowerMonitorTestData.FanState(state)); + .Setup(x => x.GetState(_defaultOptions.ExhaustFanEntityId)) + .Returns(ShowerMonitorTestData.FanState(state)); } private void VerifySwitchCall( @@ -263,18 +269,15 @@ public class ExhaustFanControlServiceTests string? because = null) { var targets = _haContextMock.Invocations - .Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService) - && (string?)invocation.Arguments[0] == "switch" - && (string?)invocation.Arguments[1] == service) - .Select(invocation => (ServiceTarget?)invocation.Arguments[2]) - .ToList(); + .Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService) && (string?)invocation.Arguments[0] == "switch" && (string?)invocation.Arguments[1] == service) + .Select(invocation => (ServiceTarget?)invocation.Arguments[2]) + .ToList(); targets.Should().HaveCount(expectedCount, because); - targets.Should().OnlyContain( - target => target != null - && target.EntityIds != null - && target.EntityIds.Count == 1 - && target.EntityIds.Single() == expectedEntityId, - because); + + targets.Should() + .OnlyContain( + target => target != null && target.EntityIds != null && target.EntityIds.Count == 1 && target.EntityIds.Single() == expectedEntityId, + because); } } \ No newline at end of file diff --git a/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs b/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs index e0a3ee2..19f267f 100644 --- a/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs +++ b/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs @@ -1,8 +1,12 @@ +#region + using FluentAssertions; using Microsoft.Extensions.Time.Testing; using ShowerMonitor.Models; using ShowerMonitorManager; +#endregion + namespace ShowerMonitor.Manager.Tests; public class HumidityRateCalculatorTests @@ -13,7 +17,7 @@ public class HumidityRateCalculatorTests private DateTimeOffset Now => _timeProvider.GetUtcNow(); - public static TheoryData RateCases => new() + public static TheoryData RateCases => new TheoryData { { "no readings", 5, [], [], 0.0 }, { "single reading", 5, [52.9], [0], 0.0 }, @@ -49,7 +53,9 @@ public class HumidityRateCalculatorTests var calculator = new HumidityRateCalculator(windowSize); for (var i = 0; i < humidities.Length; i++) + { calculator.RecordReading(humidities[i], Now.AddSeconds(offsetSeconds[i])); + } calculator.GetRatePerMinute().Should().BeApproximately(expectedRate, 1e-6, $"scenario: {scenario}"); } @@ -58,20 +64,24 @@ public class HumidityRateCalculatorTests public void GetRatePerMinute_WithGeneratedLinearSeries_ReturnsSlopeForEveryWindowSize() { const double ratePerMinute = 2.5; + var series = ShowerMonitorTestData.CreateLinearHumiditySeries( - 45.0, - ratePerMinute, - 12); + 45.0, + ratePerMinute, + 12); for (var windowSize = 2; windowSize <= series.Count; windowSize++) { var calculator = new HumidityRateCalculator(windowSize); - foreach (var sample in series) calculator.RecordReading(sample.Humidity, Now + sample.Offset); + foreach (var sample in series) + { + calculator.RecordReading(sample.Humidity, Now + sample.Offset); + } calculator.GetRatePerMinute() - .Should() - .BeApproximately(ratePerMinute, 1e-9, $"window size {windowSize}"); + .Should() + .BeApproximately(ratePerMinute, 1e-9, $"window size {windowSize}"); } } diff --git a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs index aed039b..838e6df 100644 --- a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs @@ -1,3 +1,5 @@ +#region + using FluentAssertions; using Microsoft.Extensions.Options; using Microsoft.Extensions.Time.Testing; @@ -6,6 +8,8 @@ using ShowerMonitorManager; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; +#endregion + namespace ShowerMonitor.Manager.Tests; public class ShowerDetectionServiceTests @@ -15,7 +19,7 @@ public class ShowerDetectionServiceTests private DateTimeOffset Now => _timeProvider.GetUtcNow(); - public static TheoryData IdleThresholdCases => new() + public static TheoryData IdleThresholdCases => new TheoryData { { "both thresholds met exactly", 52.0, 44.0, ShowerState.Suspected }, { "rate one step under threshold", 51.98, 44.0, ShowerState.Idle }, @@ -27,7 +31,7 @@ public class ShowerDetectionServiceTests { "very large humidity spike", 1000.0, 500.0, ShowerState.Suspected } }; - public static TheoryData ConfirmationCases => new() + public static TheoryData ConfirmationCases => new TheoryData { { "confirmation window reached", 66.0, 49.5, 120, ShowerState.Active }, { "confirmation window not yet reached", 66.0, 49.5, 119, ShowerState.Suspected }, @@ -39,14 +43,14 @@ public class ShowerDetectionServiceTests { "very large humidity at confirmation", 1000.0, 900.0, 120, ShowerState.Active } }; - public static TheoryData RecoveryBoundaryCases => new() + public static TheoryData RecoveryBoundaryCases => new TheoryData { { "differential well under threshold", 52.0, ShowerState.Completed }, { "differential exactly at threshold", 50.0, ShowerState.Completed }, { "differential just above threshold", 49.98, ShowerState.Declining } }; - public static TheoryData MaxDurationCases => new() + public static TheoryData MaxDurationCases => new TheoryData { { "one second before max duration", 3_599, ShowerState.Active }, { "exactly at max duration", 3_600, ShowerState.Declining }, @@ -149,16 +153,19 @@ public class ShowerDetectionServiceTests EvaluateBaselineAndSpike(service, start); var state = service.Evaluate( - bathroomHumidity, - mainHomeHumidity, - start.AddSeconds(30 + secondsAfterSpike)); + bathroomHumidity, + mainHomeHumidity, + start.AddSeconds(30 + secondsAfterSpike)); state.Should().Be(expectedState, $"scenario: {scenario}"); service.CurrentState.Should().Be(expectedState, $"scenario: {scenario}"); service.TodaySessionCount.Should().Be(0); service.LastCompletedSession.Should().BeNull(); - if (expectedState == ShowerState.Active) service.CurrentSession.Should().NotBeNull(); + if (expectedState == ShowerState.Active) + { + service.CurrentSession.Should().NotBeNull(); + } } [Fact] diff --git a/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs b/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs index 976a260..fdfcd59 100644 --- a/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs +++ b/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs @@ -1,8 +1,12 @@ +#region + using Microsoft.Extensions.Time.Testing; using NetDaemon.HassModel.Entities; using ShowerMonitor.Models; using ShowerMonitorManager.Models; +#endregion + namespace ShowerMonitor.Manager.Tests; /// @@ -13,7 +17,7 @@ namespace ShowerMonitor.Manager.Tests; internal static class ShowerMonitorTestData { /// Fixed base time used by all timestamp-sensitive tests. - private static readonly DateTimeOffset BaseTimestamp = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset BaseTimestamp = new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); /// Creates a fake clock positioned at unless overridden. public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) @@ -39,15 +43,13 @@ internal static class ShowerMonitorTestData return new ShowerMonitorOptions { ExhaustFanEntityId = exhaustFanEntityId, - FanRunAfterShowerMinutes = fanRunAfterShowerMinutes - ?? (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes, + FanRunAfterShowerMinutes = fanRunAfterShowerMinutes ?? (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes, SpikeRateThreshold = spikeRateThreshold, MinDifferentialHumidity = minDifferentialHumidity, PeakHumidityThreshold = peakHumidityThreshold, ConfirmationWindowMinutes = confirmationWindowMinutes, RecoveryDifferentialThreshold = recoveryDifferentialThreshold, - MaxShowerDurationMinutes = maxShowerDurationMinutes - ?? (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes, + MaxShowerDurationMinutes = maxShowerDurationMinutes ?? (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes, RateWindowSize = rateWindowSize }; } @@ -81,9 +83,9 @@ internal static class ShowerMonitorTestData return [ .. Enumerable.Range(0, sampleCount) - .Select(i => new HumiditySample( - startHumidity + ratePerMinute * i * intervalSeconds / 60.0, - TimeSpan.FromSeconds(i * intervalSeconds))) + .Select(i => new HumiditySample( + startHumidity + ratePerMinute * i * intervalSeconds / 60.0, + TimeSpan.FromSeconds(i * intervalSeconds))) ]; } diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs index 1c7866a..20b32d2 100644 --- a/ShowerMonitor.Manager/ExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -1,3 +1,5 @@ +#region + using Microsoft.Extensions.Options; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; @@ -5,13 +7,15 @@ using ShowerMonitor.Models.Enums; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; +#endregion + namespace ShowerMonitorManager; public sealed class ExhaustFanControlService( IHaContext haContext, IOptions options) : IExhaustFanControlService { - private readonly Lock _lock = new(); + private readonly Lock _lock = new Lock(); private readonly ShowerMonitorOptions _options = options.Value; private bool _fanTurnedOnByUs; @@ -27,16 +31,19 @@ public sealed class ExhaustFanControlService( case ShowerState.Suspected: TurnOnFanIfNeeded(); _showerEndedAt = null; + break; case ShowerState.Declining: case ShowerState.Completed: _showerEndedAt ??= timestamp; EvaluatePostShowerFanOff(timestamp); + break; case ShowerState.Idle: EvaluatePostShowerFanOff(timestamp); + break; default: @@ -67,10 +74,17 @@ public sealed class ExhaustFanControlService( private void TurnOnFanIfNeeded() { - if (_fanTurnedOnByUs) return; + if (_fanTurnedOnByUs) + { + return; + } var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State; - if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) return; + + if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) + { + return; + } haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); _fanTurnedOnByUs = true; @@ -78,12 +92,18 @@ public sealed class ExhaustFanControlService( private void EvaluatePostShowerFanOff(DateTimeOffset timestamp) { - if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue) return; + if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue) + { + return; + } var elapsed = timestamp - _showerEndedAt.Value; var runAfterDuration = TimeSpan.FromMinutes(_options.FanRunAfterShowerMinutes); - if (elapsed < runAfterDuration) return; + if (elapsed < runAfterDuration) + { + return; + } haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); _fanTurnedOnByUs = false; diff --git a/ShowerMonitor.Manager/HumidityRateCalculator.cs b/ShowerMonitor.Manager/HumidityRateCalculator.cs index 5fb506a..257a3f6 100644 --- a/ShowerMonitor.Manager/HumidityRateCalculator.cs +++ b/ShowerMonitor.Manager/HumidityRateCalculator.cs @@ -1,11 +1,15 @@ +#region + using ShowerMonitorManager.Interface; +#endregion + namespace ShowerMonitorManager; public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalculator { - private readonly Lock _lock = new(); - private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new(); + private readonly Lock _lock = new Lock(); + private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new Queue<(double Humidity, DateTimeOffset Timestamp)>(); private double? _previousReading; public double? PreviousReading @@ -26,7 +30,10 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul _readings.Enqueue((humidity, timestamp)); _previousReading = humidity; - while (_readings.Count > windowSize) _readings.Dequeue(); + while (_readings.Count > windowSize) + { + _readings.Dequeue(); + } } } @@ -34,13 +41,19 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul { lock (_lock) { - if (_readings.Count < 2) return 0.0; + if (_readings.Count < 2) + { + return 0.0; + } var oldest = _readings.Peek(); var newest = _readings.Last(); var elapsedMinutes = (newest.Timestamp - oldest.Timestamp).TotalMinutes; - if (elapsedMinutes <= 0) return 0.0; + if (elapsedMinutes <= 0) + { + return 0.0; + } return (newest.Humidity - oldest.Humidity) / elapsedMinutes; } diff --git a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs index aac9df8..48a42c8 100644 --- a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs @@ -1,5 +1,9 @@ +#region + using ShowerMonitor.Models.Enums; +#endregion + namespace ShowerMonitorManager.Interface; public interface IExhaustFanControlService diff --git a/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs index 3abf677..fb538d6 100644 --- a/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs +++ b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs @@ -1,6 +1,10 @@ +#region + using ShowerMonitor.Models; using ShowerMonitor.Models.Enums; +#endregion + namespace ShowerMonitorManager.Interface; public interface IShowerDetectionService diff --git a/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs index f6ca7ab..be48f00 100644 --- a/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs +++ b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs @@ -1,5 +1,9 @@ +#region + using ShowerMonitorManager.Models; +#endregion + namespace ShowerMonitorManager.Interface; public interface IShowerMonitorEntityService diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs index 7f6146c..3088d8c 100644 --- a/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs +++ b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs @@ -1,5 +1,9 @@ +#region + using ShowerMonitor.Models; +#endregion + namespace ShowerMonitorManager.Models; public sealed class ShowerMonitorOptions diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs index a010f62..7b1b701 100644 --- a/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs +++ b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs @@ -1,6 +1,10 @@ +#region + using ShowerMonitor.Models; using ShowerMonitor.Models.Enums; +#endregion + namespace ShowerMonitorManager.Models; public sealed class ShowerMonitorUpdateContext diff --git a/ShowerMonitor.Manager/ShowerDetectionService.cs b/ShowerMonitor.Manager/ShowerDetectionService.cs index c67164a..b02a47d 100644 --- a/ShowerMonitor.Manager/ShowerDetectionService.cs +++ b/ShowerMonitor.Manager/ShowerDetectionService.cs @@ -1,9 +1,13 @@ +#region + using Microsoft.Extensions.Options; using ShowerMonitor.Models; using ShowerMonitor.Models.Enums; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; +#endregion + namespace ShowerMonitorManager; public sealed class ShowerDetectionService( @@ -11,7 +15,7 @@ public sealed class ShowerDetectionService( IOptions options) : IShowerDetectionService { - private readonly Lock _lock = new(); + private readonly Lock _lock = new Lock(); private readonly ShowerMonitorOptions _options = options.Value; private ShowerSession? _currentSession; @@ -85,6 +89,7 @@ public sealed class ShowerDetectionService( lock (_lock) { _lastRate = rate; + _currentState = _currentState switch { ShowerState.Idle => EvaluateIdle(rate, differential, bathroomHumidity, timestamp), @@ -110,12 +115,15 @@ public sealed class ShowerDetectionService( private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp) { - var showerSuspected = rate >= _options.SpikeRateThreshold - && differential >= _options.MinDifferentialHumidity; + var showerSuspected = rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity; - if (!showerSuspected) return ShowerState.Idle; + if (!showerSuspected) + { + return ShowerState.Idle; + } _suspectedSince = timestamp; + _currentSession = new ShowerSession { StartTime = timestamp, @@ -137,15 +145,17 @@ public sealed class ShowerDetectionService( var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes); - if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow - && humidity >= _options.PeakHumidityThreshold - && differential >= _options.MinDifferentialHumidity) + if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow && humidity >= _options.PeakHumidityThreshold && differential >= _options.MinDifferentialHumidity) { return ShowerState.Active; } var showerAbandoned = rate < 0 && differential < _options.MinDifferentialHumidity; - if (!showerAbandoned) return ShowerState.Suspected; + + if (!showerAbandoned) + { + return ShowerState.Suspected; + } CompleteSessionCleanup(); @@ -161,11 +171,13 @@ public sealed class ShowerDetectionService( } var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); - var maxDurationReached = _currentSession is not null - && _currentSession.GetDuration(timestamp) >= maxDuration; + var maxDurationReached = _currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration; var humidityRecovered = rate < 0 && differential < _options.MinDifferentialHumidity; - if (maxDurationReached || humidityRecovered) return TransitionToDeclining(); + if (maxDurationReached || humidityRecovered) + { + return TransitionToDeclining(); + } return ShowerState.Active; } @@ -180,10 +192,12 @@ public sealed class ShowerDetectionService( } var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); - var maxDurationReached = _currentSession is not null - && _currentSession.GetDuration(timestamp) >= maxDuration; + var maxDurationReached = _currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration; - if (!maxDurationReached) return ShowerState.Declining; + if (!maxDurationReached) + { + return ShowerState.Declining; + } CompleteSession(timestamp); @@ -204,7 +218,10 @@ public sealed class ShowerDetectionService( private void CompleteSession(DateTimeOffset endTime) { - if (_currentSession is null) return; + if (_currentSession is null) + { + return; + } _currentSession.EndTime = endTime; _lastCompletedSession = _currentSession; diff --git a/ShowerMonitor.Manager/ShowerMonitorEntityService.cs b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs index e400a5a..faad397 100644 --- a/ShowerMonitor.Manager/ShowerMonitorEntityService.cs +++ b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; @@ -7,6 +9,8 @@ using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; using static ShowerMonitor.Models.ShowerMonitorConsts; +#endregion + namespace ShowerMonitorManager; public sealed class ShowerMonitorEntityService( @@ -30,17 +34,18 @@ public sealed class ShowerMonitorEntityService( cancellationToken.ThrowIfCancellationRequested(); var entities = GetAllEntities(); + var createTasks = entities.Select(async entity => - { - try - { - await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId); - } - }); + { + try + { + await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId); + } + }); await Task.WhenAll(createTasks).ConfigureAwait(false); } @@ -79,6 +84,7 @@ public sealed class ShowerMonitorEntityService( catch (Exception ex) { logger.LogError(ex, "Error cleaning up ShowerMonitor entities"); + throw; } } @@ -140,60 +146,76 @@ public sealed class ShowerMonitorEntityService( private async Task UpdateDifferentialAsync(double differential, string timestamp) { await SetEntityStateSafe(DifferentialEntityId, - Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); + await SetEntityAttributesSafe(DifferentialEntityId, new - { - unit_of_measurement = "%", - friendly_name = "Bathroom differential humidity", - last_updated = timestamp - }).ConfigureAwait(false); + { + unit_of_measurement = "%", + friendly_name = "Bathroom differential humidity", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateHumidityRateAsync(double rate, string timestamp) { await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)) - .ConfigureAwait(false); + .ConfigureAwait(false); + await SetEntityAttributesSafe(HumidityRateEntityId, new - { - unit_of_measurement = "%/min", - friendly_name = "Humidity rate of change", - last_updated = timestamp - }).ConfigureAwait(false); + { + unit_of_measurement = "%/min", + friendly_name = "Humidity rate of change", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateTodaySessionCountAsync(int count, string timestamp) { await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)) - .ConfigureAwait(false); + .ConfigureAwait(false); + await SetEntityAttributesSafe(TodaySessionCountEntityId, new - { - friendly_name = "Showers today", - last_updated = timestamp - }).ConfigureAwait(false); + { + friendly_name = "Showers today", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp) { - if (session is null) return; + if (session is null) + { + return; + } var durationSeconds = (int)session.Duration.TotalSeconds; + await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture)) - .ConfigureAwait(false); + .ConfigureAwait(false); + await SetEntityAttributesSafe(LastShowerDurationEntityId, new - { - formatted = FormatDuration(session.Duration), - peak_humidity = session.PeakHumidity, - friendly_name = "Last shower duration", - last_updated = timestamp - }).ConfigureAwait(false); + { + formatted = FormatDuration(session.Duration), + peak_humidity = session.PeakHumidity, + friendly_name = "Last shower duration", + last_updated = timestamp + }) + .ConfigureAwait(false); await SetEntityStateSafe(LastShowerTimeEntityId, - session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false); + session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)) + .ConfigureAwait(false); + await SetEntityAttributesSafe(LastShowerTimeEntityId, new - { - friendly_name = "Last shower time", - last_updated = timestamp - }).ConfigureAwait(false); + { + friendly_name = "Last shower time", + last_updated = timestamp + }) + .ConfigureAwait(false); } private async Task SetEntityStateSafe(string entityId, string state) diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs index a4def7b..8cffaa6 100644 --- a/ShowerMonitor.Manager/ShowerMonitorInit.cs +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -1,3 +1,5 @@ +#region + using System.Globalization; using System.Reactive.Concurrency; using Microsoft.Extensions.Logging; @@ -10,6 +12,8 @@ using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; using static ShowerMonitor.Models.ShowerMonitorConsts; +#endregion + namespace ShowerMonitorManager; [NetDaemonApp] @@ -69,7 +73,10 @@ public sealed class ShowerMonitorInit { await Task.Delay(TimeSpan.FromSeconds(3)); - if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync(); + if (_options.CleanupEntitiesOnStartup) + { + await _entityService.CleanupEntitiesAsync(); + } await _entityService.CreateEntitiesAsync(); @@ -81,6 +88,7 @@ public sealed class ShowerMonitorInit catch (Exception ex) { _logger.LogError(ex, "Error initializing ShowerMonitor"); + throw; } } @@ -99,28 +107,29 @@ public sealed class ShowerMonitorInit private void ScheduleMidnightReset() { _scheduler.ScheduleCron("0 0 * * *", () => - { - try - { - _logger.LogDebug("Midnight reset: clearing shower session counters"); - _detectionService.ResetDailyCounters(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error during midnight reset"); - } - }); + { + try + { + _logger.LogDebug("Midnight reset: clearing shower session counters"); + _detectionService.ResetDailyCounters(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during midnight reset"); + } + }); } private void SubscribeToCleanupButton() { var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); + cleanupButton.StateChanges() - .Subscribe(_ => - { - _logger.LogDebug("Cleanup button pressed, removing all ShowerMonitor entities"); - Task.Run(HandleCleanupAsync); - }); + .Subscribe(_ => + { + _logger.LogDebug("Cleanup button pressed, removing all ShowerMonitor entities"); + Task.Run(HandleCleanupAsync); + }); } private async Task HandleCleanupAsync() @@ -144,6 +153,7 @@ public sealed class ShowerMonitorInit if (_cleanedUp) { _logger.LogDebug("ShowerMonitor is cleaned up, skipping poll"); + return; } @@ -157,7 +167,7 @@ public sealed class ShowerMonitorInit if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", - bathroomHumidity, mainHomeHumidity); + bathroomHumidity, mainHomeHumidity); } return; @@ -183,7 +193,7 @@ public sealed class ShowerMonitorInit if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}", - bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state); + bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state); } } catch (Exception ex) @@ -196,7 +206,10 @@ public sealed class ShowerMonitorInit { var state = _haContext.GetState(entityId); - if (state?.State is null or "unavailable" or "unknown") return null; + if (state?.State is null or "unavailable" or "unknown") + { + return null; + } return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; } diff --git a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs index 774f4a8..a03ea7a 100644 --- a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs +++ b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs @@ -1,9 +1,13 @@ +#region + using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; +#endregion + namespace ShowerMonitorManager; public static class ShowerMonitorServiceRegistration @@ -11,17 +15,21 @@ public static class ShowerMonitorServiceRegistration public static IServiceCollection AddShowerMonitor(this IServiceCollection services, IConfiguration configuration) { var options = configuration - .GetSection(ShowerMonitorOptions.SectionName) - .Get() ?? new ShowerMonitorOptions(); + .GetSection(ShowerMonitorOptions.SectionName) + .Get() ?? + new ShowerMonitorOptions(); - if (!options.Enabled) return services; + if (!options.Enabled) + { + return services; + } services - .AddNetDaemonApp() - .AddSingleton(_ => new HumidityRateCalculator(options.RateWindowSize)) - .AddSingleton() - .AddScoped() - .AddTransient(); + .AddNetDaemonApp() + .AddSingleton(_ => new HumidityRateCalculator(options.RateWindowSize)) + .AddSingleton() + .AddScoped() + .AddTransient(); return services; } diff --git a/ShowerMonitor.Models/ShowerMonitorEntity.cs b/ShowerMonitor.Models/ShowerMonitorEntity.cs index d6224b6..ea22238 100644 --- a/ShowerMonitor.Models/ShowerMonitorEntity.cs +++ b/ShowerMonitor.Models/ShowerMonitorEntity.cs @@ -1,6 +1,10 @@ +#region + using HomeAssistant.Models; using NetDaemon.Extensions.MqttEntityManager; +#endregion + namespace ShowerMonitor.Models; public class ShowerMonitorEntity : EntityCreateModel