diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj index 56f1320..3691f73 100644 --- a/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj +++ b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj @@ -1,34 +1,34 @@ - - net10.0 - enable - enable - false - + + net10.0 + enable + enable + false + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - - + + + - - - - + + + + diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs index 94b6ecb..35f90f7 100644 --- a/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs +++ b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs @@ -8,150 +8,17 @@ using NetDaemon.HassModel.Entities; namespace BatteryMonitor.Manager.Tests; /// -/// Shared, deterministic builders and datasets used by the BatteryMonitor tests. -/// Keeping entity/state construction and generated inputs here means the test -/// classes only describe the scenario under test. +/// Shared, deterministic builders and datasets used by the BatteryMonitor tests. +/// Keeping entity/state construction and generated inputs here means the test +/// classes only describe the scenario under test. /// internal static class BatteryMonitorTestData { private const string DefaultFriendlyName = "Battery Device"; /// - /// Describes one entity exposed through . - /// - public sealed record EntitySpec - { - public required string EntityId { get; init; } - - public string? State { get; init; } = "50"; - - public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass; - - public string? FriendlyName { get; init; } = DefaultFriendlyName; - - /// When false the context returns no for the entity. - public bool HasState { get; init; } = true; - } - - /// A battery device-class sensor. - public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName) - { - return new EntitySpec - { - EntityId = entityId, - State = state, - FriendlyName = friendlyName - }; - } - - /// A sensor with an arbitrary (or missing) device class. - public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, string? friendlyName = DefaultFriendlyName) - { - return new EntitySpec - { - EntityId = entityId, - DeviceClass = deviceClass, - State = state, - FriendlyName = friendlyName - }; - } - - public static EntityState CreateEntityState(EntitySpec spec) - { - var attributes = new Dictionary(StringComparer.Ordinal); - - if (spec.DeviceClass is not null) - { - attributes["device_class"] = spec.DeviceClass; - } - - if (spec.FriendlyName is not null) - { - attributes["friendly_name"] = spec.FriendlyName; - } - - return new EntityState - { - State = spec.State, - AttributesJson = JsonSerializer.SerializeToElement(attributes) - }; - } - - /// - /// Wires and - /// on the mock, exposing the entities in declaration order. - /// - public static void ConfigureHaContext(Mock haContextMock, params EntitySpec[] entities) - { - var entityList = new List(entities.Length); - - foreach (var spec in entities) - { - if (spec.HasState) - { - haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec)); - } - - entityList.Add(new Entity(haContextMock.Object, spec.EntityId)); - } - - haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList); - } - - public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null) - { - return new BatterySensorInfo - { - EntityId = entityId, - FriendlyName = friendlyName ?? entityId, - BatteryLevel = batteryLevel - }; - } - - public static List CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors) - { - return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))]; - } - - public static List CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors) - { - return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))]; - } - - /// - /// Generates battery sensors with every integer level in 0..count-1. - /// - public static EntitySpec[] CreateGeneratedBatteryEntities(int count) - { - return - [ - .. Enumerable.Range(0, count) - .Select(i => Battery( - $"sensor.generated_battery_{i:D3}", - i.ToString(CultureInfo.InvariantCulture), - $"Generated Battery {i:D3}")) - ]; - } - - /// - /// Generates notification devices with deterministic, non-monotonic levels so - /// ordering behaviour is exercised over more than a handful of rows. - /// - public static IReadOnlyList CreateGeneratedSensorInfos(int count) - { - return - [ - .. Enumerable.Range(0, count) - .Select(i => CreateSensorInfo( - $"sensor.generated_{i:D3}", - i * 37 % 101, - $"Generated Device {i:D3}")) - ]; - } - - /// - /// (threshold, state, expected) rows straddling the strict level < threshold - /// boundary, including zero/negative thresholds and int min/max thresholds. + /// (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() { @@ -183,8 +50,8 @@ internal static class BatteryMonitorTestData }; /// - /// States that must never produce a , including - /// whitespace/malformed strings and a null state. + /// States that must never produce a , including + /// whitespace/malformed strings and a null state. /// public static TheoryData UnusableStateRows { get; } = [ @@ -203,9 +70,121 @@ internal static class BatteryMonitorTestData null ]; + /// Device counts used to exercise notification payload generation. + public static TheoryData NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50]; + + /// A battery device-class sensor. + public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName) + { + return new EntitySpec + { + EntityId = entityId, + State = state, + FriendlyName = friendlyName + }; + } + + /// A sensor with an arbitrary (or missing) device class. + public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, + string? friendlyName = DefaultFriendlyName) + { + return new EntitySpec + { + EntityId = entityId, + DeviceClass = deviceClass, + State = state, + FriendlyName = friendlyName + }; + } + + public static EntityState CreateEntityState(EntitySpec spec) + { + var attributes = new Dictionary(StringComparer.Ordinal); + + if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass; + + if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName; + + return new EntityState + { + State = spec.State, + AttributesJson = JsonSerializer.SerializeToElement(attributes) + }; + } + /// - /// Cross-product of every excluded keyword (lower and upper case) plus - /// non-excluded look-alikes that must not be filtered. + /// Wires and + /// on the mock, exposing the entities in declaration order. + /// + public static void ConfigureHaContext(Mock haContextMock, params EntitySpec[] entities) + { + var entityList = new List(entities.Length); + + foreach (var spec in entities) + { + if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec)); + + entityList.Add(new Entity(haContextMock.Object, spec.EntityId)); + } + + haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList); + } + + public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null) + { + return new BatterySensorInfo + { + EntityId = entityId, + FriendlyName = friendlyName ?? entityId, + BatteryLevel = batteryLevel + }; + } + + public static List CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors) + { + return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))]; + } + + public static List CreateSensorInfos( + params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors) + { + return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))]; + } + + /// + /// Generates battery sensors with every integer level in 0..count-1. + /// + public static EntitySpec[] CreateGeneratedBatteryEntities(int count) + { + return + [ + .. Enumerable.Range(0, count) + .Select(i => Battery( + $"sensor.generated_battery_{i:D3}", + i.ToString(CultureInfo.InvariantCulture), + $"Generated Battery {i:D3}")) + ]; + } + + /// + /// Generates notification devices with deterministic, non-monotonic levels so + /// ordering behaviour is exercised over more than a handful of rows. + /// + public static IReadOnlyList CreateGeneratedSensorInfos(int count) + { + return + [ + .. Enumerable.Range(0, count) + .Select(i => CreateSensorInfo( + $"sensor.generated_{i:D3}", + i * 37 % 101, + $"Generated Device {i:D3}")) + ]; + } + + /// + /// Cross-product of every excluded keyword (lower and upper case) plus + /// non-excluded look-alikes that must not be filtered. /// public static TheoryData ExcludedEntityIdRows() { @@ -229,6 +208,20 @@ internal static class BatteryMonitorTestData return data; } - /// Device counts used to exercise notification payload generation. - public static TheoryData NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50]; -} + /// + /// Describes one entity exposed through . + /// + public sealed record EntitySpec + { + public required string EntityId { get; init; } + + public string? State { get; init; } = "50"; + + public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass; + + public string? FriendlyName { get; init; } = DefaultFriendlyName; + + /// When false the context returns no for the entity. + public bool HasState { get; init; } = true; + } +} \ No newline at end of file diff --git a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs index 62b7a23..a27aa94 100644 --- a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs +++ b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs @@ -1,11 +1,11 @@ using System.Text.Json; +using BatteryMonitor.Models; +using BatteryMonitorManager; using FluentAssertions; using Microsoft.Extensions.Logging; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using BatteryMonitor.Models; -using BatteryMonitorManager; using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; namespace BatteryMonitor.Manager.Tests; @@ -36,10 +36,10 @@ public class BatteryNotificationServiceTests public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount) { var devices = CreateSensorInfos( - [ - .. Enumerable.Range(0, deviceCount) - .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5))) - ]); + [ + .. Enumerable.Range(0, deviceCount) + .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5))) + ]); var sut = CreateSut(); sut.NotifyLowBattery(devices); @@ -139,10 +139,7 @@ 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()); @@ -222,7 +219,8 @@ 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)); @@ -279,4 +277,4 @@ public class BatteryNotificationServiceTests } #endregion -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs index f434127..7b76a42 100644 --- a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs +++ b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs @@ -1,11 +1,11 @@ using System.Globalization; +using BatteryMonitor.Models; +using BatteryMonitorManager; using FluentAssertions; using Microsoft.Extensions.Logging; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using BatteryMonitor.Models; -using BatteryMonitorManager; using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; namespace BatteryMonitor.Manager.Tests; @@ -25,6 +25,17 @@ public class BatterySensorDiscoveryServiceTests ConfigureHaContext(_haContextMock, entities); } + #region IsExcludedDevice + + [Theory] + [MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))] + public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected) + { + BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected); + } + + #endregion + #region Discovery [Fact] @@ -77,7 +88,8 @@ public class BatterySensorDiscoveryServiceTests [InlineData("sensor.no_device_class", null)] [InlineData("sensorx.bathroom_battery", "battery")] [InlineData("switch.bathroom_battery", "battery")] - public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId, string? deviceClass) + public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId, + string? deviceClass) { SetupEntities( Sensor(entityId, deviceClass, "2", "Ignored Entity"), @@ -111,7 +123,8 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor() { SetupEntities( - new EntitySpec { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false }, + new EntitySpec + { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false }, Battery("sensor.bedroom_battery", "3", "Bedroom Battery") ); @@ -124,7 +137,8 @@ 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")); @@ -133,10 +147,7 @@ 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)); @@ -239,7 +250,8 @@ 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 @@ -279,15 +291,4 @@ public class BatterySensorDiscoveryServiceTests } #endregion - - #region IsExcludedDevice - - [Theory] - [MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))] - public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected) - { - BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected); - } - - #endregion -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj index 851e118..e493f51 100644 --- a/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj +++ b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj @@ -8,20 +8,20 @@ - - <_Parameter1>BatteryMonitor.Manager.Tests - + + <_Parameter1>BatteryMonitor.Manager.Tests + - - + + - - - + + + diff --git a/BatteryMonitor.Manager/BatteryMonitorInit.cs b/BatteryMonitor.Manager/BatteryMonitorInit.cs index 7b0e386..a72d22b 100644 --- a/BatteryMonitor.Manager/BatteryMonitorInit.cs +++ b/BatteryMonitor.Manager/BatteryMonitorInit.cs @@ -1,21 +1,22 @@ using System.Reactive.Concurrency; +using BatteryMonitor.Models; +using BatteryMonitorManager.Interface; +using BatteryMonitorManager.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; -using BatteryMonitorManager.Interface; -using BatteryMonitorManager.Models; namespace BatteryMonitorManager; [NetDaemonApp] public sealed class BatteryMonitorInit { - private readonly ILogger _logger; - private readonly IScheduler _scheduler; private readonly IBatterySensorDiscoveryService _discoveryService; + private readonly ILogger _logger; private readonly IBatteryNotificationService _notificationService; private readonly BatteryMonitorOptions _options; + private readonly IScheduler _scheduler; public BatteryMonitorInit( ILogger logger, @@ -55,9 +56,8 @@ public sealed class BatteryMonitorInit CheckAndNotify(); if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent); - } + _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", + _options.BatteryThresholdPercent); } catch (Exception ex) { @@ -68,7 +68,7 @@ public sealed class BatteryMonitorInit private void ScheduleDailyCheck() { - _scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () => + _scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () => { try { @@ -98,4 +98,4 @@ public sealed class BatteryMonitorInit _logger.LogDebug("No low battery devices found"); } } -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs index aa1e2d2..5608f34 100644 --- a/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs +++ b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs @@ -1,8 +1,8 @@ +using BatteryMonitorManager.Interface; +using BatteryMonitorManager.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; -using BatteryMonitorManager.Interface; -using BatteryMonitorManager.Models; namespace BatteryMonitorManager; @@ -14,10 +14,7 @@ public static class BatteryMonitorServiceRegistration .GetSection(BatteryMonitorOptions.SectionName) .Get() ?? new BatteryMonitorOptions(); - if (!options.Enabled) - { - return services; - } + if (!options.Enabled) return services; services .AddNetDaemonApp() @@ -26,4 +23,4 @@ public static class BatteryMonitorServiceRegistration return services; } -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager/BatteryNotificationService.cs b/BatteryMonitor.Manager/BatteryNotificationService.cs index ca42119..45deb32 100644 --- a/BatteryMonitor.Manager/BatteryNotificationService.cs +++ b/BatteryMonitor.Manager/BatteryNotificationService.cs @@ -1,8 +1,8 @@ using System.Text; -using Microsoft.Extensions.Logging; -using NetDaemon.HassModel; using BatteryMonitor.Models; using BatteryMonitorManager.Interface; +using Microsoft.Extensions.Logging; +using NetDaemon.HassModel; namespace BatteryMonitorManager; @@ -12,10 +12,7 @@ public sealed class BatteryNotificationService( { public void NotifyLowBattery(IReadOnlyList lowBatteryDevices) { - if (lowBatteryDevices.Count == 0) - { - return; - } + if (lowBatteryDevices.Count == 0) return; var message = BuildNotificationMessage(lowBatteryDevices); @@ -30,11 +27,9 @@ public sealed class BatteryNotificationService( }); if (logger.IsEnabled(LogLevel.Information)) - { logger.LogInformation( "Sent low battery notification for {Count} device(s)", lowBatteryDevices.Count); - } } public void DismissNotification() @@ -57,10 +52,8 @@ 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(); } -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs index 8819e9a..0a6f644 100644 --- a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs +++ b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs @@ -1,10 +1,10 @@ using System.Globalization; using System.Text.Json; +using BatteryMonitor.Models; +using BatteryMonitorManager.Interface; using Microsoft.Extensions.Logging; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using BatteryMonitor.Models; -using BatteryMonitorManager.Interface; namespace BatteryMonitorManager; @@ -24,11 +24,9 @@ public sealed class BatterySensorDiscoveryService( .ToList(); if (logger.IsEnabled(LogLevel.Information)) - { logger.LogInformation( "Battery check: found {Count} sensors below {Threshold}%", lowBatterySensors.Count, thresholdPercent); - } return lowBatterySensors!; } @@ -36,9 +34,7 @@ public sealed class BatterySensorDiscoveryService( internal static bool IsBatterySensor(Entity entity) { if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase)) - { return false; - } var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class"); @@ -60,9 +56,8 @@ public sealed class BatterySensorDiscoveryService( if (state is null or "unavailable" or "unknown") { if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null"); - } + logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, + state ?? "null"); return null; } @@ -70,17 +65,13 @@ public sealed class BatterySensorDiscoveryService( if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel)) { if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state); - } + logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, + state); return null; } - if (batteryLevel >= thresholdPercent) - { - return null; - } + if (batteryLevel >= thresholdPercent) return null; var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId; @@ -95,13 +86,10 @@ 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; } -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs index 0b6ff0d..54caf3b 100644 --- a/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs +++ b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs @@ -7,4 +7,4 @@ public interface IBatteryNotificationService void NotifyLowBattery(IReadOnlyList lowBatteryDevices); void DismissNotification(); -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs index 66e1f60..af41652 100644 --- a/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs +++ b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs @@ -5,4 +5,4 @@ namespace BatteryMonitorManager.Interface; public interface IBatterySensorDiscoveryService { IReadOnlyList DiscoverLowBatterySensors(int thresholdPercent); -} +} \ No newline at end of file diff --git a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs index 3072422..34d00d4 100644 --- a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs +++ b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs @@ -9,4 +9,4 @@ public sealed class BatteryMonitorOptions public bool Enabled { get; init; } public int BatteryThresholdPercent { get; init; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent; -} +} \ No newline at end of file diff --git a/BatteryMonitor.Models/BatteryMonitorConsts.cs b/BatteryMonitor.Models/BatteryMonitorConsts.cs index 0fb47e4..3eb4a65 100644 --- a/BatteryMonitor.Models/BatteryMonitorConsts.cs +++ b/BatteryMonitor.Models/BatteryMonitorConsts.cs @@ -32,4 +32,4 @@ public static class BatteryMonitorConsts "oneplus", "ipad" ]; -} +} \ No newline at end of file diff --git a/BatteryMonitor.Models/BatterySensorInfo.cs b/BatteryMonitor.Models/BatterySensorInfo.cs index fede27b..062f353 100644 --- a/BatteryMonitor.Models/BatterySensorInfo.cs +++ b/BatteryMonitor.Models/BatterySensorInfo.cs @@ -7,4 +7,4 @@ public sealed class BatterySensorInfo public required string FriendlyName { get; init; } public required double BatteryLevel { get; init; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs index ed12815..e20a70c 100644 --- a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs @@ -1,8 +1,8 @@ using BoilerMonitor.Models.Enums; +using BoilerMonitorManager; using FluentAssertions; using Microsoft.Extensions.Logging; using Moq; -using BoilerMonitorManager; namespace BoilerMonitor.Manager.Tests; @@ -10,84 +10,11 @@ public class BoilerControlServiceTests { private readonly Mock> _loggerMock = new(); - private BoilerControlService CreateSut() => new(_loggerMock.Object); - - #region TurnOn scenarios - - [Theory] - [InlineData("off")] - [InlineData("OFF")] - [InlineData("Off")] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - [InlineData("off ")] - [InlineData("unavailable")] - [InlineData("unknown")] - [InlineData("0")] - public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState) + private BoilerControlService CreateSut() { - var result = CreateSut().DetermineAction( - isNowCheap: true, waterReady: false, currentSwitchState: switchState, - budgetExhausted: false, budgetOverride: false); - - result.Should().Be(BoilerAction.TurnOn); + return new BoilerControlService(_loggerMock.Object); } - [Theory] - [InlineData("off", BoilerAction.TurnOn)] - [InlineData(null, BoilerAction.TurnOn)] - [InlineData("unavailable", BoilerAction.TurnOn)] - [InlineData("on", BoilerAction.NoChange)] - [InlineData("On", BoilerAction.NoChange)] - [InlineData("ON", BoilerAction.NoChange)] - public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn( - string? switchState, - BoilerAction expectedAction) - { - var result = CreateSut().DetermineAction( - isNowCheap: true, waterReady: false, currentSwitchState: switchState, - budgetExhausted: true, budgetOverride: true); - - result.Should().Be(expectedAction); - } - - #endregion - - #region TurnOff scenarios - - [Theory] - [InlineData("on")] - [InlineData("ON")] - [InlineData("On")] - [InlineData("oN")] - public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState) - { - var result = CreateSut().DetermineAction( - isNowCheap: false, waterReady: false, currentSwitchState: switchState, - budgetExhausted: false, budgetOverride: false); - - result.Should().Be(BoilerAction.TurnOff); - } - - [Theory] - [InlineData(true, false, false)] // water ready - [InlineData(false, true, false)] // budget exhausted, no override - [InlineData(true, true, true)] // water ready wins over the budget override - public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff( - bool waterReady, - bool budgetExhausted, - bool budgetOverride) - { - var result = CreateSut().DetermineAction( - isNowCheap: true, waterReady: waterReady, currentSwitchState: "on", - budgetExhausted: budgetExhausted, budgetOverride: budgetOverride); - - result.Should().Be(BoilerAction.TurnOff); - } - - #endregion - #region NoChange scenarios [Theory] @@ -115,11 +42,87 @@ public class BoilerControlServiceTests #endregion + #region TurnOn scenarios + + [Theory] + [InlineData("off")] + [InlineData("OFF")] + [InlineData("Off")] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("off ")] + [InlineData("unavailable")] + [InlineData("unknown")] + [InlineData("0")] + public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState) + { + var result = CreateSut().DetermineAction( + true, false, switchState, + false, false); + + result.Should().Be(BoilerAction.TurnOn); + } + + [Theory] + [InlineData("off", BoilerAction.TurnOn)] + [InlineData(null, BoilerAction.TurnOn)] + [InlineData("unavailable", BoilerAction.TurnOn)] + [InlineData("on", BoilerAction.NoChange)] + [InlineData("On", BoilerAction.NoChange)] + [InlineData("ON", BoilerAction.NoChange)] + public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn( + string? switchState, + BoilerAction expectedAction) + { + var result = CreateSut().DetermineAction( + true, false, switchState, + true, true); + + result.Should().Be(expectedAction); + } + + #endregion + + #region TurnOff scenarios + + [Theory] + [InlineData("on")] + [InlineData("ON")] + [InlineData("On")] + [InlineData("oN")] + public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState) + { + var result = CreateSut().DetermineAction( + false, false, switchState, + false, false); + + result.Should().Be(BoilerAction.TurnOff); + } + + [Theory] + [InlineData(true, false, false)] // water ready + [InlineData(false, true, false)] // budget exhausted, no override + [InlineData(true, true, true)] // water ready wins over the budget override + public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff( + bool waterReady, + bool budgetExhausted, + bool budgetOverride) + { + var result = CreateSut().DetermineAction( + true, waterReady, "on", + budgetExhausted, budgetOverride); + + result.Should().Be(BoilerAction.TurnOff); + } + + #endregion + #region Comprehensive truth tables /// - /// 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). + /// 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() { @@ -151,14 +154,14 @@ public class BoilerControlServiceTests BoilerAction expectedAction) { var result = CreateSut().DetermineAction( - isNowCheap, waterReady, currentSwitchState: "on", budgetExhausted, budgetOverride); + isNowCheap, waterReady, "on", budgetExhausted, budgetOverride); result.Should().Be(expectedAction); } /// - /// 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). + /// 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() { @@ -190,10 +193,10 @@ public class BoilerControlServiceTests BoilerAction expectedAction) { var result = CreateSut().DetermineAction( - isNowCheap, waterReady, currentSwitchState: "off", budgetExhausted, budgetOverride); + isNowCheap, waterReady, "off", budgetExhausted, budgetOverride); result.Should().Be(expectedAction); } #endregion -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj index 0d523c5..9a2365f 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj +++ b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj @@ -1,38 +1,38 @@ - - net10.0 - enable - enable - false - + + net10.0 + enable + enable + false + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + - - - + + + - - - - + + + + diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs index 45b4c9a..8982bf8 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs @@ -50,10 +50,10 @@ public class BoilerMonitorConfigTests bool expected) { var config = BoilerMonitorTestData.CreateConfig( - boilerPowerEntityId: powerEntityId, - boilerSwitchEntityId: switchEntityId, - pollIntervalSeconds: pollIntervalSeconds, - heatingPowerThresholdWatts: heatingPowerThresholdWatts); + powerEntityId, + switchEntityId, + pollIntervalSeconds, + heatingPowerThresholdWatts); config.IsFullyConfigured.Should().Be(expected, scenario); } @@ -62,9 +62,9 @@ public class BoilerMonitorConfigTests public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding() { var config = BoilerMonitorTestData.CreateConfig( - boilerPowerEntityId: " sensor.sonoff_1002230e32_power ", - boilerSwitchEntityId: "SWITCH.SONOFF_1002230E32"); + " sensor.sonoff_1002230e32_power ", + "SWITCH.SONOFF_1002230E32"); config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content"); } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs index 4898af6..50635fd 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs @@ -47,10 +47,13 @@ public class BoilerMonitorEntityServiceTests .Returns(Task.CompletedTask); } - private BoilerMonitorEntityService CreateSut() => new( - _entityManagerMock.Object, - _haContextMock.Object, - _loggerMock.Object); + private BoilerMonitorEntityService CreateSut() + { + return new BoilerMonitorEntityService( + _entityManagerMock.Object, + _haContextMock.Object, + _loggerMock.Object); + } #region ReadPersistedState @@ -61,7 +64,7 @@ public class BoilerMonitorEntityServiceTests TimeSpan? expectedRunTime) { _haContextMock.SetupEntityStates( - BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: runtimeState, sessionCount: "2")); + BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2")); var result = CreateSut().ReadPersistedState(); @@ -83,7 +86,7 @@ public class BoilerMonitorEntityServiceTests int? expectedSessionCount) { _haContextMock.SetupEntityStates( - BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: "3600", sessionCount: sessionCountState)); + BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState)); var result = CreateSut().ReadPersistedState(); @@ -102,7 +105,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues() { _haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates( - todayRuntime: "7200", sessionCount: "3", skipPriceCap: "ON", budgetOverride: "OFF")); + "7200", "3", "ON", "OFF")); var result = CreateSut().ReadPersistedState(); @@ -135,7 +138,7 @@ public class BoilerMonitorEntityServiceTests public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull() { _haContextMock.SetupEntityStates( - BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: null, sessionCount: null)); + BoilerMonitorTestData.CreatePersistedEntityStates(null, null)); CreateSut().ReadPersistedState().Should().BeNull(); } @@ -242,11 +245,11 @@ public class BoilerMonitorEntityServiceTests public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting() { var context = BoilerMonitorTestData.CreateUpdateContext( - todayRunTime: TimeSpan.FromSeconds(3723.9), - remainingTime: TimeSpan.FromSeconds(42.9), - budgetPercentage: 150.0, - budgetExhausted: true, - sessionCount: 4, + TimeSpan.FromSeconds(3723.9), + TimeSpan.FromSeconds(42.9), + 150.0, + true, + 4, waterReady: true); await CreateSut().UpdateEntitiesAsync(context); @@ -257,7 +260,8 @@ 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)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), + Times.Exactly(5)); } [Theory] @@ -302,7 +306,7 @@ public class BoilerMonitorEntityServiceTests public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState) { await CreateSut().UpdateEntitiesAsync( - BoilerMonitorTestData.CreateUpdateContext(todayRunTime: TimeSpan.FromSeconds(seconds))); + BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds))); _entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once); } @@ -380,8 +384,8 @@ public class BoilerMonitorEntityServiceTests public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity() { _entityManagerMock - .Setup(em => em.CreateEntityAsync(It.Is( - entity => entity.EntityId == CleanupButtonEntityId))) + .Setup(em => + em.CreateEntityAsync(It.Is(entity => entity.EntityId == CleanupButtonEntityId))) .ThrowsAsync(new InvalidOperationException("MQTT unavailable")); var act = () => CreateSut().CreateEntitiesAsync(); @@ -418,7 +422,8 @@ 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)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), + Times.Exactly(5)); } [Fact] @@ -481,9 +486,7 @@ 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)); @@ -531,7 +534,7 @@ public class BoilerMonitorEntityServiceTests public async Task Operation_WhenCancellationIsAlreadyRequested_ShouldThrowAndNotTouchEntityManager( CancelableOperation operation) { - var canceledToken = new CancellationToken(canceled: true); + var canceledToken = new CancellationToken(true); var sut = CreateSut(); Func act = operation switch { @@ -548,4 +551,4 @@ public class BoilerMonitorEntityServiceTests } #endregion -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs index 1b49c61..aa9d928 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs @@ -1,5 +1,5 @@ -using FluentAssertions; using BoilerMonitorManager.Models; +using FluentAssertions; namespace BoilerMonitor.Manager.Tests; @@ -32,7 +32,7 @@ public class BoilerMonitorOptionsTests [InlineData(true)] public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled) { - var options = BoilerMonitorTestData.CreateOptions(enabled: enabled); + var options = BoilerMonitorTestData.CreateOptions(enabled); options.Enabled.Should().Be(enabled); } @@ -50,10 +50,10 @@ public class BoilerMonitorOptionsTests [Fact] public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently() { - var options = BoilerMonitorTestData.CreateOptions(enabled: false, cleanupEntitiesOnStartup: false); + var options = BoilerMonitorTestData.CreateOptions(false, false); options.Enabled.Should().BeFalse(); options.CleanupEntitiesOnStartup.Should().BeFalse(); BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor"); } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs index 4ab633f..eb4ef83 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs @@ -9,9 +9,9 @@ using static BoilerMonitor.Models.BoilerMonitorConsts; namespace BoilerMonitor.Manager.Tests; /// -/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders, -/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted -/// setup and makes every timestamp/DST assertion independent of the real clock. +/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders, +/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted +/// setup and makes every timestamp/DST assertion independent of the real clock. /// internal static class BoilerMonitorTestData { @@ -21,30 +21,36 @@ internal static class BoilerMonitorTestData /// 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 FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) => - new(utcNow ?? BaseTime); + public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) + { + return new FakeTimeProvider(utcNow ?? BaseTime); + } public static BoilerMonitorConfig CreateConfig( string? boilerPowerEntityId = PowerEntityId, string? boilerSwitchEntityId = SwitchEntityId, int? pollIntervalSeconds = DefaultPollIntervalSeconds, - double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts) => - new() + double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts) + { + return new BoilerMonitorConfig { BoilerPowerEntityId = boilerPowerEntityId, BoilerSwitchEntityId = boilerSwitchEntityId, PollIntervalSeconds = pollIntervalSeconds, HeatingPowerThresholdWatts = heatingPowerThresholdWatts }; + } public static BoilerMonitorOptions CreateOptions( bool enabled = true, - bool cleanupEntitiesOnStartup = true) => - new() + bool cleanupEntitiesOnStartup = true) + { + return new BoilerMonitorOptions { Enabled = enabled, CleanupEntitiesOnStartup = cleanupEntitiesOnStartup }; + } public static BoilerMonitorUpdateContext CreateUpdateContext( TimeSpan? todayRunTime = null, @@ -56,8 +62,9 @@ internal static class BoilerMonitorTestData bool waterReady = false, string? boilerSwitchState = "on", double? boilerPowerWatts = 0.0, - DateTimeOffset? cooldownSince = null) => - new() + DateTimeOffset? cooldownSince = null) + { + return new BoilerMonitorUpdateContext { TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1), RemainingTime = remainingTime ?? TimeSpan.FromHours(1), @@ -68,33 +75,43 @@ internal static class BoilerMonitorTestData WaterReady = waterReady, BoilerSwitchState = boilerSwitchState, BoilerPowerWatts = boilerPowerWatts, - CooldownSince = cooldownSince, + CooldownSince = cooldownSince }; + } /// - /// The four entity states ReadPersistedState reads, with valid defaults. - /// A null value means the entity does not exist in Home Assistant. + /// The four entity states ReadPersistedState reads, with valid defaults. + /// A null value means the entity does not exist in Home Assistant. /// public static Dictionary CreatePersistedEntityStates( string? todayRuntime = "7200", string? sessionCount = "3", string? skipPriceCap = "OFF", - string? budgetOverride = "OFF") => - new() + string? budgetOverride = "OFF") + { + return new Dictionary { [TodayRuntimeEntityId] = todayRuntime, [SessionCountEntityId] = sessionCount, [SkipPriceCapEntityId] = skipPriceCap, [BudgetOverrideEntityId] = budgetOverride }; + } - public static EntityState CreateEntityState(string state) => new() { State = state }; + public static EntityState CreateEntityState(string state) + { + return new EntityState { State = state }; + } - public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary attributes) => - new() { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) }; + public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary attributes) + { + return new EntityState { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) }; + } - public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) => - CreateEntityStateWithAttributes(new Dictionary { ["cooldown_since"] = cooldownSince }); + public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) + { + return CreateEntityStateWithAttributes(new Dictionary { ["cooldown_since"] = cooldownSince }); + } extension(Mock haContextMock) { @@ -107,13 +124,15 @@ internal static class BoilerMonitorTestData } } - public void SetupEntityState(string entityId, EntityState? entityState) => + public void SetupEntityState(string entityId, EntityState? entityState) + { haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); + } } /// - /// Entity-state samples for the today-runtime sensor: valid values with the expected - /// , plus unavailable/negative/overflow values that must be rejected. + /// Entity-state samples for the today-runtime sensor: valid values with the expected + /// , plus unavailable/negative/overflow values that must be rejected. /// public static TheoryData RuntimeStateSamples() { @@ -141,11 +160,10 @@ internal static class BoilerMonitorTestData data.Add("-1", null); data.Add("-0.001", null); return data; - } /// - /// Entity-state samples for the session-count sensor, including the int boundaries. + /// Entity-state samples for the session-count sensor, including the int boundaries. /// public static TheoryData SessionCountStateSamples() { @@ -168,12 +186,11 @@ internal static class BoilerMonitorTestData data.Add("2147483648", null); data.Add("1e3", null); return data; - } /// - /// Water-ready detection samples around the heating threshold, including negative, - /// zero, exact-boundary, huge and NaN readings. + /// Water-ready detection samples around the heating threshold, including negative, + /// zero, exact-boundary, huge and NaN readings. /// public static TheoryData PowerReadingSamples() { @@ -188,11 +205,10 @@ internal static class BoilerMonitorTestData data.Add("maximum", double.MaxValue, false); data.Add("not-a-number", double.NaN, true); return data; - } /// - /// Elapsed-time sweep showing that the water-ready cooldown never expires on its own. + /// Elapsed-time sweep showing that the water-ready cooldown never expires on its own. /// public static TheoryData GeneratedElapsedTimes() { @@ -207,12 +223,11 @@ internal static class BoilerMonitorTestData data.Add(TimeSpan.FromHours(48)); data.Add(TimeSpan.FromHours(168)); return data; - } /// - /// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end - /// timestamps carrying non-zero offsets. + /// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end + /// timestamps carrying non-zero offsets. /// public static TheoryData CooldownRestoreSamples() { @@ -259,9 +274,10 @@ internal static class BoilerMonitorTestData false ); return data; - } - private static DateTimeOffset TodayMidnight() => - new(BaseTime.Date, TimeSpan.Zero); -} + private static DateTimeOffset TodayMidnight() + { + return new DateTimeOffset(BaseTime.Date, TimeSpan.Zero); + } +} \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs index 1ffb881..68940bf 100644 --- a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs @@ -1,9 +1,9 @@ using BoilerMonitor.Models; +using BoilerMonitorManager; using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Time.Testing; using Moq; -using BoilerMonitorManager; namespace BoilerMonitor.Manager.Tests; @@ -16,7 +16,10 @@ public class WaterReadyServiceTests private readonly Mock> _loggerMock = new(); private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider(); - private WaterReadyService CreateSut() => new(_loggerMock.Object, _timeProvider); + private WaterReadyService CreateSut() + { + return new WaterReadyService(_loggerMock.Object, _timeProvider); + } private WaterReadyService CreateSutWithHeatingObserved() { @@ -33,10 +36,7 @@ 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; } @@ -282,7 +282,8 @@ public class WaterReadyServiceTests { var sut = CreateSutWithHeatingObserved(); - var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts, heatingThresholdWatts: heatingThresholdWatts); + var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts, + heatingThresholdWatts: heatingThresholdWatts); result.Should().Be(expected); } @@ -475,4 +476,4 @@ public class WaterReadyServiceTests } #endregion -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/BoilerConfigReader.cs b/BoilerMonitor.Manager/BoilerConfigReader.cs index da40315..16f17f4 100644 --- a/BoilerMonitor.Manager/BoilerConfigReader.cs +++ b/BoilerMonitor.Manager/BoilerConfigReader.cs @@ -14,33 +14,34 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger 0 ? pc : double.MaxValue; - + var priceCap = + double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 + ? pc + : double.MaxValue; + var deadline = DateTime.Today.AddDays(1); var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State; - - if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime)) - { + + if (!string.IsNullOrEmpty(readyByState) && + TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime)) deadline = DateTime.Today.Add(readyByTime); - } var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State; var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase); if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", intervalCount, priceCap, skipPriceCap, deadline); - } + logger.LogDebug( + "Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", + intervalCount, priceCap, skipPriceCap, deadline); var config = new BoilerConfig { @@ -49,7 +50,7 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger logger) : { case (true, false): if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState); - } + logger.LogInformation( + "Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", + currentSwitchState); return BoilerAction.TurnOn; @@ -34,19 +34,17 @@ public sealed class BoilerControlService(ILogger logger) : var reason = GetTurnOffReason(waterReady, effectiveBudgetExhausted); if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState); - } + logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, + currentSwitchState); return BoilerAction.TurnOff; } default: if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", + logger.LogDebug( + "Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted); - } return BoilerAction.NoChange; } @@ -54,13 +52,10 @@ 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"; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj index 2f42023..9d0ff2a 100644 --- a/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj +++ b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj @@ -8,21 +8,21 @@ - - <_Parameter1>BoilerMonitor.Manager.Tests - + + <_Parameter1>BoilerMonitor.Manager.Tests + - - - + + + - - - + + + diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs index 19d3040..3f06b52 100644 --- a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Text.Json; using BoilerMonitor.Models; using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; @@ -33,14 +34,6 @@ public sealed class BoilerMonitorEntityService( AutoManagementEntityId ]; - private static object CreateDeviceBlock() => new - { - identifiers = new[] { DeviceIdentifier }, - name = DeviceName, - model = DeviceName, - manufacturer = DeviceManufacturer - }; - public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -52,9 +45,7 @@ public sealed class BoilerMonitorEntityService( 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) @@ -149,13 +140,13 @@ public sealed class BoilerMonitorEntityService( var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State; var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State; - if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount)) + if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || + !TryParseEntityInt(sessionCountState, out var sessionCount)) { if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", + logger.LogInformation( + "No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", runtimeState, sessionCountState); - } return null; } @@ -168,10 +159,10 @@ 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); - } + logger.LogInformation( + "Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}", + persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, + persisted.BudgetOverrideState); return persisted; } @@ -187,6 +178,51 @@ public sealed class BoilerMonitorEntityService( await UpdateStatusAsync(status).ConfigureAwait(false); } + public DateTimeOffset? ReadPersistedCooldownTimestamp() + { + 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; + + var stringValue = value switch + { + string s => s, + JsonElement { ValueKind: JsonValueKind.String } jsonElement => + jsonElement.GetString(), + _ => null + }; + + if (stringValue is not null && + DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var parsed)) + { + if (logger.IsEnabled(LogLevel.Information)) + logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed); + return parsed; + } + } + catch (Exception ex) + { + logger.LogError(ex, "Error reading persisted cooldown timestamp"); + } + + return null; + } + + private static object CreateDeviceBlock() + { + return new + { + identifiers = new[] { DeviceIdentifier }, + name = DeviceName, + model = DeviceName, + manufacturer = DeviceManufacturer + }; + } + private static bool TryParseEntitySeconds(string? state, out double seconds) { seconds = 0; @@ -194,7 +230,7 @@ public sealed class BoilerMonitorEntityService( && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0; - + return tryParseEntitySeconds; } @@ -205,7 +241,7 @@ public sealed class BoilerMonitorEntityService( && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0; - + return tryParseEntityInt; } @@ -235,7 +271,8 @@ public sealed class BoilerMonitorEntityService( device } }, - new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)") + new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", + "Heating power threshold (watts)") { AdditionalConfig = new { @@ -265,11 +302,13 @@ public sealed class BoilerMonitorEntityService( }, new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime") { - AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device } + AdditionalConfig = new + { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device } }, new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time") { - AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device } + AdditionalConfig = new + { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device } }, new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage") { @@ -401,7 +440,8 @@ public sealed class BoilerMonitorEntityService( private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp) { - await SetEntityStateSafe(TodayRuntimeEntityId, ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityStateSafe(TodayRuntimeEntityId, + ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); await SetEntityAttributesSafe(TodayRuntimeEntityId, new { formatted, @@ -410,10 +450,12 @@ public sealed class BoilerMonitorEntityService( }).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); + await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); await SetEntityAttributesSafe(RemainingTimeEntityId, new { formatted, @@ -426,7 +468,8 @@ public sealed class BoilerMonitorEntityService( 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); + await SetEntityStateSafe(BudgetPercentageEntityId, + ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); await SetEntityAttributesSafe(BudgetPercentageEntityId, new { unit_of_measurement = "%", @@ -442,7 +485,8 @@ public sealed class BoilerMonitorEntityService( private async Task UpdateSessionCountAsync(int sessionCount, string timestamp) { - await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); await SetEntityAttributesSafe(SessionCountEntityId, new { friendly_name = "Heating sessions today", @@ -450,57 +494,13 @@ public sealed class BoilerMonitorEntityService( }).ConfigureAwait(false); } - public DateTimeOffset? ReadPersistedCooldownTimestamp() - { - 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; - } - - var stringValue = value switch - { - string s => s, - System.Text.Json.JsonElement { ValueKind: System.Text.Json.JsonValueKind.String } jsonElement => - jsonElement.GetString(), - _ => null - }; - - if (stringValue is not null && - DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind, out var parsed)) - { - if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed); - } - return parsed; - } - } - catch (Exception ex) - { - logger.LogError(ex, "Error reading persisted cooldown timestamp"); - } - - return null; - } - private async Task SetEntityStateSafe(string entityId, string state) { try { await entityManager.SetEntityState(entityId, state).ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Debug)) - { logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state); - } } catch (Exception ex) { @@ -514,9 +514,7 @@ public sealed class BoilerMonitorEntityService( { await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Debug)) - { logger.LogDebug("Successfully set attributes for {EntityId}", entityId); - } } catch (Exception ex) { @@ -528,7 +526,7 @@ public sealed class BoilerMonitorEntityService( { var totalHours = (int)ts.TotalHours; var minutes = ts.Minutes; - + return $"{totalHours}h {minutes}m"; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/BoilerMonitorInit.cs b/BoilerMonitor.Manager/BoilerMonitorInit.cs index 9d89bab..04bf3ff 100644 --- a/BoilerMonitor.Manager/BoilerMonitorInit.cs +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -18,19 +18,19 @@ namespace BoilerMonitorManager; [NetDaemonApp] public sealed class BoilerMonitorInit { - private readonly ILogger _logger; - private readonly IHaContext _haContext; - private readonly IScheduler _scheduler; - private readonly IMqttEntityManager _mqttEntityManager; private readonly IBoilerControlService _boilerControlService; - private readonly IBoilerRunTimeTracker _tracker; private readonly IBoilerMonitorEntityService _entityService; - private readonly IWaterReadyService _waterReadyService; + private readonly IHaContext _haContext; + private readonly ILogger _logger; + private readonly IMqttEntityManager _mqttEntityManager; private readonly BoilerMonitorOptions _options; + private readonly IScheduler _scheduler; private readonly TimeProvider _timeProvider; - private bool _lastWaterReady; + private readonly IBoilerRunTimeTracker _tracker; + private readonly IWaterReadyService _waterReadyService; private volatile bool _cleanedUp; + private bool _lastWaterReady; private DateTimeOffset? _lastWaterReadyNotificationSentAt; public BoilerMonitorInit( @@ -55,7 +55,7 @@ public sealed class BoilerMonitorInit waterReadyService, options, timeProvider, - startBackgroundScheduling: true) + true) { } @@ -83,10 +83,7 @@ public sealed class BoilerMonitorInit _options = options.Value; _timeProvider = timeProvider; - if (startBackgroundScheduling) - { - _ = InitializeAndScheduleAsync(); - } + if (startBackgroundScheduling) _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() @@ -133,17 +130,13 @@ 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}", + _logger.LogInformation( + "BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", persisted.AccumulatedRunTime, persisted.SessionCount); - } } else { @@ -174,11 +167,11 @@ public sealed class BoilerMonitorInit var nextPollTime = now.Add(delayUntilNext); if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime); - } + _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", + DefaultPollIntervalSeconds, nextPollTime); - _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync()); + _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, + () => _ = PollAndUpdateAsync()); } private void ScheduleMidnightReset() @@ -207,10 +200,7 @@ public sealed class BoilerMonitorInit try { var switchState = _haContext.GetState(SkipPriceCapEntityId); - if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) - { - return; - } + if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return; _haContext.CallService("notify", "mobile_app_marius_phone", null, new { @@ -232,10 +222,7 @@ public sealed class BoilerMonitorInit skipPriceCapSwitch.StateChanges() .Subscribe(e => { - if (e.Old?.State == e.New?.State) - { - return; - } + if (e.Old?.State == e.New?.State) return; _logger.LogInformation("Skip price cap switch changed, triggering poll"); _ = PollAndUpdateAsync(); @@ -248,10 +235,7 @@ public sealed class BoilerMonitorInit autoManagementSwitch.StateChanges() .Subscribe(e => { - if (e.Old?.State == e.New?.State) - { - return; - } + if (e.Old?.State == e.New?.State) return; _logger.LogInformation("Automatic boiler control switch changed, triggering poll"); _ = PollAndUpdateAsync(); @@ -264,15 +248,9 @@ public sealed class BoilerMonitorInit showerStateSensor.StateChanges() .Subscribe(e => { - if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) - { - return; - } + 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(); @@ -312,9 +290,7 @@ public sealed class BoilerMonitorInit try { if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state); - } await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false); } catch (Exception e) @@ -344,9 +320,7 @@ public sealed class BoilerMonitorInit try { if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state); - } await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false); } catch (Exception e) @@ -385,22 +359,21 @@ 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", + _logger.LogWarning( + "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; + 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"); @@ -413,7 +386,8 @@ public sealed class BoilerMonitorInit var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0; - var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value); + var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, + config.HeatingPowerThresholdWatts!.Value); if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown()) { @@ -425,16 +399,14 @@ public sealed class BoilerMonitorInit _lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow(); _logger.LogInformation("Water ready notification sent"); } + _lastWaterReady = waterReady; var snapshot = _tracker.GetSnapshot(); 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 @@ -452,21 +424,16 @@ public sealed class BoilerMonitorInit budgetOverride); var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State; - var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase); + var autoManagementEnabled = + !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase); if (autoManagementEnabled) - { ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!); - } else if (boilerAction is not BoilerAction.NoChange) - { if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation( "Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", boilerAction); - } - } var context = new BoilerMonitorUpdateContext { @@ -479,16 +446,15 @@ public sealed class BoilerMonitorInit WaterReady = waterReady, BoilerSwitchState = boilerSwitchState, BoilerPowerWatts = boilerPowerWatts, - CooldownSince = _waterReadyService.WaterReadySince, + CooldownSince = _waterReadyService.WaterReadySince }; await _entityService.UpdateEntitiesAsync(context); if (_logger.IsEnabled(LogLevel.Debug)) - { - _logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", + _logger.LogDebug( + "Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage); - } } catch (Exception ex) { @@ -522,22 +488,18 @@ 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) + if (!string.IsNullOrWhiteSpace(pollIntervalState) + && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0) - { pollInterval = (int)pollIntervalValue; - } double? heatingThreshold = null; var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State; - - if (!string.IsNullOrWhiteSpace(thresholdState) - && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) + + if (!string.IsNullOrWhiteSpace(thresholdState) + && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0) - { heatingThreshold = thresholdValue; - } return new BoilerMonitorConfig { @@ -551,26 +513,19 @@ public sealed class BoilerMonitorInit private double? ReadSensorDouble(string entityId) { 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 { if (attributes.TryGetValue(attributeName, out var value)) - { return value switch { bool b => b, @@ -581,7 +536,6 @@ public sealed class BoilerMonitorInit bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed, _ => false }; - } } catch { @@ -593,13 +547,9 @@ 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 8e5019d..4014d63 100644 --- a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs +++ b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs @@ -14,10 +14,7 @@ public static class BoilerMonitorServiceRegistration .GetSection(BoilerMonitorOptions.SectionName) .Get() ?? new BoilerMonitorOptions(); - if (!options.Enabled) - { - return services; - } + if (!options.Enabled) return services; services .AddNetDaemonApp() @@ -28,4 +25,4 @@ public static class BoilerMonitorServiceRegistration return services; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs index f53311f..820f908 100644 --- a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs +++ b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs @@ -7,7 +7,6 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker { public void RecordPollResult() { - } public RunTimeSnapshot GetSnapshot() @@ -21,11 +20,9 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker public void Reset() { - } public void RestoreFromSnapshot() { - } } \ No newline at end of file diff --git a/BoilerMonitor.Manager/Interface/IBoilerControlService.cs b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs index e8c5e2a..685942a 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerControlService.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs @@ -10,4 +10,4 @@ public interface IBoilerControlService string? currentSwitchState, bool budgetExhausted, bool budgetOverride); -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs index d52ba22..48a7f74 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs @@ -12,4 +12,4 @@ public interface IBoilerMonitorEntityService Task SetStatusAsync(string status); PersistedBoilerState? ReadPersistedState(); DateTimeOffset? ReadPersistedCooldownTimestamp(); -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs index 4c4384a..f71ff71 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs @@ -8,4 +8,4 @@ public interface IBoilerRunTimeTracker RunTimeSnapshot GetSnapshot(); void Reset(); void RestoreFromSnapshot(); -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Interface/IWaterReadyService.cs b/BoilerMonitor.Manager/Interface/IWaterReadyService.cs index 11f93ed..44769cf 100644 --- a/BoilerMonitor.Manager/Interface/IWaterReadyService.cs +++ b/BoilerMonitor.Manager/Interface/IWaterReadyService.cs @@ -2,11 +2,11 @@ namespace BoilerMonitorManager.Interface; public interface IWaterReadyService { - bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts); bool IsInCooldown { get; } DateTimeOffset? WaterReadySince { get; } + bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts); void NotifyTurnedOn(); void RecordHeatingObserved(); void ResetCooldown(); void RestoreCooldownState(DateTimeOffset waterReadySince); -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs b/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs index aa1ff0c..cc388ab 100644 --- a/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs +++ b/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs @@ -12,4 +12,4 @@ public record BoilerMonitorConfig !string.IsNullOrWhiteSpace(BoilerSwitchEntityId) && PollIntervalSeconds is > 0 && HeatingPowerThresholdWatts is > 0; -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs b/BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs index 556d9af..55df8b7 100644 --- a/BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs +++ b/BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs @@ -7,8 +7,8 @@ public sealed class BoilerMonitorOptions public bool Enabled { get; init; } = true; /// - /// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup. - /// Manual cleanup (e.g. HA button) is not affected. + /// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup. + /// Manual cleanup (e.g. HA button) is not affected. /// public bool CleanupEntitiesOnStartup { get; init; } = true; -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs index f055d15..6f8d628 100644 --- a/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs +++ b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs @@ -12,4 +12,4 @@ public record BoilerMonitorUpdateContext public required string? BoilerSwitchState { get; init; } public required double? BoilerPowerWatts { get; init; } public required DateTimeOffset? CooldownSince { get; init; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Models/PersistedBoilerState.cs b/BoilerMonitor.Manager/Models/PersistedBoilerState.cs index 58d563c..5606500 100644 --- a/BoilerMonitor.Manager/Models/PersistedBoilerState.cs +++ b/BoilerMonitor.Manager/Models/PersistedBoilerState.cs @@ -6,4 +6,4 @@ public record PersistedBoilerState public required int SessionCount { get; init; } public required string? SkipPriceCapState { get; init; } public required string? BudgetOverrideState { get; init; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs b/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs index 3be74b3..1075c40 100644 --- a/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs +++ b/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs @@ -4,4 +4,4 @@ public record RunTimeSnapshot { public required TimeSpan AccumulatedRunTime { get; init; } public required int SessionCount { get; init; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Manager/WaterReadyService.cs b/BoilerMonitor.Manager/WaterReadyService.cs index c3ac4d9..6090fb6 100644 --- a/BoilerMonitor.Manager/WaterReadyService.cs +++ b/BoilerMonitor.Manager/WaterReadyService.cs @@ -8,9 +8,9 @@ public sealed class WaterReadyService(ILogger logger, TimePro { private const string SwitchOnState = "on"; private readonly Lock _lock = new(); - private DateTimeOffset? _waterReadySince; - private bool _hasObservedHeating; private int _consecutiveBelowThresholdCount; + private bool _hasObservedHeating; + private DateTimeOffset? _waterReadySince; public bool IsInCooldown { @@ -41,32 +41,24 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (IsWithinCooldownPeriod()) { if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince); - } + logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", + _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) { if (!_hasObservedHeating) { if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value); - } - + logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", + powerWatts.Value); + return false; } @@ -81,20 +73,20 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired) { if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", - _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value); - } - + logger.LogDebug( + "Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", + _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, + powerWatts.Value); + return false; } _waterReadySince ??= timeProvider.GetUtcNow(); if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", _consecutiveBelowThresholdCount); - } + logger.LogInformation( + "Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", + _consecutiveBelowThresholdCount); return true; } @@ -108,17 +100,15 @@ public sealed class WaterReadyService(ILogger logger, TimePro _consecutiveBelowThresholdCount = 0; } - logger.LogDebug("Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled"); + logger.LogDebug( + "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; } @@ -145,20 +135,20 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (waterReadySince < todayMidnightUtc) { if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince); - } - + logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", + waterReadySince); + return; } _waterReadySince = waterReadySince; if (logger.IsEnabled(LogLevel.Information)) - { logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince); - } } } - private bool IsWithinCooldownPeriod() => _waterReadySince is not null; -} + private bool IsWithinCooldownPeriod() + { + return _waterReadySince is not null; + } +} \ No newline at end of file diff --git a/BoilerMonitor.Models/BoilerConfig.cs b/BoilerMonitor.Models/BoilerConfig.cs index 03d9966..62d37b3 100644 --- a/BoilerMonitor.Models/BoilerConfig.cs +++ b/BoilerMonitor.Models/BoilerConfig.cs @@ -1,7 +1,7 @@ namespace BoilerMonitor.Models; /// -/// Boiler scheduling configuration read from Home Assistant entity state. +/// Boiler scheduling configuration read from Home Assistant entity state. /// public sealed class BoilerConfig { @@ -12,4 +12,4 @@ public sealed class BoilerConfig public required DateTime Deadline { get; init; } public required bool SkipPriceCap { get; init; } -} +} \ No newline at end of file diff --git a/BoilerMonitor.Models/BoilerMonitor.Models.csproj b/BoilerMonitor.Models/BoilerMonitor.Models.csproj index 119fc66..cba5a74 100644 --- a/BoilerMonitor.Models/BoilerMonitor.Models.csproj +++ b/BoilerMonitor.Models/BoilerMonitor.Models.csproj @@ -8,11 +8,11 @@ - + - + diff --git a/BoilerMonitor.Models/BoilerMonitorConsts.cs b/BoilerMonitor.Models/BoilerMonitorConsts.cs index d0cf828..0cfd731 100644 --- a/BoilerMonitor.Models/BoilerMonitorConsts.cs +++ b/BoilerMonitor.Models/BoilerMonitorConsts.cs @@ -5,27 +5,21 @@ public static class BoilerMonitorConsts public const int DefaultPollIntervalSeconds = 30; /// - /// Power threshold in watts below which the boiler is considered to have finished heating (water ready). - /// Also used as the default threshold above which the boiler is considered actively heating. + /// Power threshold in watts below which the boiler is considered to have finished heating (water ready). + /// Also used as the default threshold above which the boiler is considered actively heating. /// public const double DefaultHeatingPowerThresholdWatts = 5.0; /// - /// Number of consecutive below-threshold power readings required before - /// declaring water as ready. Prevents false positives from transient sensor glitches. - /// At 30s poll interval, a value of 2 means 60s of confirmed low power. + /// Number of consecutive below-threshold power readings required before + /// declaring water as ready. Prevents false positives from transient sensor glitches. + /// At 30s poll interval, a value of 2 means 60s of confirmed low power. /// public const int ConsecutiveReadingsRequired = 2; public const string ShowerStateEntityId = "sensor.showermonitor_state"; public const string ShowerActiveState = "Active"; - /// - /// Minimum interval between "hot water is ready" push notifications. - /// Prevents notification spam when power readings fluctuate around the heating threshold. - /// - public static readonly TimeSpan WaterReadyNotificationCooldown = TimeSpan.FromHours(1); - public const int MinPollIntervalSeconds = 5; public const int MaxPollIntervalSeconds = 300; public const int PollIntervalStepSeconds = 5; @@ -52,8 +46,8 @@ public static class BoilerMonitorConsts public const string BudgetOverrideEntityId = "switch.boilermonitor_budget_override"; /// - /// When on, the daemon may call the configured boiler switch per price/budget/water-ready logic. - /// When off, monitoring continues but automatic turn_on/turn_off calls are suppressed (manual control). + /// When on, the daemon may call the configured boiler switch per price/budget/water-ready logic. + /// When off, monitoring continues but automatic turn_on/turn_off calls are suppressed (manual control). /// public const string AutoManagementEntityId = "switch.boilermonitor_auto_management"; @@ -73,4 +67,10 @@ public static class BoilerMonitorConsts public const string DeviceIdentifier = "boiler_monitor"; public const string DeviceName = "Boiler Monitor"; public const string DeviceManufacturer = "HomeAssistant App Daemon"; -} + + /// + /// Minimum interval between "hot water is ready" push notifications. + /// Prevents notification spam when power readings fluctuate around the heating threshold. + /// + public static readonly TimeSpan WaterReadyNotificationCooldown = TimeSpan.FromHours(1); +} \ No newline at end of file diff --git a/BoilerMonitor.Models/BoilerMonitorEntity.cs b/BoilerMonitor.Models/BoilerMonitorEntity.cs index f36d91d..8b69b07 100644 --- a/BoilerMonitor.Models/BoilerMonitorEntity.cs +++ b/BoilerMonitor.Models/BoilerMonitorEntity.cs @@ -5,10 +5,6 @@ namespace BoilerMonitor.Models; public class BoilerMonitorEntity : EntityCreateModel { - private string Domain { get; } - private string Identifier { get; } - private string Name { get; } - public BoilerMonitorEntity(string domain, string identifier, string name) { Domain = domain; @@ -22,4 +18,8 @@ public class BoilerMonitorEntity : EntityCreateModel Name = Name }; } -} + + private string Domain { get; } + private string Identifier { get; } + private string Name { get; } +} \ No newline at end of file diff --git a/BoilerMonitor.Models/Enums/BoilerAction.cs b/BoilerMonitor.Models/Enums/BoilerAction.cs index 157caf0..404f044 100644 --- a/BoilerMonitor.Models/Enums/BoilerAction.cs +++ b/BoilerMonitor.Models/Enums/BoilerAction.cs @@ -5,4 +5,4 @@ public enum BoilerAction NoChange, TurnOn, TurnOff -} +} \ No newline at end of file diff --git a/BoilerMonitor.Models/IBoilerConfigReader.cs b/BoilerMonitor.Models/IBoilerConfigReader.cs index b917d97..6d2ec48 100644 --- a/BoilerMonitor.Models/IBoilerConfigReader.cs +++ b/BoilerMonitor.Models/IBoilerConfigReader.cs @@ -1,9 +1,9 @@ namespace BoilerMonitor.Models; /// -/// Reads the boiler scheduling configuration from Home Assistant entity state. +/// Reads the boiler scheduling configuration from Home Assistant entity state. /// public interface IBoilerConfigReader { BoilerConfig ReadConfig(); -} +} \ No newline at end of file diff --git a/HomeAssistant.Entities/EntityManager.cs b/HomeAssistant.Entities/EntityManager.cs index 287d677..a7e60df 100644 --- a/HomeAssistant.Entities/EntityManager.cs +++ b/HomeAssistant.Entities/EntityManager.cs @@ -23,9 +23,7 @@ public class EntityManager( public async Task CreateEntityAsync(EntityCreateModel createModel) { if (createModel.EntityId != null) - { await entityManager.CreateAsync(createModel.EntityId, createModel.Options, createModel.AdditionalConfig); - } } public async Task SetEntityState(string entityId, string state) @@ -53,14 +51,12 @@ 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; @@ -70,15 +66,13 @@ public class EntityManager( { 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)); - } var domain = entityId[..separatorIndex]; var objectId = entityId[(separatorIndex + 1)..]; return $"{discoveryPrefix}/{domain}/{objectId}"; } -} +} \ No newline at end of file diff --git a/HomeAssistant.Entities/HomeAssistant.Entities.csproj b/HomeAssistant.Entities/HomeAssistant.Entities.csproj index f584221..de0ec80 100644 --- a/HomeAssistant.Entities/HomeAssistant.Entities.csproj +++ b/HomeAssistant.Entities/HomeAssistant.Entities.csproj @@ -7,18 +7,18 @@ - - - - - - - - + + + + + + + + - - + + diff --git a/HomeAssistant.Models/EntityCreateModel.cs b/HomeAssistant.Models/EntityCreateModel.cs index b27a261..5dca19f 100644 --- a/HomeAssistant.Models/EntityCreateModel.cs +++ b/HomeAssistant.Models/EntityCreateModel.cs @@ -4,7 +4,7 @@ namespace HomeAssistant.Models; public class EntityCreateModel { - public string? EntityId { get; init; } + public string? EntityId { get; protected init; } public EntityCreationOptions? Options { get; init; } = new(); public object? AdditionalConfig { get; init; } } \ No newline at end of file diff --git a/HomeAssistant.Models/HomeAssistant.Models.csproj b/HomeAssistant.Models/HomeAssistant.Models.csproj index 29d04a7..ffaef7a 100644 --- a/HomeAssistant.Models/HomeAssistant.Models.csproj +++ b/HomeAssistant.Models/HomeAssistant.Models.csproj @@ -7,7 +7,7 @@ - + diff --git a/HomeAssistant.Server/CustomLoggingProvider.cs b/HomeAssistant.Server/CustomLoggingProvider.cs index 9704078..4c52623 100644 --- a/HomeAssistant.Server/CustomLoggingProvider.cs +++ b/HomeAssistant.Server/CustomLoggingProvider.cs @@ -11,7 +11,8 @@ public static class CustomLoggingProvider { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") - .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true) + .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", + true) .Build(); var logger = new LoggerConfiguration() @@ -20,4 +21,4 @@ public static class CustomLoggingProvider return builder.UseSerilog(logger); } -} +} \ No newline at end of file diff --git a/HomeAssistant.Server/HomeAssistant.Server.csproj b/HomeAssistant.Server/HomeAssistant.Server.csproj index 5fb99f8..625c03b 100644 --- a/HomeAssistant.Server/HomeAssistant.Server.csproj +++ b/HomeAssistant.Server/HomeAssistant.Server.csproj @@ -21,11 +21,11 @@ PreserveNewest - Always + Always - Always - Never + Always + Never Always @@ -33,35 +33,35 @@ - + - - - - - - - - + + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/HomeAssistant.Server/MqttRecreateApp.cs b/HomeAssistant.Server/MqttRecreateApp.cs index 28eb57f..dbd468b 100644 --- a/HomeAssistant.Server/MqttRecreateApp.cs +++ b/HomeAssistant.Server/MqttRecreateApp.cs @@ -25,9 +25,9 @@ public sealed class MqttRecreateApp private static readonly string[] AppDaemonIdentifiers = ["appdaemon"]; private readonly IHaContext _haContext; + private readonly ILogger _logger; private readonly IMqttEntityManager _mqttEntityManager; private readonly IServiceProvider _serviceProvider; - private readonly ILogger _logger; public MqttRecreateApp( IHaContext haContext, @@ -69,9 +69,7 @@ public sealed class MqttRecreateApp }).ConfigureAwait(false); if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId); - } var button = new Entity(_haContext, RecreateButtonEntityId); button.StateChanges() @@ -204,21 +202,17 @@ public sealed class MqttRecreateApp 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 }; - } } catch (Exception ex) { if (_logger.IsEnabled(LogLevel.Debug)) - { _logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId); - } } return null; diff --git a/HomeAssistant.Server/README.md b/HomeAssistant.Server/README.md index 5ca70e2..97902c5 100644 --- a/HomeAssistant.Server/README.md +++ b/HomeAssistant.Server/README.md @@ -1,21 +1,28 @@ # Project template for binary deploy + This is the project template for binary deploy. This allows you to build a binary package and deploy it to NetDaemon. This is generated using NetDaemon runtime version 5 and .NET 9. ## Getting started -Please see [netdaemon.xyz](https://netdaemon.xyz/docs) more information about getting starting developing apps for Home Assistant using NetDaemon. + +Please see [netdaemon.xyz](https://netdaemon.xyz/docs) more information about getting starting developing apps for Home +Assistant using NetDaemon. Please add code generation features in `program.cs` when using code generation features by removing comments! ## Use the code generator + See https://netdaemon.xyz/docs/hass_model/hass_model_codegen ## Issues -- If you have issues or suggestions of improvements to this template, please [add an issue](https://github.com/net-daemon/netdaemon-app-template) -- If you have issues or suggestions of improvements to NetDaemon, please [add an issue](https://github.com/net-daemon/netdaemon/issues) +- If you have issues or suggestions of improvements to this template, + please [add an issue](https://github.com/net-daemon/netdaemon-app-template) +- If you have issues or suggestions of improvements to NetDaemon, + please [add an issue](https://github.com/net-daemon/netdaemon/issues) ## Discuss the NetDaemon -Please [join the Discord server](https://discord.gg/K3xwfcX) to get support or if you want to contribute and help others. +Please [join the Discord server](https://discord.gg/K3xwfcX) to get support or if you want to contribute and help +others. diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index eaed12b..9f67b8b 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -1,84 +1,87 @@ { - "Serilog": { - "MinimumLevel": { - "Default": "Warning" - }, - "WriteTo": [ - { - "Name": "Console" - } - ] + "Serilog": { + "MinimumLevel": { + "Default": "Warning" }, - "NetDaemon": { - "ApplicationConfigurationFolder": "./apps" - }, - "CodeGeneration": { - "Namespace": "HomeAssistantGenerated", - "OutputFile": "HomeAssistantGenerated.cs", - "UseAttributeBaseClasses" : "false" - }, - "NordPool": { - "CleanupEntitiesOnStartup": false - }, - "BoilerMonitor": { - "Enabled": true, - "CleanupEntitiesOnStartup": false - }, - "ShowerMonitor": { - "Enabled": true, - "CleanupEntitiesOnStartup": false, - "BathroomHumidityEntityId": "sensor.bathroom_humidity", - "MainHomeHumidityEntityId": "sensor.main_home_humidity", - "BathroomTemperatureEntityId": "sensor.bathroom_temperature", - "ExhaustFanEntityId": "switch.exhaust_fan", - "PollIntervalSeconds": 5, - "SpikeRateThreshold": 4.0, - "MinDifferentialHumidity": 8.0, - "PeakHumidityThreshold": 58.0, - "ConfirmationWindowMinutes": 2, - "RecoveryDifferentialThreshold": 5.0, - "MaxShowerDurationMinutes": 60, - "FanRunAfterShowerMinutes": 10, - "RateWindowSize": 5 - }, - "LightMonitor": { - "Enabled": true, - "LightEntityId": "light.sonoff_1002214d40", - "SunEntityId": "sun.sun", - "PersonEntityIds": ["person.marius", "person.erika"] - }, - "BatteryMonitor": { - "Enabled": true, - "BatteryThresholdPercent": 5 - }, - "LeakMonitor": { - "Enabled": true, - "SensorEntityIds": [ - "binary_sensor.aquarium_leak_sensor", - "binary_sensor.boiler_moisture" - ], - "NotificationCooldownMinutes": 5 - }, - "PowerMonitor": { - "Enabled": false, - "MainMeterEntityId": "sensor.sonoff_100267d63f_power", - "PollIntervalSeconds": 1, - "SmoothingWindowSize": 10, - "AnomalyThresholdWatts": 500, - "HighPowerThresholdWatts": 6000, - "EnforceLimitEnabled": false, - "PowerLimitWatts": 5500, - "RecoverySeconds": 600, - "LimitCooldownSeconds": 30, - "EnforceSwitchOffEntityIds": [ - "switch.sonoff_1002230e32" - ], - "PauseAndRestoreEntityIds": [ - "switch.boilermonitor_auto_management" - ], - "ExcludedSensorPatterns": [ - "sensor.nordpool_*", - "sensor.powermonitor_*" - ] - } + "WriteTo": [ + { + "Name": "Console" + } + ] + }, + "NetDaemon": { + "ApplicationConfigurationFolder": "./apps" + }, + "CodeGeneration": { + "Namespace": "HomeAssistantGenerated", + "OutputFile": "HomeAssistantGenerated.cs", + "UseAttributeBaseClasses": "false" + }, + "NordPool": { + "CleanupEntitiesOnStartup": false + }, + "BoilerMonitor": { + "Enabled": true, + "CleanupEntitiesOnStartup": false + }, + "ShowerMonitor": { + "Enabled": true, + "CleanupEntitiesOnStartup": false, + "BathroomHumidityEntityId": "sensor.bathroom_humidity", + "MainHomeHumidityEntityId": "sensor.main_home_humidity", + "BathroomTemperatureEntityId": "sensor.bathroom_temperature", + "ExhaustFanEntityId": "switch.exhaust_fan", + "PollIntervalSeconds": 5, + "SpikeRateThreshold": 4.0, + "MinDifferentialHumidity": 8.0, + "PeakHumidityThreshold": 58.0, + "ConfirmationWindowMinutes": 2, + "RecoveryDifferentialThreshold": 5.0, + "MaxShowerDurationMinutes": 60, + "FanRunAfterShowerMinutes": 10, + "RateWindowSize": 5 + }, + "LightMonitor": { + "Enabled": true, + "LightEntityId": "light.sonoff_1002214d40", + "SunEntityId": "sun.sun", + "PersonEntityIds": [ + "person.marius", + "person.erika" + ] + }, + "BatteryMonitor": { + "Enabled": true, + "BatteryThresholdPercent": 5 + }, + "LeakMonitor": { + "Enabled": true, + "SensorEntityIds": [ + "binary_sensor.aquarium_leak_sensor", + "binary_sensor.boiler_moisture" + ], + "NotificationCooldownMinutes": 5 + }, + "PowerMonitor": { + "Enabled": false, + "MainMeterEntityId": "sensor.sonoff_100267d63f_power", + "PollIntervalSeconds": 1, + "SmoothingWindowSize": 10, + "AnomalyThresholdWatts": 500, + "HighPowerThresholdWatts": 6000, + "EnforceLimitEnabled": false, + "PowerLimitWatts": 5500, + "RecoverySeconds": 600, + "LimitCooldownSeconds": 30, + "EnforceSwitchOffEntityIds": [ + "switch.sonoff_1002230e32" + ], + "PauseAndRestoreEntityIds": [ + "switch.boilermonitor_auto_management" + ], + "ExcludedSensorPatterns": [ + "sensor.nordpool_*", + "sensor.powermonitor_*" + ] + } } diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 0a39ace..05809fe 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -1,10 +1,18 @@ using System; using System.Reflection; +using BatteryMonitorManager; +using BatteryMonitorManager.Models; +using BoilerMonitor.Models; +using BoilerMonitorManager; +using BoilerMonitorManager.Models; using HomeAssistant.Entities; using HomeAssistant.Entities.Interfaces; using HomeAssistantGenerated; using HomeAssistantServer; +using LeakMonitorManager; +using LeakMonitorManager.Models; using LightMonitor.Models; +using LightMonitorManager; using Mappings; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -13,19 +21,12 @@ using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.Extensions.Scheduler; using NetDaemon.Extensions.Tts; using NetDaemon.Runtime; -using BoilerMonitorManager; -using BoilerMonitorManager.Models; using NordPoolManager; using NordPoolManager.Models; using PowerMonitorManager; using PowerMonitorManager.Models; using ShowerMonitorManager; using ShowerMonitorManager.Models; -using LightMonitorManager; -using BatteryMonitorManager; -using BatteryMonitorManager.Models; -using LeakMonitorManager; -using LeakMonitorManager.Models; try { @@ -51,7 +52,7 @@ try }) .AddTransient() .AddSingleton(TimeProvider.System) - .AddScoped() + .AddScoped() .Configure(context.Configuration.GetSection(NordPoolOptions.SectionName)) .AddNordPool() .Configure(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) diff --git a/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj b/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj index 3c92fef..ee6eb00 100644 --- a/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj +++ b/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj @@ -1,34 +1,34 @@ - - net10.0 - enable - enable - false - + + net10.0 + enable + enable + false + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - - + + + - - - - + + + + diff --git a/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs index 3306b18..0531597 100644 --- a/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs +++ b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs @@ -1,21 +1,21 @@ using FluentAssertions; +using LeakMonitor.Models; +using LeakMonitorManager; +using LeakMonitorManager.Interface; +using LeakMonitorManager.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LeakMonitor.Models; -using LeakMonitorManager; -using LeakMonitorManager.Interface; -using LeakMonitorManager.Models; namespace LeakMonitor.Manager.Tests; public class LeakMonitorInitTests { private readonly Mock _haContextMock = new(); - private readonly Mock _notificationServiceMock = new(); private readonly Mock> _loggerMock = new(); + private readonly Mock _notificationServiceMock = new(); private readonly LeakMonitorTestData.TrackingObservable _stateChanges = new(); public LeakMonitorInitTests() @@ -145,7 +145,7 @@ public class LeakMonitorInitTests [Fact] public void InitializeAsync_WhenNoSensorsConfigured_ShouldNotSubscribeAndLogWarning() { - var sut = CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [])); + var sut = CreateSut(LeakMonitorTestData.CreateOptions([])); sut.Should().NotBeNull(); _stateChanges.SubscriptionCount.Should().Be(0); @@ -169,7 +169,7 @@ public class LeakMonitorInitTests [MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))] public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId) { - CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [sensorEntityId])); + CreateSut(LeakMonitorTestData.CreateOptions([sensorEntityId])); _stateChanges.SubscriptionCount.Should().Be(1); @@ -186,7 +186,7 @@ public class LeakMonitorInitTests public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors() { CreateSut(LeakMonitorTestData.CreateOptions( - sensorEntityIds: [null!, LeakMonitorTestData.BoilerSensorId])); + [null!, LeakMonitorTestData.BoilerSensorId])); _stateChanges.SubscriptionCount.Should().Be(2); @@ -294,9 +294,7 @@ public class LeakMonitorInitTests _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorTestData.DetectionSequence)) - { _stateChanges.Publish(change); - } _notificationServiceMock.Verify( n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), @@ -352,4 +350,4 @@ public class LeakMonitorInitTests } #endregion -} +} \ No newline at end of file diff --git a/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs b/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs index 6b3a02e..434af6b 100644 --- a/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs +++ b/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs @@ -1,16 +1,16 @@ using System.Text.Json; +using LeakMonitor.Models; +using LeakMonitorManager.Models; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LeakMonitor.Models; -using LeakMonitorManager.Models; namespace LeakMonitor.Manager.Tests; /// -/// Shared, deterministic builders and datasets used by the LeakMonitor tests. -/// Keeping entity/state construction, notification payload capture and generated -/// input rows here means the test classes only describe the scenario under test. +/// Shared, deterministic builders and datasets used by the LeakMonitor tests. +/// Keeping entity/state construction, notification payload capture and generated +/// input rows here means the test classes only describe the scenario under test. /// internal static class LeakMonitorTestData { @@ -23,21 +23,7 @@ internal static class LeakMonitorTestData private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); /// - /// Builds leak monitor options with production-compatible defaults. - /// Pass [] for no sensors; omit the argument for the shared sensor set. - /// - public static LeakMonitorOptions CreateOptions( - IEnumerable? sensorEntityIds = null, - int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes, - bool enabled = true) => new() - { - Enabled = enabled, - SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds], - NotificationCooldownMinutes = notificationCooldownMinutes - }; - - /// - /// Every casing of the "water detected" state, across both configured sensors. + /// Every casing of the "water detected" state, across both configured sensors. /// public static TheoryData WaterDetectedCases { get; } = new() { @@ -49,7 +35,7 @@ internal static class LeakMonitorTestData }; /// - /// Every casing of the "water cleared" state, across both configured sensors. + /// Every casing of the "water cleared" state, across both configured sensors. /// public static TheoryData WaterClearedCases { get; } = new() { @@ -60,8 +46,8 @@ internal static class LeakMonitorTestData }; /// - /// States that must never send or dismiss a leak notification. Covers unavailable, - /// unknown, blank, null and near-miss strings (the comparison is exact apart from casing). + /// States that must never send or dismiss a leak notification. Covers unavailable, + /// unknown, blank, null and near-miss strings (the comparison is exact apart from casing). /// public static TheoryData NonActionableStateCases { get; } = [ @@ -83,8 +69,8 @@ internal static class LeakMonitorTestData ]; /// - /// Blank but non-null sensor ids. Production does not validate ids, so these are - /// subscribed and forwarded verbatim. + /// Blank but non-null sensor ids. Production does not validate ids, so these are + /// subscribed and forwarded verbatim. /// public static TheoryData BlankSensorIds { get; } = [ @@ -94,8 +80,8 @@ internal static class LeakMonitorTestData ]; /// - /// (sensor id, expected notification id) rows for the id sanitising rules: - /// dots become underscores, other characters and blanks are preserved. + /// (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() { @@ -110,9 +96,9 @@ internal static class LeakMonitorTestData }; /// - /// (cooldown minutes, elapsed seconds before the second alert, expected notification count) - /// rows straddling the strict elapsed < cooldown boundary, plus zero, negative - /// and int-max cooldowns. + /// (cooldown minutes, elapsed seconds before the second alert, expected notification count) + /// rows straddling the strict elapsed < cooldown boundary, plus zero, negative + /// and int-max cooldowns. /// public static TheoryData CooldownBoundaryCases { get; } = new() { @@ -130,7 +116,7 @@ internal static class LeakMonitorTestData }; /// - /// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour. + /// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour. /// public static TheoryData RepeatedNotificationCounts { get; } = [ @@ -141,8 +127,8 @@ internal static class LeakMonitorTestData ]; /// - /// A deterministic detection/recovery sequence. The repeated "on" transition is filtered - /// out downstream, so the expected totals are two alerts and two dismissals. + /// A deterministic detection/recovery sequence. The repeated "on" transition is filtered + /// out downstream, so the expected totals are two alerts and two dismissals. /// public static (string? OldState, string? NewState)[] DetectionSequence { get; } = [ @@ -155,30 +141,55 @@ internal static class LeakMonitorTestData ]; /// - /// Builds an , or null when the entity has no state at all. + /// Builds leak monitor options with production-compatible defaults. + /// Pass [] for no sensors; omit the argument for the shared sensor set. /// - private static EntityState? CreateOptionalState(string? state) => - state is null ? null : new EntityState { State = state }; + public static LeakMonitorOptions CreateOptions( + IEnumerable? sensorEntityIds = null, + int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes, + bool enabled = true) + { + return new LeakMonitorOptions + { + Enabled = enabled, + SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds], + NotificationCooldownMinutes = notificationCooldownMinutes + }; + } + + /// + /// Builds an , or null when the entity has no state at all. + /// + private static EntityState? CreateOptionalState(string? state) + { + return state is null ? null : new EntityState { State = state }; + } public static StateChange CreateStateChange( IHaContext haContext, string entityId, string? oldState, - string? newState) => - new(new Entity(haContext, entityId), CreateOptionalState(oldState), CreateOptionalState(newState)); + string? newState) + { + return new StateChange(new Entity(haContext, entityId), CreateOptionalState(oldState), + CreateOptionalState(newState)); + } public static IReadOnlyList CreateStateChangeSequence( IHaContext haContext, string entityId, - params (string? OldState, string? NewState)[] transitions) => - [.. transitions.Select(transition => CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))]; - - /// One captured IHaContext.CallService invocation. - public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data); + params (string? OldState, string? NewState)[] transitions) + { + return + [ + .. transitions.Select(transition => + CreateStateChange(haContext, entityId, transition.OldState, transition.NewState)) + ]; + } /// - /// Wires on the mock and returns the captured calls - /// in invocation order. + /// Wires on the mock and returns the captured calls + /// in invocation order. /// public static List CaptureServiceCalls(Mock haContextMock) { @@ -197,25 +208,40 @@ internal static class LeakMonitorTestData } /// Serialises a captured service-call payload so tests can assert on it. - public static JsonElement SerializePayload(object? data) => JsonSerializer.SerializeToElement(data); + public static JsonElement SerializePayload(object? data) + { + return JsonSerializer.SerializeToElement(data); + } + + /// One captured IHaContext.CallService invocation. + public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data); /// - /// Deterministic clock so cooldown boundaries can be crossed without real waiting. + /// Deterministic clock so cooldown boundaries can be crossed without real waiting. /// public sealed class ManualTimeProvider(DateTimeOffset? start = null) : TimeProvider { private DateTimeOffset _utcNow = start ?? DefaultStart; - public override DateTimeOffset GetUtcNow() => _utcNow; + public override DateTimeOffset GetUtcNow() + { + return _utcNow; + } - public void Advance(TimeSpan duration) => _utcNow += duration; + public void Advance(TimeSpan duration) + { + _utcNow += duration; + } - public void AdvanceSeconds(int seconds) => Advance(TimeSpan.FromSeconds(seconds)); + public void AdvanceSeconds(int seconds) + { + Advance(TimeSpan.FromSeconds(seconds)); + } } /// - /// Observable that records subscriptions and lets tests push state changes through the - /// same pipeline the NetDaemon runtime uses. + /// Observable that records subscriptions and lets tests push state changes through the + /// same pipeline the NetDaemon runtime uses. /// public sealed class TrackingObservable : IObservable { @@ -232,15 +258,15 @@ 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 { - public void Dispose() => observers.Remove(observer); + public void Dispose() + { + observers.Remove(observer); + } } } -} +} \ No newline at end of file diff --git a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs index 9e23fe6..2ce52ae 100644 --- a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs +++ b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs @@ -1,12 +1,12 @@ using FluentAssertions; +using LeakMonitor.Models; +using LeakMonitorManager; +using LeakMonitorManager.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LeakMonitor.Models; -using LeakMonitorManager; -using LeakMonitorManager.Models; namespace LeakMonitor.Manager.Tests; @@ -156,10 +156,7 @@ 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()); @@ -172,10 +169,7 @@ 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)); @@ -220,10 +214,7 @@ 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)); @@ -354,4 +345,4 @@ public class LeakNotificationServiceTests } #endregion -} +} \ No newline at end of file diff --git a/LeakMonitor.Manager/Interface/ILeakNotificationService.cs b/LeakMonitor.Manager/Interface/ILeakNotificationService.cs index 57bdd0c..21c3959 100644 --- a/LeakMonitor.Manager/Interface/ILeakNotificationService.cs +++ b/LeakMonitor.Manager/Interface/ILeakNotificationService.cs @@ -5,4 +5,4 @@ public interface ILeakNotificationService void SendLeakAlert(string sensorEntityId); void DismissLeakAlert(string sensorEntityId); -} +} \ No newline at end of file diff --git a/LeakMonitor.Manager/LeakMonitor.Manager.csproj b/LeakMonitor.Manager/LeakMonitor.Manager.csproj index 17e998d..024228d 100644 --- a/LeakMonitor.Manager/LeakMonitor.Manager.csproj +++ b/LeakMonitor.Manager/LeakMonitor.Manager.csproj @@ -8,20 +8,20 @@ - - <_Parameter1>LeakMonitor.Manager.Tests - + + <_Parameter1>LeakMonitor.Manager.Tests + - - + + - - - + + + diff --git a/LeakMonitor.Manager/LeakMonitorInit.cs b/LeakMonitor.Manager/LeakMonitorInit.cs index 54b1153..b2a5946 100644 --- a/LeakMonitor.Manager/LeakMonitorInit.cs +++ b/LeakMonitor.Manager/LeakMonitorInit.cs @@ -1,11 +1,11 @@ +using LeakMonitor.Models; +using LeakMonitorManager.Interface; +using LeakMonitorManager.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LeakMonitor.Models; -using LeakMonitorManager.Interface; -using LeakMonitorManager.Models; namespace LeakMonitorManager; @@ -13,8 +13,8 @@ namespace LeakMonitorManager; public sealed class LeakMonitorInit { private readonly IHaContext _haContext; - private readonly ILeakNotificationService _notificationService; private readonly ILogger _logger; + private readonly ILeakNotificationService _notificationService; private readonly LeakMonitorOptions _options; public LeakMonitorInit( @@ -38,19 +38,15 @@ public sealed class LeakMonitorInit if (_options.SensorEntityIds.Length == 0) { _logger.LogWarning("LeakMonitor enabled but no sensor entity IDs configured"); - + 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); - } + _logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)", + _options.SensorEntityIds.Length); } catch (Exception ex) { @@ -78,9 +74,7 @@ public sealed class LeakMonitorInit }); if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId); - } } internal void HandleStateChange(string sensorEntityId, StateChange change) @@ -90,17 +84,15 @@ public sealed class LeakMonitorInit if (string.Equals(newState, LeakMonitorConsts.WaterDetectedState, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Water leak detected by {SensorId}!", sensorEntityId); - + _notificationService.SendLeakAlert(sensorEntityId); } else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase)) { if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId); - } _notificationService.DismissLeakAlert(sensorEntityId); } } -} +} \ No newline at end of file diff --git a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs index ac59c28..ea0b71f 100644 --- a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs +++ b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs @@ -1,8 +1,8 @@ +using LeakMonitorManager.Interface; +using LeakMonitorManager.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; -using LeakMonitorManager.Interface; -using LeakMonitorManager.Models; namespace LeakMonitorManager; @@ -14,11 +14,8 @@ public static class LeakMonitorServiceRegistration .GetSection(LeakMonitorOptions.SectionName) .Get() ?? new LeakMonitorOptions(); - if (!options.Enabled) - { - return; - } + if (!options.Enabled) return; services.AddNetDaemonApp().AddScoped(); } -} +} \ No newline at end of file diff --git a/LeakMonitor.Manager/LeakNotificationService.cs b/LeakMonitor.Manager/LeakNotificationService.cs index 4a14038..5a64bb6 100644 --- a/LeakMonitor.Manager/LeakNotificationService.cs +++ b/LeakMonitor.Manager/LeakNotificationService.cs @@ -1,10 +1,10 @@ using System.Collections.Concurrent; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using NetDaemon.HassModel; using LeakMonitor.Models; using LeakMonitorManager.Interface; using LeakMonitorManager.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.HassModel; namespace LeakMonitorManager; @@ -14,19 +14,17 @@ public sealed class LeakNotificationService( IOptions options, TimeProvider timeProvider) : ILeakNotificationService { - private readonly LeakMonitorOptions _options = options.Value; private readonly ConcurrentDictionary _lastNotificationTimes = new(); + private readonly LeakMonitorOptions _options = options.Value; public void SendLeakAlert(string sensorEntityId) { if (IsWithinCooldown(sensorEntityId)) { if (logger.IsEnabled(LogLevel.Debug)) - { logger.LogDebug( "Skipping leak notification for {SensorId} -- within cooldown period", sensorEntityId); - } return; } @@ -52,9 +50,7 @@ public sealed class LeakNotificationService( data: new { notification_id = notificationId }); if (logger.IsEnabled(LogLevel.Information)) - { logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId); - } } private void SendMobilePushNotification(string message) @@ -95,10 +91,7 @@ public sealed class LeakNotificationService( 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; @@ -109,4 +102,4 @@ public sealed class LeakNotificationService( 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 d73a0d2..d94e4a0 100644 --- a/LeakMonitor.Manager/Models/LeakMonitorOptions.cs +++ b/LeakMonitor.Manager/Models/LeakMonitorOptions.cs @@ -11,4 +11,4 @@ public sealed class LeakMonitorOptions public string[] SensorEntityIds { get; init; } = []; public int NotificationCooldownMinutes { get; init; } = LeakMonitorConsts.DefaultNotificationCooldownMinutes; -} +} \ No newline at end of file diff --git a/LeakMonitor.Models/LeakMonitorConsts.cs b/LeakMonitor.Models/LeakMonitorConsts.cs index 200c4ea..d9a2fd8 100644 --- a/LeakMonitor.Models/LeakMonitorConsts.cs +++ b/LeakMonitor.Models/LeakMonitorConsts.cs @@ -21,4 +21,4 @@ public static class LeakMonitorConsts public const string NotificationTitle = "Water Leak Detected!"; public const int DefaultNotificationCooldownMinutes = 5; -} +} \ No newline at end of file diff --git a/LightMonitor.Manager.Tests/LightControlServiceTests.cs b/LightMonitor.Manager.Tests/LightControlServiceTests.cs index e1c761e..15151cf 100644 --- a/LightMonitor.Manager.Tests/LightControlServiceTests.cs +++ b/LightMonitor.Manager.Tests/LightControlServiceTests.cs @@ -1,10 +1,10 @@ using LightMonitor.Models; +using LightMonitorManager; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LightMonitorManager; namespace LightMonitor.Manager.Tests; @@ -79,7 +79,7 @@ public class LightControlServiceTests public void TurnOnLight_ShouldTargetTheConfiguredLightEntity() { const string customLightEntityId = "light.kitchen_ceiling"; - var options = LightMonitorTestData.CreateOptions(lightEntityId: customLightEntityId); + var options = LightMonitorTestData.CreateOptions(customLightEntityId); SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon); SetupState(customLightEntityId, "off"); @@ -137,4 +137,4 @@ public class LightControlServiceTests _haContextMock.Verify(x => x.GetState(LightEntityId), Times.Once); VerifyTurnOn(LightEntityId, false); } -} +} \ No newline at end of file diff --git a/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj b/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj index f6e5b87..6b3461c 100644 --- a/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj +++ b/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj @@ -1,34 +1,34 @@ - - net10.0 - enable - enable - false - + + net10.0 + enable + enable + false + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - - + + + - - - - + + + + diff --git a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs index 0971d7f..67c7692 100644 --- a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs +++ b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs @@ -1,13 +1,13 @@ using System.Reactive.Subjects; using FluentAssertions; using LightMonitor.Models; +using LightMonitorManager; +using LightMonitorManager.Interface; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LightMonitorManager; -using LightMonitorManager.Interface; namespace LightMonitor.Manager.Tests; @@ -16,25 +16,21 @@ public class LightMonitorInitTests private const string SunEntityId = LightMonitorTestData.SunEntityId; private const string PersonEntityId = LightMonitorTestData.PrimaryPersonEntityId; - private readonly Mock _haContextMock = new(); - private readonly Mock _presenceServiceMock = new(); - private readonly Mock _lightControlServiceMock = new(); - private readonly Subject _stateChangesSubject = new(); - 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 LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null) { if (subscriptionException is null) - { _haContextMock.Setup(x => x.StateAllChanges()) .Returns(_stateChangesSubject); - } else - { _haContextMock.Setup(x => x.StateAllChanges()) .Throws(subscriptionException); - } return new LightMonitorInit( _haContextMock.Object, @@ -57,13 +53,9 @@ public class LightMonitorInitTests private void VerifyTurnOn(bool shouldTurnOn) { if (shouldTurnOn) - { _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once); - } else - { _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); - } } [Theory] @@ -237,7 +229,8 @@ public class LightMonitorInitTests { CreateSut(); - EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState, LightMonitorConsts.SunBelowHorizon); + EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState, + LightMonitorConsts.SunBelowHorizon); VerifyTurnOn(false); } @@ -262,4 +255,4 @@ public class LightMonitorInitTests VerifyTurnOn(false); } -} +} \ No newline at end of file diff --git a/LightMonitor.Manager.Tests/LightMonitorTestData.cs b/LightMonitor.Manager.Tests/LightMonitorTestData.cs index f75348e..057400c 100644 --- a/LightMonitor.Manager.Tests/LightMonitorTestData.cs +++ b/LightMonitor.Manager.Tests/LightMonitorTestData.cs @@ -4,9 +4,9 @@ using NetDaemon.HassModel.Entities; namespace LightMonitor.Manager.Tests; /// -/// Deterministic, reusable fixtures for the LightMonitor tests. -/// Keeping the option builder, state builders and generated state tables here -/// avoids copy-pasted setup across the test classes. +/// Deterministic, reusable fixtures for the LightMonitor tests. +/// Keeping the option builder, state builders and generated state tables here +/// avoids copy-pasted setup across the test classes. /// internal static class LightMonitorTestData { @@ -33,36 +33,9 @@ internal static class LightMonitorTestData ]; /// - /// Builds light monitor options with production-compatible defaults. - /// - public static LightMonitorOptions CreateOptions( - string lightEntityId = LightEntityId, - string sunEntityId = SunEntityId, - IEnumerable? personEntityIds = null, - bool enabled = true) => new() - { - Enabled = enabled, - LightEntityId = lightEntityId, - SunEntityId = sunEntityId, - PersonEntityIds = personEntityIds?.ToArray() ?? [.. PersonEntityIds] - }; - - /// - /// Builds an carrying . - /// - public static EntityState CreateState(string? state) => new() { State = state }; - - /// - /// Builds an , or null when the entity has no state at all - /// (as returned by IHaContext.GetState for a missing entity). - /// - public static EntityState? CreateOptionalState(string? state) => - state is null ? null : CreateState(state); - - /// - /// Sun states that should (true) or should not (false) cause a light turn on. - /// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and - /// missing states must never turn the light on. + /// Sun states that should (true) or should not (false) cause a light turn on. + /// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and + /// missing states must never turn the light on. /// public static TheoryData SunStateTurnOnCases { get; } = new() { @@ -79,8 +52,8 @@ 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. + /// 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() { @@ -97,8 +70,8 @@ internal static class LightMonitorTestData }; /// - /// Person states checked against the "arrived home" transition. - /// Only "home" in any casing counts. + /// Person states checked against the "arrived home" transition. + /// Only "home" in any casing counts. /// public static TheoryData PersonNewStateCases { get; } = new() { @@ -116,8 +89,8 @@ 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. + /// 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() { @@ -130,8 +103,8 @@ internal static class LightMonitorTestData }; /// - /// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown - /// or missing state must be ignored. + /// 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() { @@ -143,13 +116,13 @@ internal static class LightMonitorTestData }; /// - /// Every 4^3 = 64 combination of home / not_home / unavailable / missing state across the - /// three configured person entities. + /// Every 4^3 = 64 combination of home / not_home / unavailable / missing state across the + /// three configured person entities. /// public static TheoryData PresenceStateMatrix { get; } = CreatePresenceStateMatrix(); /// - /// Person id configurations that resolve to "nobody tracked". + /// Person id configurations that resolve to "nobody tracked". /// public static TheoryData NoPersonEntityIdSets { get; } = [ @@ -158,21 +131,50 @@ internal static class LightMonitorTestData [" "] ]; + /// + /// Builds light monitor options with production-compatible defaults. + /// + public static LightMonitorOptions CreateOptions( + string lightEntityId = LightEntityId, + string sunEntityId = SunEntityId, + IEnumerable? personEntityIds = null, + bool enabled = true) + { + return new LightMonitorOptions + { + Enabled = enabled, + LightEntityId = lightEntityId, + SunEntityId = sunEntityId, + PersonEntityIds = personEntityIds?.ToArray() ?? [.. PersonEntityIds] + }; + } + + /// + /// Builds an carrying . + /// + public static EntityState CreateState(string? state) + { + return new EntityState { State = state }; + } + + /// + /// Builds an , or null when the entity has no state at all + /// (as returned by IHaContext.GetState for a missing entity). + /// + public static EntityState? CreateOptionalState(string? state) + { + return state is null ? null : CreateState(state); + } + private static TheoryData CreatePresenceStateMatrix() { 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; } -} +} \ No newline at end of file diff --git a/LightMonitor.Manager.Tests/PresenceServiceTests.cs b/LightMonitor.Manager.Tests/PresenceServiceTests.cs index c68dea8..fe86ccf 100644 --- a/LightMonitor.Manager.Tests/PresenceServiceTests.cs +++ b/LightMonitor.Manager.Tests/PresenceServiceTests.cs @@ -1,18 +1,17 @@ using FluentAssertions; using LightMonitor.Models; +using LightMonitorManager; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; -using LightMonitorManager; namespace LightMonitor.Manager.Tests; public class PresenceServiceTests { - private readonly Mock _haContextMock = new(); - private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); + private readonly Mock _haContextMock = new(); private PresenceService CreateService(LightMonitorOptions? options = null) { @@ -96,9 +95,7 @@ public class PresenceServiceTests CreateService().IsAnyoneHome().Should().BeFalse(); foreach (var personEntityId in LightMonitorTestData.PersonEntityIds) - { _haContextMock.Verify(x => x.GetState(personEntityId), Times.Once); - } } [Fact] @@ -123,8 +120,6 @@ 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/Interface/ILightControlService.cs b/LightMonitor.Manager/Interface/ILightControlService.cs index 7a3e62d..4d97a69 100644 --- a/LightMonitor.Manager/Interface/ILightControlService.cs +++ b/LightMonitor.Manager/Interface/ILightControlService.cs @@ -3,4 +3,4 @@ namespace LightMonitorManager.Interface; public interface ILightControlService { void TurnOnLight(); -} +} \ No newline at end of file diff --git a/LightMonitor.Manager/Interface/IPresenceService.cs b/LightMonitor.Manager/Interface/IPresenceService.cs index 3efdffd..ce0c306 100644 --- a/LightMonitor.Manager/Interface/IPresenceService.cs +++ b/LightMonitor.Manager/Interface/IPresenceService.cs @@ -3,4 +3,4 @@ namespace LightMonitorManager.Interface; public interface IPresenceService { bool IsAnyoneHome(); -} +} \ No newline at end of file diff --git a/LightMonitor.Manager/LightControlService.cs b/LightMonitor.Manager/LightControlService.cs index 0b95ae8..03a3378 100644 --- a/LightMonitor.Manager/LightControlService.cs +++ b/LightMonitor.Manager/LightControlService.cs @@ -1,9 +1,9 @@ +using LightMonitor.Models; +using LightMonitorManager.Interface; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LightMonitor.Models; -using LightMonitorManager.Interface; namespace LightMonitorManager; @@ -22,9 +22,7 @@ public sealed class LightControlService( if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) { if (logger.IsEnabled(LogLevel.Debug)) - { logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState); - } return; } @@ -34,9 +32,7 @@ public sealed class LightControlService( if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase)) { if (logger.IsEnabled(LogLevel.Debug)) - { logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId); - } return; } @@ -44,8 +40,6 @@ public sealed class LightControlService( haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId)); if (logger.IsEnabled(LogLevel.Information)) - { logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId); - } } -} +} \ No newline at end of file diff --git a/LightMonitor.Manager/LightMonitor.Manager.csproj b/LightMonitor.Manager/LightMonitor.Manager.csproj index f188841..3b1ec7c 100644 --- a/LightMonitor.Manager/LightMonitor.Manager.csproj +++ b/LightMonitor.Manager/LightMonitor.Manager.csproj @@ -8,19 +8,19 @@ - - <_Parameter1>LightMonitor.Manager.Tests - + + <_Parameter1>LightMonitor.Manager.Tests + - - + + - - + + diff --git a/LightMonitor.Manager/LightMonitorInit.cs b/LightMonitor.Manager/LightMonitorInit.cs index b233588..100dc4e 100644 --- a/LightMonitor.Manager/LightMonitorInit.cs +++ b/LightMonitor.Manager/LightMonitorInit.cs @@ -1,10 +1,10 @@ +using LightMonitor.Models; +using LightMonitorManager.Interface; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using LightMonitor.Models; -using LightMonitorManager.Interface; namespace LightMonitorManager; @@ -12,10 +12,10 @@ namespace LightMonitorManager; public sealed class LightMonitorInit { private readonly IHaContext _haContext; - private readonly ILogger _logger; - private readonly IPresenceService _presenceService; private readonly ILightControlService _lightControlService; + private readonly ILogger _logger; private readonly LightMonitorOptions _options; + private readonly IPresenceService _presenceService; public LightMonitorInit( IHaContext haContext, @@ -41,9 +41,8 @@ public sealed class LightMonitorInit SubscribeToPersonStateChanges(); if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", _options.PersonEntityIds.Length); - } + _logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", + _options.PersonEntityIds.Length); } catch (Exception ex) { @@ -61,27 +60,20 @@ public sealed class LightMonitorInit { try { - if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) - { - return; - } + 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); - } return; } _logger.LogInformation("Sun went below horizon, checking if anyone is home"); - if (_presenceService.IsAnyoneHome()) - { - _lightControlService.TurnOnLight(); - } + if (_presenceService.IsAnyoneHome()) _lightControlService.TurnOnLight(); } catch (Exception ex) { @@ -100,25 +92,21 @@ public sealed class LightMonitorInit { try { - if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) - { - return; - } + 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); - } + _logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", + personEntityId, e.Old?.State); return; } if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId); - } + _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", + personEntityId); _lightControlService.TurnOnLight(); } @@ -130,5 +118,8 @@ public sealed class LightMonitorInit } } - private static bool IsRecoveryTransition(string? oldState) => oldState is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState; -} + private static bool IsRecoveryTransition(string? oldState) + { + return oldState is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState; + } +} \ No newline at end of file diff --git a/LightMonitor.Manager/LightMonitorServiceRegistration.cs b/LightMonitor.Manager/LightMonitorServiceRegistration.cs index 1c698d0..939a208 100644 --- a/LightMonitor.Manager/LightMonitorServiceRegistration.cs +++ b/LightMonitor.Manager/LightMonitorServiceRegistration.cs @@ -1,8 +1,8 @@ using LightMonitor.Models; +using LightMonitorManager.Interface; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; -using LightMonitorManager.Interface; namespace LightMonitorManager; @@ -14,15 +14,12 @@ public static class LightMonitorServiceRegistration .GetSection(LightMonitorOptions.SectionName) .Get() ?? new LightMonitorOptions(); - if (!options.Enabled) - { - return services; - } + if (!options.Enabled) return services; services.AddNetDaemonApp() - .AddScoped() - .AddScoped(); + .AddScoped() + .AddScoped(); return services; } -} +} \ No newline at end of file diff --git a/LightMonitor.Manager/PresenceService.cs b/LightMonitor.Manager/PresenceService.cs index 70f45e3..31dabd0 100644 --- a/LightMonitor.Manager/PresenceService.cs +++ b/LightMonitor.Manager/PresenceService.cs @@ -1,15 +1,15 @@ +using LightMonitor.Models; +using LightMonitorManager.Interface; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.HassModel; -using LightMonitor.Models; -using LightMonitorManager.Interface; namespace LightMonitorManager; public sealed class PresenceService( - IHaContext haContext, - ILogger logger, - IOptions options) : IPresenceService + IHaContext haContext, + ILogger logger, + IOptions options) : IPresenceService { private readonly LightMonitorOptions _options = options.Value; @@ -20,23 +20,16 @@ public sealed class PresenceService( var state = haContext.GetState(personEntityId); if (state?.State is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState) - { continue; - } - if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) - { - continue; - } + if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState, + 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; } return false; } -} +} \ No newline at end of file diff --git a/LightMonitor.Models/LightMonitor.Models.csproj b/LightMonitor.Models/LightMonitor.Models.csproj index 097c2f6..87c476a 100644 --- a/LightMonitor.Models/LightMonitor.Models.csproj +++ b/LightMonitor.Models/LightMonitor.Models.csproj @@ -8,11 +8,11 @@ - + - + diff --git a/LightMonitor.Models/LightMonitorConsts.cs b/LightMonitor.Models/LightMonitorConsts.cs index 5c85875..46f243d 100644 --- a/LightMonitor.Models/LightMonitorConsts.cs +++ b/LightMonitor.Models/LightMonitorConsts.cs @@ -5,17 +5,17 @@ public static class LightMonitorConsts public const string DefaultLightEntityId = "light.sonoff_1002214d40"; public const string DefaultSunEntityId = "sun.sun"; - public static readonly string[] DefaultPersonEntityIds = - [ - "person.marius", - "person.erika", - "person.home_phone" - ]; - public const string SunBelowHorizon = "below_horizon"; public const string SunAboveHorizon = "above_horizon"; public const string PersonHomeState = "home"; public const string LightOnState = "on"; public const string UnavailableState = "unavailable"; public const string UnknownState = "unknown"; -} + + public static readonly string[] DefaultPersonEntityIds = + [ + "person.marius", + "person.erika", + "person.home_phone" + ]; +} \ No newline at end of file diff --git a/LightMonitor.Models/LightMonitorOptions.cs b/LightMonitor.Models/LightMonitorOptions.cs index 5b1158b..d4e2837 100644 --- a/LightMonitor.Models/LightMonitorOptions.cs +++ b/LightMonitor.Models/LightMonitorOptions.cs @@ -10,4 +10,4 @@ public sealed class LightMonitorOptions public string LightEntityId { get; init; } = DefaultLightEntityId; public string SunEntityId { get; init; } = DefaultSunEntityId; public string[] PersonEntityIds { get; init; } = DefaultPersonEntityIds; -} +} \ No newline at end of file diff --git a/Mappings/Converters/DateTimeTypeConverter.cs b/Mappings/Converters/DateTimeTypeConverter.cs index d306125..2efcb17 100644 --- a/Mappings/Converters/DateTimeTypeConverter.cs +++ b/Mappings/Converters/DateTimeTypeConverter.cs @@ -9,4 +9,4 @@ public class DateTimeTypeConverter : ITypeConverter { return DateTime.Parse(source, CultureInfo.InvariantCulture); } -} +} \ No newline at end of file diff --git a/Mappings/Mappings.csproj b/Mappings/Mappings.csproj index c0e665d..9464151 100644 --- a/Mappings/Mappings.csproj +++ b/Mappings/Mappings.csproj @@ -7,11 +7,11 @@ - + - + diff --git a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs index 4824e56..dcdc57b 100644 --- a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs +++ b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs @@ -8,16 +8,25 @@ namespace NordPool.Manager.Tests; public class CheapestIntervalsFinderTests { + private const int Hour = 3_600; + private const int Quarter = 15 * 60; private static readonly DateTime DayStart = NordPoolTestData.DayStart; private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1); private readonly Mock> _loggerMock = new(); - private CheapestIntervalsFinder CreateSut() => new(_loggerMock.Object); + private CheapestIntervalsFinder CreateSut() + { + return new CheapestIntervalsFinder(_loggerMock.Object); + } - private static bool IsPrice(double actual, double expected) => Math.Abs(actual - expected) < 0.000_001; + private static bool IsPrice(double actual, double expected) + { + return Math.Abs(actual - expected) < 0.000_001; + } - private static NordPoolPrice CreatePricesForDay(DateTime dayStart, int intervalCount = NordPoolConsts.MaxDailyIntervals) + private static NordPoolPrice CreatePricesForDay(DateTime dayStart, + int intervalCount = NordPoolConsts.MaxDailyIntervals) { return new NordPoolPrice { @@ -44,9 +53,6 @@ public class CheapestIntervalsFinderTests }; } - private const int Hour = 3_600; - private const int Quarter = 15 * 60; - #region FindCheapestIntervals public static TheoryData FilteringCases => new() @@ -314,12 +320,25 @@ public class CheapestIntervalsFinderTests ("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), - ("boundary between adjacent intervals", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter, price: 8.96, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, price: 6.20, rank: 2)], true), - ("unsorted intervals", 14 * Hour + 5 * 60, [Interval(14 * Hour, 14 * Hour + Quarter, price: 4.93, rank: 2), Interval(10 * Hour, 10 * Hour + Quarter, price: 6.20, rank: 1)], true), + ("outside all intervals", 12 * Hour, + [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), + ("unsorted intervals", 14 * Hour + 5 * 60, + [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), - ("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), + ("in gap between intervals", 10 * Hour + 2 * Quarter, + [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), ("empty interval list", 12 * Hour, [], false) ]; @@ -357,4 +376,4 @@ public class CheapestIntervalsFinderTests } #endregion -} +} \ No newline at end of file diff --git a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs index 881fb83..54b440a 100644 --- a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs +++ b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs @@ -1,3 +1,4 @@ +using System.Text; using System.Text.Json; using FluentAssertions; using NordPool.Models; @@ -14,6 +15,18 @@ public class CompactNordPoolDayPriceTests private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds(); private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds(); + public static TheoryData InvalidJsonPayloads => new() + { + { "empty array", "[]" }, + { "too few elements", "[1,2]" }, + { "extra elements", "[1,2,3,4]" }, + { "missing end of array", "[1,2,3" }, + { "non-numeric start", "[\"abc\",2,3]" }, + { "non-numeric end", "[1,\"abc\",3]" }, + { "non-numeric price", "[1,2,\"abc\"]" }, + { "object instead of array", "{\"start\":1}" } + }; + [Fact] public void FromDayPrice_ShouldConvertDateTimesToUnixEpochSeconds() { @@ -150,7 +163,9 @@ public class CompactNordPoolDayPriceTests var json = JsonSerializer.Serialize(prices); - json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]"); + json.Should() + .Be( + $"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]"); } [Fact] @@ -161,18 +176,6 @@ public class CompactNordPoolDayPriceTests act.Should().Throw(); } - public static TheoryData InvalidJsonPayloads => new() - { - { "empty array", "[]" }, - { "too few elements", "[1,2]" }, - { "extra elements", "[1,2,3,4]" }, - { "missing end of array", "[1,2,3" }, - { "non-numeric start", "[\"abc\",2,3]" }, - { "non-numeric end", "[1,\"abc\",3]" }, - { "non-numeric price", "[1,2,\"abc\"]" }, - { "object instead of array", "{\"start\":1}" } - }; - [Theory] [MemberData(nameof(InvalidJsonPayloads))] public void JsonDeserialization_WithInvalidPayload_ShouldThrowJsonException(string scenario, string json) @@ -237,7 +240,8 @@ 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] @@ -284,9 +288,9 @@ public class CompactNordPoolDayPriceTests last_updated = DateTime.UtcNow.ToString("O") }; var json = JsonSerializer.Serialize(attributePayload); - var byteCount = System.Text.Encoding.UTF8.GetByteCount(json); + var byteCount = Encoding.UTF8.GetByteCount(json); 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/NordPool.Manager.Tests.csproj b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj index 4c0f2b8..48ded57 100644 --- a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj +++ b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj @@ -1,36 +1,36 @@ - - net10.0 - enable - enable - false - + + net10.0 + enable + enable + false + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + - - - + + + - - - - - + + + + + \ No newline at end of file diff --git a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs index 7465217..128790c 100644 --- a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs @@ -1,3 +1,5 @@ +using System.Text; +using System.Text.Json; using FluentAssertions; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; @@ -266,7 +268,8 @@ public class NordPoolEntityServiceTests _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), 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); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"), + 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); } @@ -284,13 +287,20 @@ public class NordPoolEntityServiceTests await _sut.ResetEntitiesAsync(); // Assert - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), Times.Once); - _entityManagerMock.Verify(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); - _entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny()), + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), + Times.Once); + _entityManagerMock.Verify( + 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); + _entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny()), + Times.Once); } [Fact] @@ -299,7 +309,8 @@ public class NordPoolEntityServiceTests // Arrange _entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny())) .ThrowsAsync(new InvalidOperationException("State update failed")); - _entityManagerMock.Setup(em => em.SetEntityState(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) + _entityManagerMock.Setup(em => + 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); @@ -325,7 +336,8 @@ public class NordPoolEntityServiceTests // 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)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), + Times.Exactly(7)); } #endregion @@ -378,12 +390,16 @@ public class NordPoolEntityServiceTests await _sut.UpdateEntitiesAsync(context); // Assert - _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny()), + 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); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); + _entityManagerMock.Verify( + 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); } [Fact] @@ -401,10 +417,14 @@ public class NordPoolEntityServiceTests await _sut.UpdateEntitiesAsync(context); // Assert - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), + Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), + Times.Once); + _entityManagerMock.Verify( + em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); } [Fact] @@ -448,26 +468,46 @@ public class NordPoolEntityServiceTests { Prices = [ - new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 }, + new NordPoolDayPrice + { + Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 + }, new NordPoolDayPrice { Start = null, End = todayStart.AddHours(3).AddMinutes(15), Price = 1.0 } ] }, new NordPoolPrice { - Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] + Prices = + [ + new NordPoolDayPrice + { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 } + ] }, 2 ), ( "only today", - new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] }, + new NordPoolPrice + { + Prices = + [ + new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 } + ] + }, new NordPoolPrice { Prices = [] }, 1 ), ( "only tomorrow", new NordPoolPrice { Prices = [] }, - new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] }, + new NordPoolPrice + { + Prices = + [ + new NordPoolDayPrice + { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 } + ] + }, 1 ), ("empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0), @@ -481,10 +521,13 @@ public class NordPoolEntityServiceTests object? capturedAttributes = null; _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + _entityManagerMock.Setup(em => + 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())) + _entityManagerMock.Setup(em => + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), + It.IsAny())) .Returns(Task.CompletedTask); var context = CreateDefaultContext() with @@ -513,12 +556,15 @@ public class NordPoolEntityServiceTests // Arrange var todayPrice = new NordPoolPrice { - Prices = [new NordPoolDayPrice - { - Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc), - End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc), - Price = 17.91 - }] + Prices = + [ + new NordPoolDayPrice + { + Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc), + End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc), + Price = 17.91 + } + ] }; var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] }); @@ -563,10 +609,13 @@ public class NordPoolEntityServiceTests object? capturedAttributes = null; _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + _entityManagerMock.Setup(em => + 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())) + _entityManagerMock.Setup(em => + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), + It.IsAny())) .Returns(Task.CompletedTask); var context = CreateDefaultContext( @@ -578,8 +627,8 @@ public class NordPoolEntityServiceTests // Assert capturedAttributes.Should().NotBeNull(); - var json = System.Text.Json.JsonSerializer.Serialize(capturedAttributes); - var byteCount = System.Text.Encoding.UTF8.GetByteCount(json); + 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"); } @@ -590,10 +639,11 @@ public class NordPoolEntityServiceTests [InlineData(-5.25, "-5.25")] [InlineData(1234.5, "1234.50")] [InlineData(17.916, "17.92")] - public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, string expected) + public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, + string expected) { // Arrange - var context = CreateDefaultContext(currentPrice: price); + var context = CreateDefaultContext(price); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); @@ -617,7 +667,8 @@ public class NordPoolEntityServiceTests _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) + _entityManagerMock.Setup(em => + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) .Returns(Task.CompletedTask); var context = CreateDefaultContext() with @@ -654,7 +705,9 @@ public class NordPoolEntityServiceTests _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny())) + _entityManagerMock.Setup(em => + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), + It.IsAny())) .Returns(Task.CompletedTask); var first = new CheapestIntervalResult @@ -693,7 +746,8 @@ public class NordPoolEntityServiceTests capturedAttributes.Should().NotBeNull(); var attributes = capturedAttributes!; var type = attributes.GetType(); - ((IEnumerable)type.GetProperty("intervals")!.GetValue(attributes)!).Should().HaveCount(2); + ((IEnumerable)type.GetProperty("intervals")!.GetValue(attributes)!).Should() + .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")); @@ -714,7 +768,9 @@ public class NordPoolEntityServiceTests _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny())) + _entityManagerMock.Setup(em => + em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), + It.IsAny())) .Returns(Task.CompletedTask); var context = CreateDefaultContext() with { CheapestIntervals = null }; @@ -740,10 +796,13 @@ public class NordPoolEntityServiceTests object? capturedAttributes = null; _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + _entityManagerMock.Setup(em => + 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())) + _entityManagerMock.Setup(em => + 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); @@ -751,7 +810,8 @@ public class NordPoolEntityServiceTests { Prices = [ - new NordPoolDayPrice { Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 }, + new NordPoolDayPrice + { Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 }, new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 } ] }; @@ -759,7 +819,8 @@ public class NordPoolEntityServiceTests { Prices = [ - new NordPoolDayPrice { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 } + new NordPoolDayPrice + { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 } ] }; var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice); @@ -813,7 +874,8 @@ public class NordPoolEntityServiceTests l => l.Log( LogLevel.Warning, It.IsAny(), - It.Is((state, _) => state != null && state.ToString()!.Contains("exceeds expected maximum")), + It.Is((state, _) => + state != null && state.ToString()!.Contains("exceeds expected maximum")), It.IsAny(), It.IsAny>()), Times.Once); @@ -826,7 +888,7 @@ public class NordPoolEntityServiceTests public static TheoryData> CancelledOperations() { var data = new TheoryData>(); - var cancelled = new CancellationToken(canceled: true); + var cancelled = new CancellationToken(true); var context = CreateDefaultContext(); data.Add("create entities", sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled)); @@ -854,4 +916,4 @@ public class NordPoolEntityServiceTests } #endregion -} +} \ No newline at end of file diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index 54c1c18..bc9208b 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -15,14 +15,14 @@ namespace NordPool.Manager.Tests; public class NordPoolInitTests { + private readonly Mock _boilerConfigProviderMock; + private readonly Mock _cheapestIntervalsFinderMock; + private readonly Entities _entities; + private readonly Mock _entityServiceMock; + private readonly Mock _haContextMock; private readonly Mock> _loggerMock; private readonly Mock _priceServiceMock; - private readonly Mock _entityServiceMock; private readonly Mock _schedulerMock; - private readonly Mock _cheapestIntervalsFinderMock; - private readonly Mock _boilerConfigProviderMock; - private readonly Mock _haContextMock; - private readonly Entities _entities; public NordPoolInitTests() { @@ -37,10 +37,12 @@ public class NordPoolInitTests _entities = new Entities(_haContextMock.Object); _priceServiceMock.Setup(p => p.FetchPricesAsync()).Returns(Task.CompletedTask); - _entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny())) + .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); + _entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny())) + .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); @@ -49,7 +51,8 @@ public class NordPoolInitTests _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())) + .Setup(c => c.IsCurrentIntervalCheap(It.IsAny>(), + It.IsAny())) .Returns(false); _boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig { @@ -101,9 +104,12 @@ public class NordPoolInitTests _entityServiceMock.Verify( es => es.CleanupEntitiesAsync(It.IsAny()), cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never()); - _entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny(), It.IsAny()), Times.AtLeastOnce); + _entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny(), It.IsAny()), + Times.AtLeastOnce); _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny()), Times.AtLeastOnce); - _entityServiceMock.Verify(es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), Times.AtLeastOnce); + _entityServiceMock.Verify( + es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), + Times.AtLeastOnce); } [Fact] @@ -118,6 +124,7 @@ public class NordPoolInitTests 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); + _entityServiceMock.Verify( + 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 72d9f99..2047344 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -30,14 +30,14 @@ public class NordPoolPriceServiceTests #region GetTimeQuarterIndex [Theory] - [InlineData(0, 0, 8)] // UTC 00:00 = CEST 02:00 - [InlineData(1, 0, 12)] // UTC 01:00 = CEST 03:00 - [InlineData(6, 0, 32)] // UTC 06:00 = CEST 08:00 - [InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00 - [InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 (next day start) - [InlineData(22, 15, 1)] // UTC 22:15 = CEST 00:15 - [InlineData(22, 30, 2)] // UTC 22:30 = CEST 00:30 - [InlineData(22, 45, 3)] // UTC 22:45 = CEST 00:45 + [InlineData(0, 0, 8)] // UTC 00:00 = CEST 02:00 + [InlineData(1, 0, 12)] // UTC 01:00 = CEST 03:00 + [InlineData(6, 0, 32)] // UTC 06:00 = CEST 08:00 + [InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00 + [InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 (next day start) + [InlineData(22, 15, 1)] // UTC 22:15 = CEST 00:15 + [InlineData(22, 30, 2)] // UTC 22:30 = CEST 00:30 + [InlineData(22, 45, 3)] // UTC 22:45 = CEST 00:45 public void GetTimeQuarterIndex_ShouldReturnCorrectIndex(int hour, int minute, int expectedIndex) { // Arrange — 2026-03-31 is in CEST (UTC+2) @@ -51,11 +51,11 @@ public class NordPoolPriceServiceTests } [Theory] - [InlineData(0, 15, 9)] // UTC 00:15 = CEST 02:15 - [InlineData(1, 30, 14)] // UTC 01:30 = CEST 03:30 - [InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00 - [InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 - [InlineData(22, 59, 3)] // UTC 22:59 = CEST 00:59 + [InlineData(0, 15, 9)] // UTC 00:15 = CEST 02:15 + [InlineData(1, 30, 14)] // UTC 01:30 = CEST 03:30 + [InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00 + [InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 + [InlineData(22, 59, 3)] // UTC 22:59 = CEST 00:59 public void GetTimeQuarterIndex_ShouldHandleAllHoursCorrectly(int hour, int minute, int expectedIndex) { // Arrange — 2026-03-31 is in CEST (UTC+2) @@ -115,13 +115,11 @@ 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) { - 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); - } + var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); + var index = NordPoolPriceService.GetTimeQuarterIndex(date); + indices.Add(index); } // Assert @@ -131,9 +129,10 @@ 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) + [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) { // Arrange var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc); @@ -233,7 +232,14 @@ public class NordPoolPriceServiceTests // Arrange var dto = new NordPoolPriceResultDto { - Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }] + Prices = + [ + new NordPoolDayPriceDto + { + Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), + Price = 100.0 + } + ] }; var jsonString = JsonSerializer.Serialize(dto); @@ -243,7 +249,11 @@ public class NordPoolPriceServiceTests { Prices = new List { - new() { Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture), End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0 } + new() + { + Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture), + End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0 + } } }; @@ -265,7 +275,14 @@ public class NordPoolPriceServiceTests // Arrange var dto = new NordPoolPriceResultDto { - Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }] + Prices = + [ + new NordPoolDayPriceDto + { + Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), + Price = 100.0 + } + ] }; var jsonString = JsonSerializer.Serialize(dto); @@ -456,14 +473,12 @@ 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 }; @@ -667,32 +682,37 @@ public class NordPoolPriceServiceTests #region ShouldFetchNewPrices - private static NordPoolPrice CreatePrices(params double?[] values) => new() + private static NordPoolPrice CreatePrices(params double?[] values) { - Prices = [.. values.Select(price => new NordPoolDayPrice { Price = price })] - }; + return new NordPoolPrice + { + Prices = [.. values.Select(price => new NordPoolDayPrice { Price = price })] + }; + } /// - /// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00, - /// so the "tomorrow missing" cases are covered separately below). xUnit cannot serialize - /// rows, so the matrix runs inside a single test. + /// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00, + /// so the "tomorrow missing" cases are covered separately below). xUnit cannot serialize + /// rows, so the matrix runs inside a single test. /// [Fact] public void ShouldFetchNewPrices_ShouldMatchScenario() { var today = DateOnly.FromDateTime(DateTime.Now); - (string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, bool Expected)[] cases = - [ - ("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true), - ("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), true), - ("last fetch date is in the future", today.AddDays(1), CreatePrices(12.50), CreatePrices(18.71), false), - ("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true), - ("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), - ("all price payloads are null", today, null, null, true) - ]; + (string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, bool + Expected)[] cases = + [ + ("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true), + ("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), true), + ("last fetch date is in the future", today.AddDays(1), CreatePrices(12.50), CreatePrices(18.71), false), + ("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true), + ("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), + ("all price payloads are null", today, null, null, true) + ]; foreach (var (scenario, lastFetchedDate, todayPrice, tomorrowPrice, expected) in cases) { @@ -779,7 +799,7 @@ public class NordPoolPriceServiceTests } /// - /// Rows are not serializable as theory data, so the three unusable payloads are exercised in one test. + /// Rows are not serializable as theory data, so the three unusable payloads are exercised in one test. /// [Fact] public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice() @@ -789,7 +809,7 @@ public class NordPoolPriceServiceTests foreach (var tomorrow in unusablePrices) { // Arrange - _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = [new() { Price = 12.50 }] }; + _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = [new NordPoolDayPrice { Price = 12.50 }] }; _sut.TomorrowNordPoolPrice = tomorrow; _sut.DayQuartersIndex = 42; var today = new DateOnly(2026, 4, 1); @@ -849,4 +869,4 @@ public class NordPoolPriceServiceTests } #endregion -} +} \ No newline at end of file diff --git a/NordPool.Manager.Tests/NordPoolTestData.cs b/NordPool.Manager.Tests/NordPoolTestData.cs index 8294336..163aa1d 100644 --- a/NordPool.Manager.Tests/NordPoolTestData.cs +++ b/NordPool.Manager.Tests/NordPoolTestData.cs @@ -3,15 +3,15 @@ using NordPool.Models; namespace NordPool.Manager.Tests; /// -/// Shared, deterministic datasets used by the NordPool tests. -/// Keeping the generators here avoids copy-pasted price loops across test classes. +/// Shared, deterministic datasets used by the NordPool tests. +/// Keeping the generators here avoids copy-pasted price loops across test classes. /// internal static class NordPoolTestData { public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); /// - /// Builds a contiguous set of 15-minute intervals starting at . + /// Builds a contiguous set of 15-minute intervals starting at . /// public static List CreateIntervals( int count, @@ -33,8 +33,8 @@ internal static class NordPoolTestData } /// - /// A full 96-interval day with a deterministic sawtooth price curve covering - /// negative, zero, cheap and expensive prices. + /// A full 96-interval day with a deterministic sawtooth price curve covering + /// negative, zero, cheap and expensive prices. /// public static List CreateGeneratedDay(DateTime? dayStart = null) { @@ -45,4 +45,4 @@ internal static class NordPoolTestData 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 ee273c1..54e5a00 100644 --- a/NordPool.Manager/CheapestIntervalsFinder.cs +++ b/NordPool.Manager/CheapestIntervalsFinder.cs @@ -6,19 +6,20 @@ namespace NordPoolManager; public class CheapestIntervalsFinder(ILogger logger) : ICheapestIntervalsFinder { - public IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline) + public IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, + double priceCap, DateTime deadline) { if (prices.Prices is not { Count: > 0 }) { logger.LogWarning("No prices available for cheapest interval calculation"); - + return []; } if (numberOfIntervals <= 0) { logger.LogWarning("Number of intervals requested is {Count}, returning empty", numberOfIntervals); - + return []; } @@ -49,4 +50,4 @@ public class CheapestIntervalsFinder(ILogger logger) : { return cheapestIntervals.Any(interval => utcNow >= interval.Start && utcNow < interval.End); } -} +} \ No newline at end of file diff --git a/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs b/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs index 90d3a01..cfed1a7 100644 --- a/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs +++ b/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs @@ -4,7 +4,8 @@ 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 e41dbaa..7c9b23e 100644 --- a/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs +++ b/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs @@ -3,9 +3,9 @@ using BoilerMonitor.Models; namespace NordPoolManager.Interface; /// -/// Supplies boiler scheduling configuration for NordPool cheapest-interval logic. +/// Supplies boiler scheduling configuration for NordPool cheapest-interval logic. /// public interface INordPoolBoilerConfigProvider { BoilerConfig GetCurrentConfiguration(); -} +} \ No newline at end of file diff --git a/NordPool.Manager/Interface/INordPoolEntityService.cs b/NordPool.Manager/Interface/INordPoolEntityService.cs index 1ac23bf..0ff21b0 100644 --- a/NordPool.Manager/Interface/INordPoolEntityService.cs +++ b/NordPool.Manager/Interface/INordPoolEntityService.cs @@ -8,4 +8,4 @@ public interface INordPoolEntityService Task ResetEntitiesAsync(CancellationToken cancellationToken = default); Task UpdateEntitiesAsync(EntityUpdateContext context, CancellationToken cancellationToken = default); Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); -} +} \ No newline at end of file diff --git a/NordPool.Manager/Interface/INordPoolPriceService.cs b/NordPool.Manager/Interface/INordPoolPriceService.cs index dc7474a..2fa1df3 100644 --- a/NordPool.Manager/Interface/INordPoolPriceService.cs +++ b/NordPool.Manager/Interface/INordPoolPriceService.cs @@ -16,4 +16,4 @@ public interface INordPoolPriceService double GetCurrentPrice(); bool ShouldFetchNewPrices(DateOnly today); void RollOverPrices(DateOnly today); -} +} \ No newline at end of file diff --git a/NordPool.Manager/Models/EntityUpdateContext.cs b/NordPool.Manager/Models/EntityUpdateContext.cs index 4775208..fb4b7be 100644 --- a/NordPool.Manager/Models/EntityUpdateContext.cs +++ b/NordPool.Manager/Models/EntityUpdateContext.cs @@ -19,4 +19,4 @@ public record EntityUpdateContext public required string? ConfiguredReadyBy { get; init; } public required bool IsNowCheap { get; init; } public required DateTime? NextCheapIntervalStart { get; init; } -} +} \ No newline at end of file diff --git a/NordPool.Manager/Models/NordPoolOptions.cs b/NordPool.Manager/Models/NordPoolOptions.cs index e5f1dfe..949d4e4 100644 --- a/NordPool.Manager/Models/NordPoolOptions.cs +++ b/NordPool.Manager/Models/NordPoolOptions.cs @@ -5,7 +5,7 @@ public sealed class NordPoolOptions public const string SectionName = "NordPool"; /// - /// When true, removes existing NordPool MQTT entities before recreating them on app startup. + /// When true, removes existing NordPool MQTT entities before recreating them on app startup. /// public bool CleanupEntitiesOnStartup { get; init; } = true; -} +} \ No newline at end of file diff --git a/NordPool.Manager/NordPool.Manager.csproj b/NordPool.Manager/NordPool.Manager.csproj index a49b2f1..da8ba19 100644 --- a/NordPool.Manager/NordPool.Manager.csproj +++ b/NordPool.Manager/NordPool.Manager.csproj @@ -8,22 +8,22 @@ - - <_Parameter1>NordPool.Manager.Tests - + + <_Parameter1>NordPool.Manager.Tests + - - - + + + - - - - + + + + diff --git a/NordPool.Manager/NordPoolBoilerConfigProvider.cs b/NordPool.Manager/NordPoolBoilerConfigProvider.cs index 899737e..d961be9 100644 --- a/NordPool.Manager/NordPoolBoilerConfigProvider.cs +++ b/NordPool.Manager/NordPoolBoilerConfigProvider.cs @@ -4,9 +4,12 @@ using NordPoolManager.Interface; namespace NordPoolManager; /// -/// Resolves boiler configuration from Home Assistant state for NordPool scheduling. +/// Resolves boiler configuration from Home Assistant state for NordPool scheduling. /// public sealed class NordPoolBoilerConfigProvider(IBoilerConfigReader boilerConfigReader) : INordPoolBoilerConfigProvider { - public BoilerConfig GetCurrentConfiguration() => boilerConfigReader.ReadConfig(); -} + public BoilerConfig GetCurrentConfiguration() + { + return boilerConfigReader.ReadConfig(); + } +} \ No newline at end of file diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index da1abfc..641d478 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -8,7 +8,8 @@ using NordPoolManager.Models; namespace NordPoolManager; -public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger logger) : INordPoolEntityService +public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger logger) + : INordPoolEntityService { private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time"; private const string TodayPricesEntityId = "sensor.nordpool_today_prices"; @@ -51,7 +52,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - + await Task.WhenAll( ResetLastUpdateTimeAsync(), ResetCurrentPriceAsync(), @@ -63,6 +64,59 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< ).ConfigureAwait(false); } + public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + var utcNow = DateTime.UtcNow; + var timestamp = utcNow.ToString("O"); + var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); + var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture); + var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0; + var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0; + var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice); + + if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries) + logger.LogWarning( + "Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", + mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries); + + var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; + + if (logger.IsEnabled(LogLevel.Information)) + logger.LogInformation( + "Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", + cheapestCount, ctx.IsNowCheap); + + var updateTasks = new[] + { + UpdateLastUpdateTimeAsync(updateTimeState), + UpdateCurrentPriceAsync(priceValue, ctx, timestamp), + UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp), + UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp), + UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp), + UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp) + }; + + await Task.WhenAll(updateTasks).ConfigureAwait(false); + } + + public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity); + await Task.WhenAll(removeTasks).ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogError(ex, "Error cleaning up NordPool entities"); + throw; + } + } + private async Task ResetLastUpdateTimeAsync() { await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false); @@ -149,43 +203,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< }).ConfigureAwait(false); } - public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - - var utcNow = DateTime.UtcNow; - var timestamp = utcNow.ToString("O"); - var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); - var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture); - var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0; - var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0; - var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice); - - if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries) - { - logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries); - } - - var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; - - if (logger.IsEnabled(LogLevel.Information)) - { - logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap); - } - - var updateTasks = new[] - { - UpdateLastUpdateTimeAsync(updateTimeState), - UpdateCurrentPriceAsync(priceValue, ctx, timestamp), - UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp), - UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp), - UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp), - UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp) - }; - - await Task.WhenAll(updateTasks).ConfigureAwait(false); - } - private async Task UpdateLastUpdateTimeAsync(string updateTimeState) { await SetEntityStateSafe(LastUpdateTimeEntityId, updateTimeState).ConfigureAwait(false); @@ -229,7 +246,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< }).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 @@ -260,22 +278,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< }).ConfigureAwait(false); } - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - - try - { - var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity); - await Task.WhenAll(removeTasks).ConfigureAwait(false); - } - catch (Exception ex) - { - logger.LogError(ex, "Error cleaning up NordPool entities"); - throw; - } - } - internal static ICollection GetInitEntitiesList(string? unitOfMeasurement) { const string currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId; @@ -344,4 +346,4 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId); } } -} +} \ No newline at end of file diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index c4fa507..bfb3001 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -17,19 +17,16 @@ namespace NordPoolManager; [NetDaemonApp] public class NordPoolInit { - private readonly ILogger _logger; - private readonly IHaContext _haContext; - private readonly INordPoolPriceService _priceService; - private readonly INordPoolEntityService _entityService; - private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly INordPoolBoilerConfigProvider _boilerConfigProvider; - private readonly IScheduler _scheduler; + private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; + private readonly INordPoolEntityService _entityService; + private readonly IHaContext _haContext; + private readonly ILogger _logger; private readonly NordPoolOptions _options; + private readonly INordPoolPriceService _priceService; + private readonly IScheduler _scheduler; private readonly TimeProvider _timeProvider; - private string? UnitOfMeasurement { get; } - private IReadOnlyList? CheapestIntervals { get; set; } - public NordPoolInit( Entities entities, IHaContext haContext, @@ -57,22 +54,22 @@ public class NordPoolInit _ = InitializeAndScheduleAsync(); } - + + private string? UnitOfMeasurement { get; } + private IReadOnlyList? CheapestIntervals { get; set; } + public async Task InitializeAsync() { try { 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(); await Task.Delay(TimeSpan.FromSeconds(10)); - + await UpdatePricesAsync(); } catch (Exception ex) @@ -81,7 +78,7 @@ public class NordPoolInit throw; } } - + private async Task InitializeAndScheduleAsync() { try @@ -118,14 +115,9 @@ public class NordPoolInit var today = DateOnly.FromDateTime(nowCet); if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today) - { _priceService.RollOverPrices(today); - } - if (_priceService.ShouldFetchNewPrices(today)) - { - await _priceService.FetchPricesAsync(); - } + if (_priceService.ShouldFetchNewPrices(today)) await _priceService.FetchPricesAsync(); _priceService.UpdateCurrentPrice(); @@ -161,11 +153,12 @@ public class NordPoolInit { _logger.LogDebug("No today prices available, skipping cheapest intervals calculation"); CheapestIntervals = []; - + return; } - CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline); + CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, + effectiveIntervalCount, effectivePriceCap, config.Deadline); } catch (Exception ex) { @@ -183,8 +176,9 @@ public class NordPoolInit var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour; var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture); - var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); - + var isNowCheap = CheapestIntervals != null && + _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); + var nextCheapInterval = CheapestIntervals? .Where(i => i.Start > currentDateTime) .OrderBy(i => i.Start) @@ -211,4 +205,4 @@ public class NordPoolInit await _entityService.UpdateEntitiesAsync(context); } -} +} \ No newline at end of file diff --git a/NordPool.Manager/NordPoolPriceService.cs b/NordPool.Manager/NordPoolPriceService.cs index 7c8fcc3..b63de5b 100644 --- a/NordPool.Manager/NordPoolPriceService.cs +++ b/NordPool.Manager/NordPoolPriceService.cs @@ -9,7 +9,8 @@ using NordPoolManager.Models.Consts; namespace NordPoolManager; -public class NordPoolPriceService(Services services, IMapper mapper, ILogger logger) : INordPoolPriceService +public class NordPoolPriceService(Services services, IMapper mapper, ILogger logger) + : INordPoolPriceService { private readonly NordpoolServices _nordPoolServices = services.Nordpool; @@ -29,19 +30,16 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger index) { var price = TodayNordPoolPrice.Prices[index].Price; if (price.HasValue) - { CurrentPrice = price.Value; - } else - { logger.LogWarning("Price at index {Index} is null", index); - } } else { - logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0); + logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", + index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0); } DayQuartersIndex = index; @@ -92,25 +83,13 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger 0 }) - { - return false; - } + if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false; var currentHour = DateTime.Now.Hour; @@ -119,7 +98,9 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger 0 } ? TomorrowNordPoolPrice : new NordPoolPrice(); + TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } + ? TomorrowNordPoolPrice + : new NordPoolPrice(); TomorrowNordPoolPrice = null; @@ -130,7 +111,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger FetchPricesForDateWithRetryAsync(DateOnly date, string label) { for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++) - { try { return await GetNordPoolPriceAsync(date); @@ -138,18 +118,23 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger(); - return priceResult != null ? mapper.Map(priceResult) : new NordPoolPrice(); + return priceResult != null + ? mapper.Map(priceResult) + : new NordPoolPrice(); } internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice) @@ -189,17 +173,11 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger() }; - 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 { @@ -229,4 +207,4 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger { - 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) - { throw new JsonException("Expected number for Start at position 0."); - } var start = reader.GetInt64(); if (!reader.Read() || reader.TokenType != JsonTokenType.Number) - { throw new JsonException("Expected number for End at position 1."); - } var end = reader.GetInt64(); if (!reader.Read() || (reader.TokenType != JsonTokenType.Number && reader.TokenType != JsonTokenType.Null)) - { throw new JsonException("Expected number or null for Price at position 2."); - } double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble(); @@ -82,14 +74,10 @@ 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/NordPool.Models.csproj b/NordPool.Models/NordPool.Models.csproj index 85d62f7..d2da538 100644 --- a/NordPool.Models/NordPool.Models.csproj +++ b/NordPool.Models/NordPool.Models.csproj @@ -7,11 +7,11 @@ - + - + diff --git a/NordPool.Models/NordPoolConsts.cs b/NordPool.Models/NordPoolConsts.cs index f30158c..96f636c 100644 --- a/NordPool.Models/NordPoolConsts.cs +++ b/NordPool.Models/NordPoolConsts.cs @@ -5,23 +5,23 @@ public static class NordPoolConsts public const string ConfigEntry = "01K9HYQE4Y0E7KC36JZV11MEXH"; /// - /// NordPool electricity market uses 15-minute trading intervals. + /// NordPool electricity market uses 15-minute trading intervals. /// public const int MinutesPerInterval = 15; /// - /// Number of 15-minute intervals in one hour. + /// Number of 15-minute intervals in one hour. /// public const int IntervalsPerHour = 4; /// - /// Maximum number of 15-minute intervals in a single day (96 = 24h * 4). + /// Maximum number of 15-minute intervals in a single day (96 = 24h * 4). /// public const int MaxDailyIntervals = 96; /// - /// Maximum expected price entries when today and tomorrow are both available - /// (96 intervals per day x 2 days). Used for logging a warning if exceeded. + /// Maximum expected price entries when today and tomorrow are both available + /// (96 intervals per day x 2 days). Used for logging a warning if exceeded. /// public const int MaxExpectedPriceEntries = 192; @@ -30,22 +30,22 @@ public static class NordPoolConsts public const string DeviceManufacturer = "HomeAssistant App Daemon"; /// - /// Home Assistant entity id for the Nord Pool current price sensor published by this integration. + /// Home Assistant entity id for the Nord Pool current price sensor published by this integration. /// public const string CurrentPriceEntityId = "sensor.nordpool_current_price"; /// - /// Home Assistant entity id for the button that triggers a manual NordPool price fetch + entity update. + /// Home Assistant entity id for the button that triggers a manual NordPool price fetch + entity update. /// public const string FetchPricesButtonEntityId = "button.nordpool_fetch_prices"; /// - /// Maximum number of retry attempts when fetching prices from the NordPool API. + /// Maximum number of retry attempts when fetching prices from the NordPool API. /// public const int MaxFetchRetryAttempts = 3; /// - /// Base delay in seconds between retry attempts (used with exponential backoff). + /// Base delay in seconds between retry attempts (used with exponential backoff). /// public const int RetryBaseDelaySeconds = 5; } \ No newline at end of file diff --git a/NordPool.Models/NordPoolDayPriceExtensions.cs b/NordPool.Models/NordPoolDayPriceExtensions.cs index 4436e1e..71c3df9 100644 --- a/NordPool.Models/NordPoolDayPriceExtensions.cs +++ b/NordPool.Models/NordPoolDayPriceExtensions.cs @@ -8,4 +8,4 @@ public static class NordPoolDayPriceExtensions ? [] : [.. prices.Select(CompactNordPoolDayPrice.FromDayPrice)]; } -} +} \ No newline at end of file diff --git a/NordPool.Models/NordPoolEntities.cs b/NordPool.Models/NordPoolEntities.cs index 43a09c1..5054423 100644 --- a/NordPool.Models/NordPoolEntities.cs +++ b/NordPool.Models/NordPoolEntities.cs @@ -13,10 +13,6 @@ public class NordPoolEntity : EntityCreateModel manufacturer = NordPoolConsts.DeviceManufacturer }; - public string Domain { get; } - public string Identifier { get; } - public string Name { get; } - public NordPoolEntity(string domain, string identifier, string name) { Domain = domain; @@ -33,9 +29,13 @@ public class NordPoolEntity : EntityCreateModel AdditionalConfig = new { device = DeviceBlock }; } + public string Domain { get; } + public string Identifier { get; } + public string Name { get; } + /// - /// Creates an AdditionalConfig that merges custom properties with the NordPool device block. - /// Use this when an entity needs extra config beyond the default device assignment. + /// Creates an AdditionalConfig that merges custom properties with the NordPool device block. + /// Use this when an entity needs extra config beyond the default device assignment. /// public static object CreateAdditionalConfig(object extraProperties) { diff --git a/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs b/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs index 66acbde..b8c759b 100644 --- a/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs +++ b/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs @@ -13,6 +13,60 @@ public class CostAccumulatorTests Month } + #region Thread safety + + [Fact] + public async Task AddCost_ConcurrentAccess_ShouldNotLoseData() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + var sut = new CostAccumulator(now); + const double incrementPerCall = 0.001; + const int callsPerThread = 1000; + const int threadCount = 10; + + // Act + var tasks = Enumerable.Range(0, threadCount) + .Select(_ => Task.Run(() => + { + for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1)); + })) + .ToArray(); + + await Task.WhenAll(tasks); + + // Assert + var snapshot = sut.GetSnapshot(); + const double expected = incrementPerCall * callsPerThread * threadCount; + snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001); + } + + #endregion + + private static double GetCurrent(CostSnapshot snapshot, CostWindow window) + { + return window switch + { + CostWindow.FifteenMinutes => snapshot.Cost15Min, + CostWindow.Hour => snapshot.Cost1Hour, + CostWindow.Day => snapshot.CostDaily, + CostWindow.Month => snapshot.CostMonthly, + _ => throw new ArgumentOutOfRangeException(nameof(window)) + }; + } + + private static double GetPrevious(CostSnapshot snapshot, CostWindow window) + { + return window switch + { + CostWindow.FifteenMinutes => snapshot.Previous15Min, + CostWindow.Hour => snapshot.Previous1Hour, + CostWindow.Day => snapshot.PreviousDaily, + CostWindow.Month => snapshot.PreviousMonthly, + _ => throw new ArgumentOutOfRangeException(nameof(window)) + }; + } + #region AddCost and GetSnapshot [Fact] @@ -67,10 +121,7 @@ public class CostAccumulatorTests .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(); @@ -142,21 +193,66 @@ public class CostAccumulatorTests public static TheoryData WindowRolloverCases => new() { - { "15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), new DateTime(2026, 3, 17, 10, 15, 0), 0.10, 0.02 }, - { "15 minute slot ends across the hour", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.10, 0.02 }, - { "15 minute slot ends at midnight", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.10, 0.02 }, - { "15 minute slot ends on DST spring forward", CostWindow.FifteenMinutes, new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.10, 0.02 }, - { "15 minute slot ends on DST fall back", CostWindow.FifteenMinutes, new DateTime(2026, 10, 25, 2, 45, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.10, 0.02 }, - { "hour ends", CostWindow.Hour, new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.50, 0.01 }, - { "hour ends at midnight", CostWindow.Hour, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.50, 0.01 }, - { "hour ends on DST spring forward", CostWindow.Hour, new DateTime(2026, 3, 29, 2, 59, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.50, 0.01 }, - { "hour ends on DST fall back", CostWindow.Hour, new DateTime(2026, 10, 25, 2, 59, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.50, 0.01 }, - { "day changes", CostWindow.Day, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 5.00, 0.01 }, - { "day changes at month end", CostWindow.Day, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 5.00, 0.01 }, - { "day changes at year end", CostWindow.Day, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 5.00, 0.01 }, - { "month changes", CostWindow.Month, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 100.00, 0.01 }, - { "year changes", CostWindow.Month, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 100.00, 0.01 }, - { "month changes on leap day", CostWindow.Month, new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), 100.00, 0.01 } + { + "15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), + new DateTime(2026, 3, 17, 10, 15, 0), 0.10, 0.02 + }, + { + "15 minute slot ends across the hour", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 45, 0), + new DateTime(2026, 3, 17, 11, 0, 0), 0.10, 0.02 + }, + { + "15 minute slot ends at midnight", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 23, 45, 0), + new DateTime(2026, 3, 18, 0, 0, 0), 0.10, 0.02 + }, + { + "15 minute slot ends on DST spring forward", CostWindow.FifteenMinutes, new DateTime(2026, 3, 29, 2, 45, 0), + new DateTime(2026, 3, 29, 3, 0, 0), 0.10, 0.02 + }, + { + "15 minute slot ends on DST fall back", CostWindow.FifteenMinutes, new DateTime(2026, 10, 25, 2, 45, 0), + new DateTime(2026, 10, 25, 3, 0, 0), 0.10, 0.02 + }, + { + "hour ends", CostWindow.Hour, new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 0, 0), + 0.50, 0.01 + }, + { + "hour ends at midnight", CostWindow.Hour, new DateTime(2026, 3, 17, 23, 59, 0), + new DateTime(2026, 3, 18, 0, 0, 0), 0.50, 0.01 + }, + { + "hour ends on DST spring forward", CostWindow.Hour, new DateTime(2026, 3, 29, 2, 59, 0), + new DateTime(2026, 3, 29, 3, 0, 0), 0.50, 0.01 + }, + { + "hour ends on DST fall back", CostWindow.Hour, new DateTime(2026, 10, 25, 2, 59, 0), + new DateTime(2026, 10, 25, 3, 0, 0), 0.50, 0.01 + }, + { + "day changes", CostWindow.Day, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), + 5.00, 0.01 + }, + { + "day changes at month end", CostWindow.Day, new DateTime(2026, 3, 31, 23, 59, 0), + new DateTime(2026, 4, 1, 0, 0, 0), 5.00, 0.01 + }, + { + "day changes at year end", CostWindow.Day, new DateTime(2026, 12, 31, 23, 59, 0), + new DateTime(2027, 1, 1, 0, 0, 0), 5.00, 0.01 + }, + { + "month changes", CostWindow.Month, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), + 100.00, 0.01 + }, + { + "year changes", CostWindow.Month, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), + 100.00, 0.01 + }, + { + "month changes on leap day", CostWindow.Month, new DateTime(2028, 2, 29, 23, 59, 0), + new DateTime(2028, 3, 1, 0, 0, 0), 100.00, 0.01 + } }; [Theory] @@ -251,7 +347,9 @@ public class CostAccumulatorTests public static TheoryData HourBoundaryCases => new() { { "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false }, - { "same hour, later minute", new DateTime(2026, 3, 17, 10, 10, 0), new DateTime(2026, 3, 17, 10, 11, 0), false }, + { + "same hour, later minute", new DateTime(2026, 3, 17, 10, 10, 0), new DateTime(2026, 3, 17, 10, 11, 0), false + }, { "same hour, last minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 59, 59), false }, { "next hour", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 11, 0, 0), true }, { "next hour, late minute", new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 59, 0), true }, @@ -292,7 +390,10 @@ public class CostAccumulatorTests { "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 }, { "next month", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true }, - { "clock moved into previous month", new DateTime(2026, 4, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 0), true }, + { + "clock moved into previous month", new DateTime(2026, 4, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 0), + true + }, { "year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true }, { "leap day rollover", new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), true } }; @@ -305,55 +406,4 @@ public class CostAccumulatorTests } #endregion - - #region Thread safety - - [Fact] - public async Task AddCost_ConcurrentAccess_ShouldNotLoseData() - { - // Arrange - var now = PowerMonitorTestData.FixedNow; - var sut = new CostAccumulator(now); - const double incrementPerCall = 0.001; - const int callsPerThread = 1000; - const int threadCount = 10; - - // Act - var tasks = Enumerable.Range(0, threadCount) - .Select(_ => Task.Run(() => - { - for (var i = 0; i < callsPerThread; i++) - { - sut.AddCost(incrementPerCall, now.AddSeconds(1)); - } - })) - .ToArray(); - - await Task.WhenAll(tasks); - - // Assert - var snapshot = sut.GetSnapshot(); - const double expected = incrementPerCall * callsPerThread * threadCount; - snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001); - } - - #endregion - - private static double GetCurrent(CostSnapshot snapshot, CostWindow window) => window switch - { - CostWindow.FifteenMinutes => snapshot.Cost15Min, - CostWindow.Hour => snapshot.Cost1Hour, - CostWindow.Day => snapshot.CostDaily, - CostWindow.Month => snapshot.CostMonthly, - _ => throw new ArgumentOutOfRangeException(nameof(window)) - }; - - private static double GetPrevious(CostSnapshot snapshot, CostWindow window) => window switch - { - CostWindow.FifteenMinutes => snapshot.Previous15Min, - CostWindow.Hour => snapshot.Previous1Hour, - CostWindow.Day => snapshot.PreviousDaily, - CostWindow.Month => snapshot.PreviousMonthly, - _ => throw new ArgumentOutOfRangeException(nameof(window)) - }; -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs index 11fa2ee..16f4cfe 100644 --- a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs @@ -41,7 +41,7 @@ public class OtherPowerCalculationServiceTests string expectedDataQuality) { // Arrange - var sut = CreateSut(smoothingWindowSize: 1); + var sut = CreateSut(1); var devices = deviceWatts .Select((watts, index) => (entityId: $"sensor.device{index}_power", watts)) .ToDictionary(entry => entry.entityId, entry => entry.watts); @@ -62,7 +62,7 @@ public class OtherPowerCalculationServiceTests public void Calculate_ShouldIncludeAllDeviceReadingsInResult() { // Arrange - var sut = CreateSut(smoothingWindowSize: 1); + var sut = CreateSut(1); var devices = PowerMonitorTestData.CreateCostDeviceReadings(); // Act @@ -78,7 +78,7 @@ public class OtherPowerCalculationServiceTests public void Calculate_ShouldCopyDeviceReadingsInsteadOfAliasingThem() { // Arrange - var sut = CreateSut(smoothingWindowSize: 1); + var sut = CreateSut(1); var devices = new Dictionary { ["sensor.tv_power"] = 100.0 }; // Act @@ -98,7 +98,7 @@ public class OtherPowerCalculationServiceTests public void Calculate_FirstSample_ShouldReturnRawValueWithoutSmoothing() { // Arrange - var sut = CreateSut(smoothingWindowSize: 10); + var sut = CreateSut(); // Act var result = sut.Calculate(341.97, new Dictionary()); @@ -111,7 +111,7 @@ public class OtherPowerCalculationServiceTests public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage() { // Arrange - var sut = CreateSut(smoothingWindowSize: 4); + var sut = CreateSut(4); // Act var result1 = sut.Calculate(341.97, new Dictionary()); @@ -127,7 +127,7 @@ public class OtherPowerCalculationServiceTests public void Calculate_WithSmoothingWindowOfOne_ShouldFollowRawValueExactly() { // Arrange - alpha becomes 1, so the previous value has no influence. - var sut = CreateSut(smoothingWindowSize: 1); + var sut = CreateSut(1); // Act sut.Calculate(500.0, new Dictionary()); @@ -141,7 +141,7 @@ public class OtherPowerCalculationServiceTests public void Calculate_ShouldDampenSingleSpike() { // Arrange - var sut = CreateSut(smoothingWindowSize: 10); + var sut = CreateSut(); sut.Calculate(100.0, new Dictionary()); // Act @@ -166,10 +166,7 @@ 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); @@ -179,7 +176,7 @@ public class OtherPowerCalculationServiceTests public void Calculate_WithGeneratedSeries_ShouldNeverOvershootTheInputRange() { // Arrange - var sut = CreateSut(smoothingWindowSize: 5); + var sut = CreateSut(5); var samples = PowerMonitorTestData.CreatePowerSampleSeries(50); // Act @@ -198,7 +195,7 @@ public class OtherPowerCalculationServiceTests public void Reset_ShouldClearSmoothedState() { // Arrange - var sut = CreateSut(smoothingWindowSize: 10); + var sut = CreateSut(); sut.Calculate(341.97, new Dictionary()); sut.Calculate(341.97, new Dictionary()); @@ -214,7 +211,7 @@ public class OtherPowerCalculationServiceTests public void Reset_WhenCalledBeforeAnyCalculation_ShouldKeepFirstSampleRaw() { // Arrange - var sut = CreateSut(smoothingWindowSize: 10); + var sut = CreateSut(); // Act sut.Reset(); @@ -225,4 +222,4 @@ public class OtherPowerCalculationServiceTests } #endregion -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs index f2067a8..fae838e 100644 --- a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs @@ -14,6 +14,70 @@ public class PowerCostCalculationServiceTests private readonly PowerCostCalculationService _sut = new(); + #region Snapshot defaults + + [Theory] + [InlineData(CostBucket.Total)] + [InlineData(CostBucket.Other)] + public void GetSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot(CostBucket bucket) + { + // Act + var snapshot = bucket == CostBucket.Total + ? _sut.GetTotalCostSnapshot() + : _sut.GetOtherCostSnapshot(); + + // Assert + snapshot.Cost15Min.Should().Be(0); + snapshot.Cost1Hour.Should().Be(0); + snapshot.CostDaily.Should().Be(0); + snapshot.CostMonthly.Should().Be(0); + snapshot.PartialWindow.Should().BeTrue(); + } + + #endregion + + #region Thread safety + + [Fact] + public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(); + const int callsPerThread = 100; + const int threadCount = 10; + + // 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(); + + await Task.WhenAll(tasks); + + // Assert + var total = _sut.GetTotalCostSnapshot(); + total.CostDaily.Should().BeGreaterThan(0); + + var devices = _sut.GetAllDeviceCostSnapshots(); + devices.Should().HaveCount(2); + } + + #endregion + + private static double ExpectedCost( + double powerWatts, + double pricePerKwh, + int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) + { + return powerWatts / PowerMonitorConsts.WattsPerKilowatt + * pricePerKwh + * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); + } + #region CalculateCostIncrement public static TheoryData CostIncrementCases => new() @@ -57,15 +121,14 @@ public class PowerCostCalculationServiceTests // Act var costs = samples - .Select(watts => PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds)) + .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 @@ -80,11 +143,14 @@ public class PowerCostCalculationServiceTests var result = PowerMonitorTestData.CreateCalculation(); // Act - _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, + now); // Assert - var expectedTotal = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); - var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, PowerMonitorTestData.DefaultPricePerKwh); + var expectedTotal = + ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, + PowerMonitorTestData.DefaultPricePerKwh); _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12); _sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12); @@ -101,7 +167,8 @@ public class PowerCostCalculationServiceTests var result = PowerMonitorTestData.CreateCalculation(); // Act - _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, + now); // Assert var snapshot = _sut.GetDeviceCostSnapshot(entityId); @@ -119,7 +186,8 @@ public class PowerCostCalculationServiceTests var result = PowerMonitorTestData.CreateCalculation(); // Act - _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, + now); // Assert var total = _sut.GetTotalCostSnapshot(); @@ -157,7 +225,8 @@ public class PowerCostCalculationServiceTests _sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now); _sut.GetAllDeviceCostSnapshots().Should().HaveCount(1); - _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15)); + _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, + now.AddSeconds(15)); // Assert _sut.GetAllDeviceCostSnapshots().Should().HaveCount(2); @@ -202,9 +271,9 @@ public class PowerCostCalculationServiceTests // Arrange var now = PowerMonitorTestData.FixedNow; var result = PowerMonitorTestData.CreateCalculation( - totalWatts: 0, - smoothedOtherWatts: 0, - deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0))); + 0, + 0, + PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0))); // Act _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); @@ -321,9 +390,9 @@ public class PowerCostCalculationServiceTests for (var slot = 0; slot < timestamps.Count; slot++) { var result = PowerMonitorTestData.CreateCalculation( - totalWatts: wattSamples[slot], - smoothedOtherWatts: wattSamples[slot] / 2, - deviceReadings: new Dictionary()); + wattSamples[slot], + wattSamples[slot] / 2, + new Dictionary()); _sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]); } @@ -348,9 +417,9 @@ public class PowerCostCalculationServiceTests { var watts = 500.0 + start.Hour * 125.0; var result = PowerMonitorTestData.CreateCalculation( - totalWatts: watts, - smoothedOtherWatts: watts / 4, - deviceReadings: 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)); } @@ -407,7 +476,8 @@ public class PowerCostCalculationServiceTests // Assert _sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh); _sut.PriceSource.Should().Be("live"); - var expected = 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + var expected = + 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12); } @@ -486,68 +556,4 @@ public class PowerCostCalculationServiceTests } #endregion - - #region Snapshot defaults - - [Theory] - [InlineData(CostBucket.Total)] - [InlineData(CostBucket.Other)] - public void GetSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot(CostBucket bucket) - { - // Act - var snapshot = bucket == CostBucket.Total - ? _sut.GetTotalCostSnapshot() - : _sut.GetOtherCostSnapshot(); - - // Assert - snapshot.Cost15Min.Should().Be(0); - snapshot.Cost1Hour.Should().Be(0); - snapshot.CostDaily.Should().Be(0); - snapshot.CostMonthly.Should().Be(0); - snapshot.PartialWindow.Should().BeTrue(); - } - - #endregion - - #region Thread safety - - [Fact] - public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData() - { - // Arrange - var now = PowerMonitorTestData.FixedNow; - var result = PowerMonitorTestData.CreateCalculation(); - const int callsPerThread = 100; - const int threadCount = 10; - - // 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(); - - await Task.WhenAll(tasks); - - // Assert - var total = _sut.GetTotalCostSnapshot(); - total.CostDaily.Should().BeGreaterThan(0); - - var devices = _sut.GetAllDeviceCostSnapshots(); - devices.Should().HaveCount(2); - } - - #endregion - - private static double ExpectedCost( - double powerWatts, - double pricePerKwh, - int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) => - powerWatts / PowerMonitorConsts.WattsPerKilowatt - * pricePerKwh - * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs index 6a56e55..c620a68 100644 --- a/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs @@ -18,40 +18,52 @@ public class PowerLimitEnforcementServiceTests private readonly Mock _haContextMock = new(); private readonly Mock> _loggerMock = new(); - private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow); private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions(); + private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow); - private PowerLimitEnforcementService CreateSut() => - new( + private PowerLimitEnforcementService CreateSut() + { + return new PowerLimitEnforcementService( _haContextMock.Object, _loggerMock.Object, Options.Create(_options), _timeProvider); + } - private void VerifyNoServiceCalls() => + private void VerifyNoServiceCalls() + { _haContextMock.Verify( x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } - private void VerifyTurnOff(string entityId, int expectedCalls) => + 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)); + } - private void VerifyTurnOn(string entityId, int 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)); + } - private void VerifyNotificationCreated(int expectedCalls) => + private void VerifyNotificationCreated(int expectedCalls) + { _haContextMock.Verify( x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), Times.Exactly(expectedCalls)); + } - private void VerifyNotificationDismissed(int expectedCalls) => + private void VerifyNotificationDismissed(int expectedCalls) + { _haContextMock.Verify( x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), Times.Exactly(expectedCalls)); + } #region EnforceLimit @@ -120,7 +132,8 @@ 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())) + .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(); @@ -131,7 +144,8 @@ 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); } @@ -253,7 +267,8 @@ public class PowerLimitEnforcementServiceTests [InlineData(30, true)] [InlineData(31, true)] [InlineData(600, true)] - public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, bool expectedLimitActive) + public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, + bool expectedLimitActive) { // Arrange var sut = CreateSut(); @@ -435,4 +450,4 @@ public class PowerLimitEnforcementServiceTests } #endregion -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj b/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj index 66b8ebf..7736ec6 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj +++ b/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj @@ -1,35 +1,35 @@ - - net10.0 - enable - enable - false - + + net10.0 + enable + enable + false + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + - - - + + + - - - - + + + + diff --git a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs index 8819e68..f272387 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs @@ -33,13 +33,65 @@ public class PowerMonitorEntityServiceTests public PowerMonitorEntityServiceTests() { var loggerMock = new Mock>(); - _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())).Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())).Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())).Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())).Returns(Task.CompletedTask); _sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object); } + #region GetDeviceCostEntityIds + + [Theory] + [InlineData("sonoff_abc")] + [InlineData("tv")] + [InlineData("akvariumas")] + public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName) + { + // Act + var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList(); + + // Assert + result.Should().HaveCount(4); + string[] expectedEntityIds = + [ + $"sensor.powermonitor_{deviceName}_cost_15min", + $"sensor.powermonitor_{deviceName}_cost_1h", + $"sensor.powermonitor_{deviceName}_cost_daily", + $"sensor.powermonitor_{deviceName}_cost_monthly" + ]; + result.Should().BeEquivalentTo(expectedEntityIds); + } + + #endregion + + #region CreateDeviceEntitiesAsync + + [Theory] + [InlineData(0, 0)] + [InlineData(1, 4)] + [InlineData(2, 8)] + [InlineData(5, 20)] + public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates) + { + // Arrange + var sensors = Enumerable.Range(0, sensorCount) + .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)); + } + + #endregion + #region GetSystemEntitiesList [Fact] @@ -159,31 +211,6 @@ public class PowerMonitorEntityServiceTests #endregion - #region GetDeviceCostEntityIds - - [Theory] - [InlineData("sonoff_abc")] - [InlineData("tv")] - [InlineData("akvariumas")] - public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName) - { - // Act - var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList(); - - // Assert - result.Should().HaveCount(4); - string[] expectedEntityIds = - [ - $"sensor.powermonitor_{deviceName}_cost_15min", - $"sensor.powermonitor_{deviceName}_cost_1h", - $"sensor.powermonitor_{deviceName}_cost_daily", - $"sensor.powermonitor_{deviceName}_cost_monthly" - ]; - result.Should().BeEquivalentTo(expectedEntityIds); - } - - #endregion - #region CreateSystemEntitiesAsync [Fact] @@ -201,7 +228,8 @@ 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")))) + .Setup(em => + em.CreateEntityAsync(It.Is(entity => entity.Identifier.EndsWith("_cost_1h")))) .ThrowsAsync(new InvalidOperationException("Entity creation failed")); // Act @@ -213,29 +241,6 @@ public class PowerMonitorEntityServiceTests #endregion - #region CreateDeviceEntitiesAsync - - [Theory] - [InlineData(0, 0)] - [InlineData(1, 4)] - [InlineData(2, 8)] - [InlineData(5, 20)] - public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates) - { - // Arrange - var sensors = Enumerable.Range(0, sensorCount) - .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)); - } - - #endregion - #region ResetEntitiesAsync [Theory] @@ -299,7 +304,8 @@ public class PowerMonitorEntityServiceTests await _sut.RemoveSystemEntitiesAsync(); // Assert - _entityManagerMock.Verify(em => em.RemoveEntity(It.Is(id => SystemEntityIds.Contains(id))), Times.Exactly(14)); + _entityManagerMock.Verify(em => em.RemoveEntity(It.Is(id => SystemEntityIds.Contains(id))), + Times.Exactly(14)); } [Fact] @@ -399,11 +405,9 @@ public class PowerMonitorEntityServiceTests // Assert foreach (var window in new[] { "15min", "1h", "daily", "monthly" }) - { _entityManagerMock.Verify( em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny()), Times.Once); - } } [Theory] @@ -412,13 +416,14 @@ public class PowerMonitorEntityServiceTests public async Task UpdateEntitiesAsync_ShouldProjectAnomalyState(bool isAnomaly, string expectedState) { // Arrange - var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly: isAnomaly); + var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly); // Act await _sut.UpdateEntitiesAsync(context); // Assert - _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState), + Times.Once); } [Theory] @@ -450,7 +455,8 @@ 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); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"), + Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once); } @@ -469,7 +475,8 @@ 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); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny()), + Times.Once); } #endregion @@ -513,7 +520,7 @@ public class PowerMonitorEntityServiceTests public static TheoryData> CancelledOperations() { var data = new TheoryData>(); - var cancelled = new CancellationToken(canceled: true); + var cancelled = new CancellationToken(true); List sensors = [PowerMonitorTestData.CreateSensor("sensor.tv_power")]; var context = PowerMonitorTestData.CreateUpdateContext(); @@ -545,4 +552,4 @@ public class PowerMonitorEntityServiceTests } #endregion -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs index 884162c..85e7c2e 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs @@ -6,6 +6,13 @@ namespace PowerMonitor.Manager.Tests; public class PowerMonitorOptionsTests { + public static TheoryData CollectionProperties => + [ + nameof(PowerMonitorOptions.ExcludedSensorPatterns), + nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds), + nameof(PowerMonitorOptions.PauseAndRestoreEntityIds) + ]; + [Theory] [InlineData(nameof(PowerMonitorOptions.Enabled), false)] [InlineData(nameof(PowerMonitorOptions.MainMeterEntityId), "")] @@ -31,13 +38,6 @@ public class PowerMonitorOptionsTests actual.Should().Be(expected); } - public static TheoryData CollectionProperties => - [ - nameof(PowerMonitorOptions.ExcludedSensorPatterns), - nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds), - nameof(PowerMonitorOptions.PauseAndRestoreEntityIds) - ]; - [Theory] [MemberData(nameof(CollectionProperties))] public void Defaults_ShouldExposeEmptyCollection(string propertyName) @@ -96,4 +96,4 @@ public class PowerMonitorOptionsTests { PowerMonitorOptions.SectionName.Should().Be("PowerMonitor"); } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs b/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs index 90a059e..3f2d236 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs @@ -7,9 +7,9 @@ using PowerMonitorManager.Models.Consts; namespace PowerMonitor.Manager.Tests; /// -/// Shared, deterministic datasets and builders used by the PowerMonitor tests. -/// Keeping the builders and generated series here avoids copy-pasted setup and -/// hard-coded clocks across test classes. +/// Shared, deterministic datasets and builders used by the PowerMonitor tests. +/// Keeping the builders and generated series here avoids copy-pasted setup and +/// hard-coded clocks across test classes. /// internal static class PowerMonitorTestData { @@ -28,30 +28,38 @@ internal static class PowerMonitorTestData public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero); /// - /// Two-device reading set used by the cost calculation tests. + /// Two-device reading set used by the cost calculation tests. /// - public static IReadOnlyDictionary CreateCostDeviceReadings() => new Dictionary + public static IReadOnlyDictionary CreateCostDeviceReadings() { - ["sensor.sonoff_100215c534_power"] = 101.0, - ["sensor.sonoff_10018909cb_power"] = 109.93 - }; + return new Dictionary + { + ["sensor.sonoff_100215c534_power"] = 101.0, + ["sensor.sonoff_10018909cb_power"] = 109.93 + }; + } /// - /// Realistic seven-device reading set used by the entity projection tests. + /// Realistic seven-device reading set used by the entity projection tests. /// - private static Dictionary CreateDeviceReadings() => new() + private static Dictionary CreateDeviceReadings() { - ["sensor.sonoff_100215c534_power"] = 8.55, - ["sensor.sonoff_10018909cb_power"] = 36.93, - ["sensor.tv_power"] = 101.0, - ["sensor.akvariumas_power"] = 21.0, - ["sensor.sonoff_1002230a48_power"] = 20.06, - ["sensor.temp_power"] = 14.0, - ["sensor.balkony_laps_power"] = 9.39 - }; + return new Dictionary + { + ["sensor.sonoff_100215c534_power"] = 8.55, + ["sensor.sonoff_10018909cb_power"] = 36.93, + ["sensor.tv_power"] = 101.0, + ["sensor.akvariumas_power"] = 21.0, + ["sensor.sonoff_1002230a48_power"] = 20.06, + ["sensor.temp_power"] = 14.0, + ["sensor.balkony_laps_power"] = 9.39 + }; + } - public static IReadOnlyDictionary CreateReadings(params (string EntityId, double Watts)[] readings) => - readings.ToDictionary(r => r.EntityId, r => r.Watts); + public static IReadOnlyDictionary CreateReadings(params (string EntityId, double Watts)[] readings) + { + return readings.ToDictionary(r => r.EntityId, r => r.Watts); + } public static PowerCalculationResult CreateCalculation( double totalWatts = DefaultTotalWatts, @@ -77,14 +85,17 @@ internal static class PowerMonitorTestData double cost1Hour = 0.004, double costDaily = 0.03, double costMonthly = 0.9, - bool partialWindow = true) => new() + bool partialWindow = true) { - Cost15Min = cost15Min, - Cost1Hour = cost1Hour, - CostDaily = costDaily, - CostMonthly = costMonthly, - PartialWindow = partialWindow - }; + return new CostSnapshot + { + Cost15Min = cost15Min, + Cost1Hour = cost1Hour, + CostDaily = costDaily, + CostMonthly = costMonthly, + PartialWindow = partialWindow + }; + } public static PowerUpdateContext CreateUpdateContext( bool isAnomaly = false, @@ -98,10 +109,10 @@ internal static class PowerMonitorTestData var readings = deviceReadings ?? CreateDeviceReadings(); var deviceCosts = readings .Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot( - cost15Min: 0.0005 * (index + 1), - cost1Hour: 0.002 * (index + 1), - costDaily: 0.03 * (index + 1), - costMonthly: 0.9 * (index + 1)))) + 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 @@ -135,8 +146,9 @@ internal static class PowerMonitorTestData return options; } - public static PowerMonitorOptions CreateLimitEnforcementOptions(Action? configure = null) => - CreateOptions(options => + public static PowerMonitorOptions CreateLimitEnforcementOptions(Action? configure = null) + { + return CreateOptions(options => { options.EnforceLimitEnabled = true; options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts; @@ -146,18 +158,22 @@ internal static class PowerMonitorTestData options.PauseAndRestoreEntityIds = [AutoManagementEntityId]; configure?.Invoke(options); }); + } public static PowerSensorInfo CreateSensor( string entityId, string? friendlyName = null, string? deviceName = null, - string unitOfMeasurement = PowerMonitorConsts.WattUnit) => new() + string unitOfMeasurement = PowerMonitorConsts.WattUnit) { - EntityId = entityId, - FriendlyName = friendlyName ?? entityId, - DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId), - UnitOfMeasurement = unitOfMeasurement - }; + return new PowerSensorInfo + { + EntityId = entityId, + FriendlyName = friendlyName ?? entityId, + DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId), + UnitOfMeasurement = unitOfMeasurement + }; + } public static JsonElement CreateAttributesJson( string? deviceClass, @@ -166,42 +182,39 @@ 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); } /// - /// Deterministic, strictly positive and monotonically increasing power samples - /// used by the looping scenarios. + /// Deterministic, strictly positive and monotonically increasing power samples + /// used by the looping scenarios. /// - public static IReadOnlyList CreatePowerSampleSeries(int count = 96) => - [ - .. Enumerable.Range(0, count) - .Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2)) - ]; + public static IReadOnlyList CreatePowerSampleSeries(int count = 96) + { + return + [ + .. Enumerable.Range(0, count) + .Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2)) + ]; + } /// - /// Deterministic, strictly positive hourly tariff series (EUR/kWh). + /// Deterministic, strictly positive hourly tariff series (EUR/kWh). /// - private static IReadOnlyList CreateTariffPriceSeries(int count = 24) => - [ - .. Enumerable.Range(0, count) - .Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4)) - ]; + private static IReadOnlyList CreateTariffPriceSeries(int count = 24) + { + return + [ + .. Enumerable.Range(0, count) + .Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4)) + ]; + } public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart) { @@ -214,9 +227,12 @@ internal static class PowerMonitorTestData ]; } - public static IReadOnlyList CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) => - [ - .. Enumerable.Range(0, count) - .Select(i => start.AddMinutes(i * intervalMinutes)) - ]; -} + public static IReadOnlyList CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) + { + return + [ + .. Enumerable.Range(0, count) + .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 475270a..f5632f0 100644 --- a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs @@ -37,15 +37,63 @@ public class PowerSensorDiscoveryServiceTests } private void SetupEntities( - params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) => + params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) + { _haContextMock .Setup(h => h.GetAllEntities()) - .Returns([.. entities.Select(entity => SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))]); + .Returns([ + .. entities.Select(entity => + SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName)) + ]); + } - private void SetupEntitiesWithoutState(params string[] entityIds) => + private void SetupEntitiesWithoutState(params string[] entityIds) + { _haContextMock .Setup(h => h.GetAllEntities()) .Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]); + } + + #region ExtractDeviceName + + [Theory] + [InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")] + [InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")] + [InlineData("sensor.tv_power", "tv")] + [InlineData("sensor.temp_power", "temp")] + [InlineData("sensor.power", "power")] + [InlineData("sensor.TV_POWER", "TV")] + [InlineData("sensor.boiler_output_power", "boiler_output")] + [InlineData("sensor.temperature", "temperature")] + [InlineData("tv_power", "tv")] + [InlineData("sensor.", "")] + public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected) + { + PowerSensorDiscoveryService.ExtractDeviceName(entityId).Should().Be(expected); + } + + #endregion + + #region GlobToRegex + + [Theory] + [InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)] + [InlineData("sensor.nordpool_*", "sensor.tv_power", false)] + [InlineData("sensor.nordpool_*", "SENSOR.NORDPOOL_CURRENT_PRICE", true)] + [InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)] + [InlineData("*_power", "sensor.sonoff_100215c534_power", true)] + [InlineData("*_power", "sensor.sonoff_100215c534_energy", false)] + [InlineData("sensor.tv_power", "sensor.tv_power", true)] + [InlineData("sensor.tv_power", "sensor.tv_power_2", false)] + [InlineData("sensor.?.power", "sensor.a.power", false)] + [InlineData("*", "anything at all", true)] + public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected) + { + var regex = PowerSensorDiscoveryService.GlobToRegex(glob); + regex.IsMatch(input).Should().Be(expected); + } + + #endregion #region Discovery @@ -96,7 +144,7 @@ public class PowerSensorDiscoveryServiceTests (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), ("sensor.tv_power", "power", "W", "TV Power")); - var sut = CreateSut(mainMeterEntityId: string.Empty); + var sut = CreateSut(string.Empty); // Act var result = sut.DiscoverDeviceSensors(); @@ -271,47 +319,6 @@ public class PowerSensorDiscoveryServiceTests #endregion - #region ExtractDeviceName - - [Theory] - [InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")] - [InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")] - [InlineData("sensor.tv_power", "tv")] - [InlineData("sensor.temp_power", "temp")] - [InlineData("sensor.power", "power")] - [InlineData("sensor.TV_POWER", "TV")] - [InlineData("sensor.boiler_output_power", "boiler_output")] - [InlineData("sensor.temperature", "temperature")] - [InlineData("tv_power", "tv")] - [InlineData("sensor.", "")] - public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected) - { - PowerSensorDiscoveryService.ExtractDeviceName(entityId).Should().Be(expected); - } - - #endregion - - #region GlobToRegex - - [Theory] - [InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)] - [InlineData("sensor.nordpool_*", "sensor.tv_power", false)] - [InlineData("sensor.nordpool_*", "SENSOR.NORDPOOL_CURRENT_PRICE", true)] - [InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)] - [InlineData("*_power", "sensor.sonoff_100215c534_power", true)] - [InlineData("*_power", "sensor.sonoff_100215c534_energy", false)] - [InlineData("sensor.tv_power", "sensor.tv_power", true)] - [InlineData("sensor.tv_power", "sensor.tv_power_2", false)] - [InlineData("sensor.?.power", "sensor.a.power", false)] - [InlineData("*", "anything at all", true)] - public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected) - { - var regex = PowerSensorDiscoveryService.GlobToRegex(glob); - regex.IsMatch(input).Should().Be(expected); - } - - #endregion - #region IsPowerSensor [Theory] @@ -359,4 +366,4 @@ public class PowerSensorDiscoveryServiceTests } #endregion -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs b/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs index e971889..e24afef 100644 --- a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs +++ b/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs @@ -5,4 +5,4 @@ namespace PowerMonitorManager.Interface; public interface IOtherPowerCalculationService { PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary deviceReadings); -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs b/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs index ae2ffaf..820d046 100644 --- a/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs +++ b/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs @@ -4,10 +4,10 @@ namespace PowerMonitorManager.Interface; public interface IPowerCostCalculationService { + double LastKnownPrice { get; } + string PriceSource { get; } void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now); CostSnapshot GetTotalCostSnapshot(); CostSnapshot GetOtherCostSnapshot(); IReadOnlyDictionary GetAllDeviceCostSnapshots(); - double LastKnownPrice { get; } - string PriceSource { get; } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs b/PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs index 26b80b1..a9e5ac5 100644 --- a/PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs +++ b/PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs @@ -2,11 +2,10 @@ namespace PowerMonitorManager.Interface; public interface IPowerLimitEnforcementService { + bool IsLimitActive { get; } void EnforceLimit(double currentPowerWatts); void TriggerLimitBreach(); void ResetLimitBreach(); - - bool IsLimitActive { get; } } \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs b/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs index c2c2beb..0f0f0e7 100644 --- a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs @@ -6,9 +6,14 @@ namespace PowerMonitorManager.Interface; public interface IPowerMonitorEntityService { Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default); - Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, CancellationToken cancellationToken = default); + + Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, + 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); -} + + Task RemoveDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerNotificationService.cs b/PowerMonitor.Manager/Interface/IPowerNotificationService.cs index 244ae91..450f3a4 100644 --- a/PowerMonitor.Manager/Interface/IPowerNotificationService.cs +++ b/PowerMonitor.Manager/Interface/IPowerNotificationService.cs @@ -5,4 +5,4 @@ public interface IPowerNotificationService void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts); void DismissHighPowerNotification(); -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs b/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs index d6f91ab..0535d54 100644 --- a/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs +++ b/PowerMonitor.Manager/Interface/IPowerSensorDiscoveryService.cs @@ -4,6 +4,6 @@ namespace PowerMonitorManager.Interface; public interface IPowerSensorDiscoveryService { - IReadOnlyList DiscoverDeviceSensors(); IReadOnlyList CurrentDeviceSensors { get; } -} + IReadOnlyList DiscoverDeviceSensors(); +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs b/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs index ec1e8cd..a5ecf7d 100644 --- a/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs +++ b/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs @@ -34,4 +34,4 @@ public static class PowerMonitorConsts public const string SwitchDomain = "switch"; public const string TurnOnService = "turn_on"; public const string TurnOffService = "turn_off"; -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Models/CostAccumulator.cs b/PowerMonitor.Manager/Models/CostAccumulator.cs index 072feac..c1d7190 100644 --- a/PowerMonitor.Manager/Models/CostAccumulator.cs +++ b/PowerMonitor.Manager/Models/CostAccumulator.cs @@ -9,11 +9,6 @@ public sealed class CostAccumulator(DateTime now) private double _costDaily; private double _costMonthly; - private double _previous15Min; - private double _previous1Hour; - private double _previousDaily; - private double _previousMonthly; - private DateTime _last15MinReset = now; private DateTime _last1HourReset = now; private DateTime _lastDailyReset = now; @@ -21,6 +16,11 @@ public sealed class CostAccumulator(DateTime now) private bool _partialWindow = true; + private double _previous15Min; + private double _previous1Hour; + private double _previousDaily; + private double _previousMonthly; + public void AddCost(double costIncrement, DateTime now) { lock (_lock) @@ -77,10 +77,7 @@ public sealed class CostAccumulator(DateTime now) _lastDailyReset = now; } - if (!IsNewMonthWindow(now, _lastMonthlyReset)) - { - return; - } + if (!IsNewMonthWindow(now, _lastMonthlyReset)) return; _previousMonthly = _costMonthly; _costMonthly = 0; @@ -108,4 +105,4 @@ public sealed class CostAccumulator(DateTime now) { return now.Year != lastReset.Year || now.Month != lastReset.Month; } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Models/CostSnapshot.cs b/PowerMonitor.Manager/Models/CostSnapshot.cs index b4d6d1d..0c1963e 100644 --- a/PowerMonitor.Manager/Models/CostSnapshot.cs +++ b/PowerMonitor.Manager/Models/CostSnapshot.cs @@ -11,4 +11,4 @@ public sealed class CostSnapshot public double PreviousDaily { get; init; } public double PreviousMonthly { get; init; } public bool PartialWindow { get; init; } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Models/PowerCalculationResult.cs b/PowerMonitor.Manager/Models/PowerCalculationResult.cs index 4d9b6e3..93d7637 100644 --- a/PowerMonitor.Manager/Models/PowerCalculationResult.cs +++ b/PowerMonitor.Manager/Models/PowerCalculationResult.cs @@ -8,4 +8,4 @@ public sealed class PowerCalculationResult public double SmoothedOtherPowerWatts { get; init; } public string DataQuality { get; init; } = "ok"; public IReadOnlyDictionary DevicePowerReadings { get; init; } = new Dictionary(); -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs index 4ecd319..fa01fe5 100644 --- a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs +++ b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs @@ -20,4 +20,4 @@ public sealed class PowerMonitorOptions public int LimitCooldownSeconds { get; set; } = PowerMonitorConsts.DefaultLimitCooldownSeconds; public string[] EnforceSwitchOffEntityIds { get; set; } = []; public string[] PauseAndRestoreEntityIds { get; set; } = []; -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Models/PowerUpdateContext.cs b/PowerMonitor.Manager/Models/PowerUpdateContext.cs index dd43388..11056af 100644 --- a/PowerMonitor.Manager/Models/PowerUpdateContext.cs +++ b/PowerMonitor.Manager/Models/PowerUpdateContext.cs @@ -15,4 +15,4 @@ public sealed class PowerUpdateContext public required int TrackedSensorCount { get; init; } public required IReadOnlyList DegradedSensors { get; init; } public required string SystemStatus { get; init; } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/OtherPowerCalculationService.cs b/PowerMonitor.Manager/OtherPowerCalculationService.cs index 5d6ec32..344ba08 100644 --- a/PowerMonitor.Manager/OtherPowerCalculationService.cs +++ b/PowerMonitor.Manager/OtherPowerCalculationService.cs @@ -7,8 +7,8 @@ namespace PowerMonitorManager; public sealed class OtherPowerCalculationService : IOtherPowerCalculationService { private readonly double _alpha; - private double? _previousSmoothed; private readonly Lock _lock = new(); + private double? _previousSmoothed; public OtherPowerCalculationService(IOptions options) { @@ -55,4 +55,4 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService _previousSmoothed = null; } } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerCostCalculationService.cs b/PowerMonitor.Manager/PowerCostCalculationService.cs index 1e099e4..01a58a8 100644 --- a/PowerMonitor.Manager/PowerCostCalculationService.cs +++ b/PowerMonitor.Manager/PowerCostCalculationService.cs @@ -7,35 +7,39 @@ namespace PowerMonitorManager; public sealed class PowerCostCalculationService : IPowerCostCalculationService { - private readonly ConcurrentDictionary _deviceAccumulators = new(); - private CostAccumulator? _totalAccumulator; - private CostAccumulator? _otherAccumulator; private readonly Lock _accumulatorLock = new(); + private readonly ConcurrentDictionary _deviceAccumulators = new(); + private readonly Lock _priceLock = new(); private double _lastKnownPrice; + private CostAccumulator? _otherAccumulator; private string _priceSource = "live"; - private readonly Lock _priceLock = new(); + private CostAccumulator? _totalAccumulator; public double LastKnownPrice { - get { lock (_priceLock) { return _lastKnownPrice; } } + get + { + lock (_priceLock) + { + return _lastKnownPrice; + } + } } public string PriceSource { - get { lock (_priceLock) { return _priceSource; } } - } - - public void SetPrice(double price) - { - lock (_priceLock) + get { - _lastKnownPrice = price; - _priceSource = "stale"; + lock (_priceLock) + { + return _priceSource; + } } } - public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now) + public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, + DateTime now) { lock (_priceLock) { @@ -51,7 +55,8 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService var totalCost = CalculateCostIncrement(calculation.TotalPowerWatts, effectivePrice, pollIntervalSeconds); GetOrCreateTotalAccumulator(now).AddCost(totalCost, now); - var otherCost = CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds); + var otherCost = + CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds); GetOrCreateOtherAccumulator(now).AddCost(otherCost, now); foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings) @@ -78,13 +83,6 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService } } - public CostSnapshot GetDeviceCostSnapshot(string entityId) - { - return _deviceAccumulators.TryGetValue(entityId, out var accumulator) - ? accumulator.GetSnapshot() - : CreateEmptySnapshot(); - } - public IReadOnlyDictionary GetAllDeviceCostSnapshots() { return _deviceAccumulators.ToDictionary( @@ -92,6 +90,22 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService kvp => kvp.Value.GetSnapshot()); } + public void SetPrice(double price) + { + lock (_priceLock) + { + _lastKnownPrice = price; + _priceSource = "stale"; + } + } + + public CostSnapshot GetDeviceCostSnapshot(string entityId) + { + return _deviceAccumulators.TryGetValue(entityId, out var accumulator) + ? accumulator.GetSnapshot() + : CreateEmptySnapshot(); + } + internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds) { var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt; @@ -118,4 +132,4 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService { return new CostSnapshot { PartialWindow = true }; } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerLimitEnforcementService.cs b/PowerMonitor.Manager/PowerLimitEnforcementService.cs index bcc1a45..3670e9e 100644 --- a/PowerMonitor.Manager/PowerLimitEnforcementService.cs +++ b/PowerMonitor.Manager/PowerLimitEnforcementService.cs @@ -25,10 +25,7 @@ public sealed class PowerLimitEnforcementService( public void EnforceLimit(double currentPowerWatts) { - if (!_options.EnforceLimitEnabled) - { - return; - } + if (!_options.EnforceLimitEnabled) return; var now = timeProvider.GetUtcNow(); @@ -67,15 +64,9 @@ 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); @@ -87,10 +78,7 @@ public sealed class PowerLimitEnforcementService( private void ExecuteRecover() { - foreach (var entityId in _options.PauseAndRestoreEntityIds) - { - TurnOn(entityId); - } + foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId); DismissLimitNotification(); @@ -100,22 +88,20 @@ 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); - } + logger.LogDebug( + "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); + logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts, + _options.PowerLimitWatts); ExecuteEnforce(currentPowerWatts); } @@ -124,28 +110,23 @@ 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); + logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced", + currentPowerWatts, _options.PowerLimitWatts); _enforcedAt = now; - + return; } 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); - } + logger.LogInformation( + "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(); @@ -155,17 +136,20 @@ public sealed class PowerLimitEnforcementService( private void TurnOff(string entityId) { - haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService, ServiceTarget.FromEntity(entityId)); + haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService, + ServiceTarget.FromEntity(entityId)); } private void TurnOn(string entityId) { - haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService, ServiceTarget.FromEntity(entityId)); + haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService, + ServiceTarget.FromEntity(entityId)); } private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts) { - var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt, limitWatts / PowerMonitorConsts.WattsPerKilowatt); + var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt, + limitWatts / PowerMonitorConsts.WattsPerKilowatt); haContext.CallService( PowerMonitorConsts.PersistentNotificationDomain, diff --git a/PowerMonitor.Manager/PowerMonitor.Manager.csproj b/PowerMonitor.Manager/PowerMonitor.Manager.csproj index 9d8e692..3d3a331 100644 --- a/PowerMonitor.Manager/PowerMonitor.Manager.csproj +++ b/PowerMonitor.Manager/PowerMonitor.Manager.csproj @@ -8,20 +8,20 @@ - - <_Parameter1>PowerMonitor.Manager.Tests - + + <_Parameter1>PowerMonitor.Manager.Tests + - - - + + + - - + + diff --git a/PowerMonitor.Manager/PowerMonitorEntityService.cs b/PowerMonitor.Manager/PowerMonitorEntityService.cs index 8da663f..e16183a 100644 --- a/PowerMonitor.Manager/PowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/PowerMonitorEntityService.cs @@ -49,9 +49,7 @@ public sealed class PowerMonitorEntityService( try { if (logger.IsEnabled(LogLevel.Information)) - { logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId); - } await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); } @@ -64,7 +62,8 @@ public sealed class PowerMonitorEntityService( await Task.WhenAll(tasks).ConfigureAwait(false); } - public async Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, CancellationToken cancellationToken = default) + public async Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, + CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -74,9 +73,7 @@ public sealed class PowerMonitorEntityService( try { if (logger.IsEnabled(LogLevel.Information)) - { logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId); - } await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); } @@ -98,15 +95,23 @@ public sealed class PowerMonitorEntityService( var tasks = new List { UpdateTotalPowerAsync(context, timestamp), - UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost, "Total cost (15 min)", timestamp), - UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost, "Total cost (1h)", timestamp), - UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost, "Total cost (daily)", timestamp), - UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost, "Total cost (monthly)", timestamp), + UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost, + "Total cost (15 min)", timestamp), + UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost, + "Total cost (1h)", timestamp), + UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost, + "Total cost (daily)", timestamp), + UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost, + "Total cost (monthly)", timestamp), UpdateOtherPowerAsync(context, timestamp), - UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost, "Other cost (15 min)", timestamp), - UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost, "Other cost (1h)", timestamp), - UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost, "Other cost (daily)", timestamp), - UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost, "Other cost (monthly)", timestamp), + UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost, + "Other cost (15 min)", timestamp), + UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost, + "Other cost (1h)", timestamp), + UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost, + "Other cost (daily)", timestamp), + UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost, + "Other cost (monthly)", timestamp), UpdateAnomalyAsync(context, timestamp), UpdateStatusAsync(context, timestamp) }; @@ -114,10 +119,14 @@ 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)); - tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour, costSnapshot, $"{deviceName} cost (1h)", timestamp)); - tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily, costSnapshot, $"{deviceName} cost (daily)", timestamp)); - tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly, costSnapshot, $"{deviceName} cost (monthly)", timestamp)); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min, + costSnapshot, $"{deviceName} cost (15 min)", timestamp)); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour, + costSnapshot, $"{deviceName} cost (1h)", timestamp)); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily, + costSnapshot, $"{deviceName} cost (daily)", timestamp)); + tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly, + costSnapshot, $"{deviceName} cost (monthly)", timestamp)); } await Task.WhenAll(tasks).ConfigureAwait(false); @@ -154,9 +163,9 @@ public sealed class PowerMonitorEntityService( try { var tasks = SystemEntityIds.Select(entityManager.RemoveEntity); - + await Task.WhenAll(tasks).ConfigureAwait(false); - + logger.LogInformation("PowerMonitor system entities cleaned up"); } catch (Exception ex) @@ -166,22 +175,20 @@ public sealed class PowerMonitorEntityService( } } - public async Task RemoveDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, CancellationToken cancellationToken = default) + public async Task RemoveDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, + CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var entityIds = removedDeviceNames.SelectMany(GetDeviceCostEntityIds).ToList(); - + var tasks = entityIds.Select(async id => { try { await entityManager.RemoveEntity(id).ConfigureAwait(false); - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Entity removed: {EntityId}", id); - } + if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Entity removed: {EntityId}", id); } catch (Exception ex) { @@ -191,7 +198,7 @@ public sealed class PowerMonitorEntityService( await Task.WhenAll(tasks).ConfigureAwait(false); } - + internal static ICollection GetSystemEntitiesList() { @@ -199,7 +206,12 @@ public sealed class PowerMonitorEntityService( { new("sensor", "powermonitor_total_power", "PowerMonitor total power") { - AdditionalConfig = new { unit_of_measurement = PowerMonitorConsts.WattUnit, device_class = PowerMonitorConsts.PowerDeviceClass, state_class = PowerMonitorConsts.MeasurementStateClass } + AdditionalConfig = new + { + unit_of_measurement = PowerMonitorConsts.WattUnit, + device_class = PowerMonitorConsts.PowerDeviceClass, + state_class = PowerMonitorConsts.MeasurementStateClass + } }, CreateCostEntity("powermonitor_total_cost_15min", "PowerMonitor total cost (15 min)"), CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"), @@ -207,7 +219,12 @@ public sealed class PowerMonitorEntityService( CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"), new("sensor", "powermonitor_other_power", "PowerMonitor other power") { - AdditionalConfig = new { unit_of_measurement = PowerMonitorConsts.WattUnit, device_class = PowerMonitorConsts.PowerDeviceClass, state_class = PowerMonitorConsts.MeasurementStateClass } + AdditionalConfig = new + { + unit_of_measurement = PowerMonitorConsts.WattUnit, + device_class = PowerMonitorConsts.PowerDeviceClass, + state_class = PowerMonitorConsts.MeasurementStateClass + } }, CreateCostEntity("powermonitor_other_cost_15min", "PowerMonitor other cost (15 min)"), CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"), @@ -293,7 +310,8 @@ public sealed class PowerMonitorEntityService( }).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); @@ -360,4 +378,4 @@ public sealed class PowerMonitorEntityService( logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId); } } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index 8ee8b67..a17b325 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -15,21 +15,21 @@ namespace PowerMonitorManager; [NetDaemonApp] public sealed class PowerMonitorInit { - private readonly ILogger _logger; - private readonly IHaContext _haContext; - private readonly PowerMonitorOptions _options; - private readonly IPowerSensorDiscoveryService _discoveryService; private readonly IOtherPowerCalculationService _calculationService; private readonly IPowerCostCalculationService _costService; - private readonly IPowerMonitorEntityService _entityService; - private readonly IPowerNotificationService _notificationService; + private readonly IPowerSensorDiscoveryService _discoveryService; private readonly IPowerLimitEnforcementService _enforcementService; + private readonly IPowerMonitorEntityService _entityService; + private readonly IHaContext _haContext; + private readonly ILogger _logger; + private readonly IPowerNotificationService _notificationService; + private readonly PowerMonitorOptions _options; private readonly TimeProvider _timeProvider; + private DateTimeOffset? _anomalyStartTime; + private bool _highPowerNotificationActive; + private DateTimeOffset? _lastPollTimestamp; private int _mainMeterConsecutiveFailures; - private DateTimeOffset? _anomalyStartTime; - private DateTimeOffset? _lastPollTimestamp; - private bool _highPowerNotificationActive; public PowerMonitorInit( IHaContext haContext, @@ -99,9 +99,7 @@ public sealed class PowerMonitorInit await _entityService.CreateDeviceEntitiesAsync(sensors); if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count); - } await PollAndUpdateAsync(); } @@ -115,7 +113,7 @@ public sealed class PowerMonitorInit private IReadOnlyList GetPowerSensorEntitiesNames() { var sensors = _discoveryService.DiscoverDeviceSensors(); - + return sensors; } @@ -136,18 +134,13 @@ public sealed class PowerMonitorInit meter.StateChanges() .Subscribe(e => { - if (e.Old?.State == e.New?.State) - { - return; - } + if (e.Old?.State == e.New?.State) return; _ = PollAndUpdateAsync(); }); if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId); - } } private void SubscribeToRediscoverButton() @@ -197,20 +190,14 @@ public sealed class PowerMonitorInit { 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); - } + _logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", + newSensors.Count, added.Count, removed.Count); } catch (Exception ex) { @@ -222,11 +209,9 @@ public sealed class PowerMonitorInit { var removedNames = removed.Select(s => s.DeviceName).ToList(); await _entityService.RemoveDeviceEntitiesAsync(removedNames); - + if (_logger.IsEnabled(LogLevel.Information)) - { _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); - } } private async Task PollAndUpdateAsync() @@ -237,8 +222,9 @@ public sealed class PowerMonitorInit if (totalPower is null) { _mainMeterConsecutiveFailures++; - _logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures); - + _logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, + PowerMonitorConsts.MainMeterMaxConsecutiveFailures); + return; } @@ -302,10 +288,10 @@ public sealed class PowerMonitorInit _enforcementService.EnforceLimit(calculation.TotalPowerWatts); 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); - } + _logger.LogDebug( + "Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", + calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, + effectivePrice); } catch (Exception ex) { @@ -316,23 +302,18 @@ public sealed class PowerMonitorInit private double ReadNordPoolPrice() { var state = _haContext.GetState(NordPoolConsts.CurrentPriceEntityId); - + 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)) - { _logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State); - } - + return 0; } @@ -357,10 +338,7 @@ 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 @@ -384,10 +362,11 @@ public sealed class PowerMonitorInit if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)) { - var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase) + var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, + StringComparison.OrdinalIgnoreCase) ? value * PowerMonitorConsts.WattsPerKilowatt : value; - + readings[sensor.EntityId] = powerWatts; } else @@ -399,4 +378,4 @@ public sealed class PowerMonitorInit return (readings, degraded); } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs index 366906d..90aabaf 100644 --- a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs +++ b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs @@ -19,4 +19,4 @@ public static class PowerMonitorServiceRegistration return services; } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerNotificationService.cs b/PowerMonitor.Manager/PowerNotificationService.cs index 23e3879..6287939 100644 --- a/PowerMonitor.Manager/PowerNotificationService.cs +++ b/PowerMonitor.Manager/PowerNotificationService.cs @@ -27,7 +27,8 @@ public sealed class PowerNotificationService( notification_id = PowerMonitorConsts.HighPowerNotificationId }); - logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", currentKw, thresholdKw); + logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", + currentKw, thresholdKw); } public void DismissHighPowerNotification() @@ -51,4 +52,4 @@ public sealed class PowerNotificationService( currentKw, thresholdKw); } -} +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs index 982e651..2027375 100644 --- a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs +++ b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs @@ -13,15 +13,13 @@ namespace PowerMonitorManager; public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService { - private readonly IHaContext _haContext; - private readonly PowerMonitorOptions _options; - private readonly ILogger _logger; private readonly Regex[] _exclusionPatterns; + private readonly IHaContext _haContext; + private readonly ILogger _logger; + private readonly PowerMonitorOptions _options; private volatile IReadOnlyList _currentDeviceSensors = []; - public IReadOnlyList CurrentDeviceSensors => _currentDeviceSensors; - public PowerSensorDiscoveryService( IHaContext haContext, IOptions options, @@ -33,6 +31,8 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService _exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)]; } + public IReadOnlyList CurrentDeviceSensors => _currentDeviceSensors; + public IReadOnlyList DiscoverDeviceSensors() { var allEntities = _haContext.GetAllEntities(); @@ -53,26 +53,19 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService _currentDeviceSensors = powerSensors; if (_logger.IsEnabled(LogLevel.Information)) - { - _logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", + _logger.LogInformation( + "Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); - } return powerSensors; } 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"); @@ -117,10 +110,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService 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() @@ -132,4 +122,4 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService 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/PowerMonitor.Models.csproj b/PowerMonitor.Models/PowerMonitor.Models.csproj index fdc44f8..5121301 100644 --- a/PowerMonitor.Models/PowerMonitor.Models.csproj +++ b/PowerMonitor.Models/PowerMonitor.Models.csproj @@ -8,11 +8,11 @@ - + - + diff --git a/PowerMonitor.Models/PowerMonitorEntity.cs b/PowerMonitor.Models/PowerMonitorEntity.cs index f1a5bce..f348701 100644 --- a/PowerMonitor.Models/PowerMonitorEntity.cs +++ b/PowerMonitor.Models/PowerMonitorEntity.cs @@ -5,10 +5,6 @@ namespace PowerMonitor.Models; public class PowerMonitorEntity : EntityCreateModel { - public string Domain { get; } - public string Identifier { get; } - public string Name { get; } - public PowerMonitorEntity(string domain, string identifier, string name) { Domain = domain; @@ -22,4 +18,8 @@ public class PowerMonitorEntity : EntityCreateModel Name = Name }; } -} + + public string Domain { get; } + public string Identifier { get; } + public string Name { get; } +} \ No newline at end of file diff --git a/PowerMonitor.Models/PowerSensorInfo.cs b/PowerMonitor.Models/PowerSensorInfo.cs index ccd1fd0..1ce3bca 100644 --- a/PowerMonitor.Models/PowerSensorInfo.cs +++ b/PowerMonitor.Models/PowerSensorInfo.cs @@ -6,4 +6,4 @@ public sealed class PowerSensorInfo public required string FriendlyName { get; init; } public required string DeviceName { get; init; } public string UnitOfMeasurement { get; init; } = "W"; -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs index 0bfd39e..98a3ea3 100644 --- a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs @@ -15,8 +15,8 @@ public class ExhaustFanControlServiceTests private const string FanEntityId = "switch.exhaust_fan"; private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions(); - private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider(); private readonly Mock _haContextMock = new(); + private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider(); private DateTimeOffset Now => _timeProvider.GetUtcNow(); @@ -237,7 +237,7 @@ public class ExhaustFanControlServiceTests [InlineData(null)] public void Evaluate_WithConfiguredFanEntityId_TargetsThatExactEntity(string? entityId) { - var service = CreateService(ShowerMonitorTestData.CreateOptions(exhaustFanEntityId: entityId!)); + var service = CreateService(ShowerMonitorTestData.CreateOptions(entityId!)); service.Evaluate(ShowerState.Active, Now); @@ -264,17 +264,17 @@ public class ExhaustFanControlServiceTests { var targets = _haContextMock.Invocations .Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService) - && (string?)invocation.Arguments[0] == "switch" - && (string?)invocation.Arguments[1] == service) + && (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, + && 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 0752487..e0a3ee2 100644 --- a/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs +++ b/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs @@ -49,9 +49,7 @@ 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}"); } @@ -61,18 +59,15 @@ public class HumidityRateCalculatorTests { const double ratePerMinute = 2.5; var series = ShowerMonitorTestData.CreateLinearHumiditySeries( - startHumidity: 45.0, - ratePerMinute: ratePerMinute, - sampleCount: 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() @@ -125,4 +120,4 @@ public class HumidityRateCalculatorTests calculator.GetRatePerMinute().Should().Be(0.0); calculator.PreviousReading.Should().BeNull(); } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs index 80c5d70..aed039b 100644 --- a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs @@ -158,10 +158,7 @@ public class ShowerDetectionServiceTests 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] @@ -508,4 +505,4 @@ public class ShowerDetectionServiceTests service.Evaluate(56.0, 50.0, start.AddMinutes(12)); service.Evaluate(55.0, 50.0, start.AddMinutes(13)); } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj b/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj index 7d8480c..e9d62d4 100644 --- a/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj +++ b/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj @@ -1,35 +1,35 @@ - - net10.0 - enable - enable - false - + + net10.0 + enable + enable + false + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + - - - + + + - - - - + + + + diff --git a/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs b/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs index e0a70c6..976a260 100644 --- a/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs +++ b/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs @@ -6,21 +6,24 @@ using ShowerMonitorManager.Models; namespace ShowerMonitor.Manager.Tests; /// -/// Shared, deterministic fixtures for the shower monitor tests. -/// Keeping options, fan states and sample series here avoids copy-pasted setup -/// across test classes and keeps every timestamp independent of the wall clock. +/// Shared, deterministic fixtures for the shower monitor tests. +/// Keeping options, fan states and sample series here avoids copy-pasted setup +/// across test classes and keeps every timestamp independent of the wall clock. /// 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); - /// Creates a fake clock positioned at unless overridden. - public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) => new(start ?? BaseTimestamp); + /// Creates a fake clock positioned at unless overridden. + public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) + { + return new FakeTimeProvider(start ?? BaseTimestamp); + } /// - /// Builds monitor options from the production defaults, overriding only the - /// values a test cares about. + /// Builds monitor options from the production defaults, overriding only the + /// values a test cares about. /// public static ShowerMonitorOptions CreateOptions( string exhaustFanEntityId = ShowerMonitorConsts.ExhaustFanEntityId, @@ -37,40 +40,53 @@ internal static class ShowerMonitorTestData { ExhaustFanEntityId = exhaustFanEntityId, FanRunAfterShowerMinutes = fanRunAfterShowerMinutes - ?? (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes, + ?? (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes, SpikeRateThreshold = spikeRateThreshold, MinDifferentialHumidity = minDifferentialHumidity, PeakHumidityThreshold = peakHumidityThreshold, ConfirmationWindowMinutes = confirmationWindowMinutes, RecoveryDifferentialThreshold = recoveryDifferentialThreshold, MaxShowerDurationMinutes = maxShowerDurationMinutes - ?? (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes, + ?? (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes, RateWindowSize = rateWindowSize }; } /// Creates the HA state payload for the exhaust fan. - public static EntityState FanState(string? state) => new() { State = state }; - - /// A humidity sample with its offset from a test's base timestamp. - public readonly record struct HumiditySample(double Humidity, TimeSpan Offset); + public static EntityState FanState(string? state) + { + return new EntityState { State = state }; + } /// Builds a sample series from (humidity, offset-in-seconds) pairs. public static IReadOnlyList CreateHumiditySeries( - params (double Humidity, int OffsetSeconds)[] samples) => - [.. samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds)))]; + params (double Humidity, int OffsetSeconds)[] samples) + { + return + [ + .. samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds))) + ]; + } /// - /// Generates evenly spaced samples along a constant humidity slope, useful for - /// exercising every window size against a known rate. + /// Generates evenly spaced samples along a constant humidity slope, useful for + /// exercising every window size against a known rate. /// public static IReadOnlyList CreateLinearHumiditySeries( double startHumidity, double ratePerMinute, int sampleCount, - int intervalSeconds = 60) => - [.. Enumerable.Range(0, sampleCount) - .Select(i => new HumiditySample( - startHumidity + ratePerMinute * i * intervalSeconds / 60.0, - TimeSpan.FromSeconds(i * intervalSeconds)))]; -} + int intervalSeconds = 60) + { + return + [ + .. Enumerable.Range(0, sampleCount) + .Select(i => new HumiditySample( + startHumidity + ratePerMinute * i * intervalSeconds / 60.0, + TimeSpan.FromSeconds(i * intervalSeconds))) + ]; + } + + /// A humidity sample with its offset from a test's base timestamp. + public readonly record struct HumiditySample(double Humidity, TimeSpan Offset); +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs index c628267..8eafb8f 100644 --- a/ShowerMonitor.Manager/ExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -11,8 +11,8 @@ public sealed class ExhaustFanControlService( IHaContext haContext, IOptions options) : IExhaustFanControlService { - private readonly ShowerMonitorOptions _options = options.Value; private readonly Lock _lock = new(); + private readonly ShowerMonitorOptions _options = options.Value; private bool _fanTurnedOnByUs; private DateTimeOffset? _showerEndedAt; @@ -53,11 +53,9 @@ public sealed class ExhaustFanControlService( if (_fanTurnedOnByUs) { var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State; - + if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) - { haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); - } } _fanTurnedOnByUs = false; @@ -67,16 +65,10 @@ 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; @@ -84,21 +76,15 @@ 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; _showerEndedAt = null; } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/HumidityRateCalculator.cs b/ShowerMonitor.Manager/HumidityRateCalculator.cs index 12c5880..5fb506a 100644 --- a/ShowerMonitor.Manager/HumidityRateCalculator.cs +++ b/ShowerMonitor.Manager/HumidityRateCalculator.cs @@ -10,7 +10,13 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul public double? PreviousReading { - get { lock (_lock) { return _previousReading; } } + get + { + lock (_lock) + { + return _previousReading; + } + } } public void RecordReading(double humidity, DateTimeOffset timestamp) @@ -20,10 +26,7 @@ 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(); } } @@ -31,19 +34,13 @@ 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; } @@ -57,4 +54,4 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul _previousReading = null; } } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs index 6b6195c..aac9df8 100644 --- a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs @@ -6,4 +6,4 @@ public interface IExhaustFanControlService { void Evaluate(ShowerState state, DateTimeOffset timestamp); void Reset(); -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/Interface/IHumidityRateCalculator.cs b/ShowerMonitor.Manager/Interface/IHumidityRateCalculator.cs index f75ba19..edbece6 100644 --- a/ShowerMonitor.Manager/Interface/IHumidityRateCalculator.cs +++ b/ShowerMonitor.Manager/Interface/IHumidityRateCalculator.cs @@ -2,8 +2,8 @@ namespace ShowerMonitorManager.Interface; public interface IHumidityRateCalculator { + double? PreviousReading { get; } void RecordReading(double humidity, DateTimeOffset timestamp); double GetRatePerMinute(); void Reset(); - double? PreviousReading { get; } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs index ca1daed..3abf677 100644 --- a/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs +++ b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs @@ -11,4 +11,4 @@ public interface IShowerDetectionService ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp); void ResetDailyCounters(); -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs index 475e201..f6ca7ab 100644 --- a/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs +++ b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs @@ -7,4 +7,4 @@ public interface IShowerMonitorEntityService Task CreateEntitiesAsync(CancellationToken cancellationToken = default); Task UpdateEntitiesAsync(ShowerMonitorUpdateContext context, CancellationToken cancellationToken = default); Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs index 21301b9..7f6146c 100644 --- a/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs +++ b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs @@ -17,8 +17,11 @@ public sealed class ShowerMonitorOptions public double MinDifferentialHumidity { get; init; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity; public double PeakHumidityThreshold { get; init; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold; public int ConfirmationWindowMinutes { get; init; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes; - public double RecoveryDifferentialThreshold { get; init; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold; + + public double RecoveryDifferentialThreshold { get; init; } = + ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold; + public int MaxShowerDurationMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes; public int FanRunAfterShowerMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes; public int RateWindowSize { get; init; } = ShowerMonitorConsts.DefaultRateWindowSize; -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs index 95bbed6..a010f62 100644 --- a/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs +++ b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs @@ -10,4 +10,4 @@ public sealed class ShowerMonitorUpdateContext public required double HumidityRate { get; init; } public required int TodaySessionCount { get; init; } public ShowerSession? LastCompletedSession { get; init; } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/ShowerDetectionService.cs b/ShowerMonitor.Manager/ShowerDetectionService.cs index 549b957..86774ef 100644 --- a/ShowerMonitor.Manager/ShowerDetectionService.cs +++ b/ShowerMonitor.Manager/ShowerDetectionService.cs @@ -11,39 +11,69 @@ public sealed class ShowerDetectionService( IOptions options) : IShowerDetectionService { - private readonly ShowerMonitorOptions _options = options.Value; private readonly Lock _lock = new(); + private readonly ShowerMonitorOptions _options = options.Value; + private ShowerSession? _currentSession; private ShowerState _currentState = ShowerState.Idle; - private ShowerSession? _currentSession; private ShowerSession? _lastCompletedSession; - private int _todaySessionCount; - private DateTimeOffset? _suspectedSince; private double _lastRate; + private DateTimeOffset? _suspectedSince; + private int _todaySessionCount; public ShowerState CurrentState { - get { lock (_lock) { return _currentState; } } + get + { + lock (_lock) + { + return _currentState; + } + } } public ShowerSession? CurrentSession { - get { lock (_lock) { return _currentSession; } } + get + { + lock (_lock) + { + return _currentSession; + } + } } public ShowerSession? LastCompletedSession { - get { lock (_lock) { return _lastCompletedSession; } } + get + { + lock (_lock) + { + return _lastCompletedSession; + } + } } public int TodaySessionCount { - get { lock (_lock) { return _todaySessionCount; } } + get + { + lock (_lock) + { + return _todaySessionCount; + } + } } public double LastRate { - get { lock (_lock) { return _lastRate; } } + get + { + lock (_lock) + { + return _lastRate; + } + } } public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp) @@ -83,10 +113,7 @@ public sealed class ShowerDetectionService( var showerSuspected = rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity; - if (!showerSuspected) - { - return ShowerState.Idle; - } + if (!showerSuspected) return ShowerState.Idle; _suspectedSince = timestamp; _currentSession = new ShowerSession @@ -111,17 +138,12 @@ public sealed class ShowerDetectionService( var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes); if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow - && humidity >= _options.PeakHumidityThreshold - && differential >= _options.MinDifferentialHumidity) - { + && 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(); @@ -141,10 +163,7 @@ public sealed class ShowerDetectionService( && _currentSession.GetDuration(timestamp) >= maxDuration; var humidityRecovered = rate < 0 && differential < _options.MinDifferentialHumidity; - if (maxDurationReached || humidityRecovered) - { - return TransitionToDeclining(); - } + if (maxDurationReached || humidityRecovered) return TransitionToDeclining(); return ShowerState.Active; } @@ -162,10 +181,7 @@ public sealed class ShowerDetectionService( var maxDurationReached = _currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration; - if (!maxDurationReached) - { - return ShowerState.Declining; - } + if (!maxDurationReached) return ShowerState.Declining; CompleteSession(timestamp); @@ -180,16 +196,13 @@ public sealed class ShowerDetectionService( private ShowerState TransitionToIdle() { rateCalculator.Reset(); - + return ShowerState.Idle; } private void CompleteSession(DateTimeOffset endTime) { - if (_currentSession is null) - { - return; - } + if (_currentSession is null) return; _currentSession.EndTime = endTime; _lastCompletedSession = _currentSession; @@ -204,4 +217,4 @@ public sealed class ShowerDetectionService( _currentSession = null; _suspectedSince = null; } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj b/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj index 22f9bb2..388bd60 100644 --- a/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj +++ b/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj @@ -8,20 +8,20 @@ - - <_Parameter1>ShowerMonitor.Manager.Tests - + + <_Parameter1>ShowerMonitor.Manager.Tests + - - + + - - - + + + diff --git a/ShowerMonitor.Manager/ShowerMonitorEntityService.cs b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs index f3addf2..e400a5a 100644 --- a/ShowerMonitor.Manager/ShowerMonitorEntityService.cs +++ b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs @@ -25,14 +25,6 @@ public sealed class ShowerMonitorEntityService( CleanupButtonEntityId ]; - private static object CreateDeviceBlock() => new - { - identifiers = new[] { DeviceIdentifier }, - name = DeviceName, - model = DeviceName, - manufacturer = DeviceManufacturer - }; - public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -91,6 +83,17 @@ public sealed class ShowerMonitorEntityService( } } + private static object CreateDeviceBlock() + { + return new + { + identifiers = new[] { DeviceIdentifier }, + name = DeviceName, + model = DeviceName, + manufacturer = DeviceManufacturer + }; + } + private static ICollection GetAllEntities() { var device = CreateDeviceBlock(); @@ -107,7 +110,8 @@ public sealed class ShowerMonitorEntityService( }, new ShowerMonitorEntity("sensor", "showermonitor_differential_humidity", "Bathroom differential humidity") { - AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device } + AdditionalConfig = new + { unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device } }, new ShowerMonitorEntity("sensor", "showermonitor_humidity_rate", "Humidity rate of change") { @@ -119,7 +123,8 @@ public sealed class ShowerMonitorEntityService( }, new ShowerMonitorEntity("sensor", "showermonitor_last_shower_duration", "Last shower duration") { - AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device } + AdditionalConfig = new + { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device } }, new ShowerMonitorEntity("sensor", "showermonitor_last_shower_time", "Last shower time") { @@ -134,7 +139,8 @@ public sealed class ShowerMonitorEntityService( private async Task UpdateDifferentialAsync(double differential, string timestamp) { - await SetEntityStateSafe(DifferentialEntityId, Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityStateSafe(DifferentialEntityId, + Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); await SetEntityAttributesSafe(DifferentialEntityId, new { unit_of_measurement = "%", @@ -145,7 +151,8 @@ public sealed class ShowerMonitorEntityService( private async Task UpdateHumidityRateAsync(double rate, string timestamp) { - await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); await SetEntityAttributesSafe(HumidityRateEntityId, new { unit_of_measurement = "%/min", @@ -156,7 +163,8 @@ public sealed class ShowerMonitorEntityService( private async Task UpdateTodaySessionCountAsync(int count, string timestamp) { - await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); await SetEntityAttributesSafe(TodaySessionCountEntityId, new { friendly_name = "Showers today", @@ -166,13 +174,11 @@ public sealed class ShowerMonitorEntityService( 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); + await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture)) + .ConfigureAwait(false); await SetEntityAttributesSafe(LastShowerDurationEntityId, new { formatted = FormatDuration(session.Duration), @@ -181,7 +187,8 @@ public sealed class ShowerMonitorEntityService( last_updated = timestamp }).ConfigureAwait(false); - await SetEntityStateSafe(LastShowerTimeEntityId, session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityStateSafe(LastShowerTimeEntityId, + session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false); await SetEntityAttributesSafe(LastShowerTimeEntityId, new { friendly_name = "Last shower time", @@ -217,7 +224,7 @@ public sealed class ShowerMonitorEntityService( { var totalMinutes = (int)ts.TotalMinutes; var seconds = ts.Seconds; - + return $"{totalMinutes}m {seconds}s"; } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs index aa61290..7271817 100644 --- a/ShowerMonitor.Manager/ShowerMonitorInit.cs +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -15,13 +15,13 @@ namespace ShowerMonitorManager; [NetDaemonApp] public sealed class ShowerMonitorInit { - private readonly ILogger _logger; - private readonly IHaContext _haContext; - private readonly IScheduler _scheduler; private readonly IShowerDetectionService _detectionService; - private readonly IExhaustFanControlService _fanControlService; private readonly IShowerMonitorEntityService _entityService; + private readonly IExhaustFanControlService _fanControlService; + private readonly IHaContext _haContext; + private readonly ILogger _logger; private readonly ShowerMonitorOptions _options; + private readonly IScheduler _scheduler; private readonly TimeProvider _timeProvider; private volatile bool _cleanedUp; @@ -69,10 +69,7 @@ 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(); @@ -158,9 +155,8 @@ public sealed class ShowerMonitorInit if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue) { if (_logger.IsEnabled(LogLevel.Debug)) - { - _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity); - } + _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", + bathroomHumidity, mainHomeHumidity); return; } @@ -183,10 +179,8 @@ public sealed class ShowerMonitorInit await _entityService.UpdateEntitiesAsync(context); 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); - } } catch (Exception ex) { @@ -198,11 +192,8 @@ 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; } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs index aeb4c78..774f4a8 100644 --- a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs +++ b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs @@ -14,10 +14,7 @@ public static class ShowerMonitorServiceRegistration .GetSection(ShowerMonitorOptions.SectionName) .Get() ?? new ShowerMonitorOptions(); - if (!options.Enabled) - { - return services; - } + if (!options.Enabled) return services; services .AddNetDaemonApp() @@ -28,4 +25,4 @@ public static class ShowerMonitorServiceRegistration return services; } -} +} \ No newline at end of file diff --git a/ShowerMonitor.Models/Enums/ShowerState.cs b/ShowerMonitor.Models/Enums/ShowerState.cs index 1145495..46fe563 100644 --- a/ShowerMonitor.Models/Enums/ShowerState.cs +++ b/ShowerMonitor.Models/Enums/ShowerState.cs @@ -7,4 +7,4 @@ public enum ShowerState Active, Declining, Completed -} +} \ No newline at end of file diff --git a/ShowerMonitor.Models/ShowerMonitor.Models.csproj b/ShowerMonitor.Models/ShowerMonitor.Models.csproj index 4c156c4..a0b3752 100644 --- a/ShowerMonitor.Models/ShowerMonitor.Models.csproj +++ b/ShowerMonitor.Models/ShowerMonitor.Models.csproj @@ -8,11 +8,11 @@ - + - + diff --git a/ShowerMonitor.Models/ShowerMonitorConsts.cs b/ShowerMonitor.Models/ShowerMonitorConsts.cs index a517c71..3795e29 100644 --- a/ShowerMonitor.Models/ShowerMonitorConsts.cs +++ b/ShowerMonitor.Models/ShowerMonitorConsts.cs @@ -11,9 +11,6 @@ public static class ShowerMonitorConsts public const double DefaultRecoveryDifferentialThreshold = 5.0; public const int DefaultRateWindowSize = 5; - public static readonly TimeSpan DefaultMaxShowerDuration = TimeSpan.FromMinutes(60); - public static readonly TimeSpan DefaultFanRunAfterShower = TimeSpan.FromMinutes(10); - public const string BathroomHumidityEntityId = "sensor.bathroom_humidity"; public const string MainHomeHumidityEntityId = "sensor.main_home_humidity"; public const string BathroomTemperatureEntityId = "sensor.bathroom_temperature"; @@ -31,4 +28,7 @@ public static class ShowerMonitorConsts public const string DeviceIdentifier = "shower_monitor"; public const string DeviceName = "Shower Monitor"; public const string DeviceManufacturer = "HomeAssistant App Daemon"; -} + + public static readonly TimeSpan DefaultMaxShowerDuration = TimeSpan.FromMinutes(60); + public static readonly TimeSpan DefaultFanRunAfterShower = TimeSpan.FromMinutes(10); +} \ No newline at end of file diff --git a/ShowerMonitor.Models/ShowerMonitorEntity.cs b/ShowerMonitor.Models/ShowerMonitorEntity.cs index ee3903b..d6224b6 100644 --- a/ShowerMonitor.Models/ShowerMonitorEntity.cs +++ b/ShowerMonitor.Models/ShowerMonitorEntity.cs @@ -5,10 +5,6 @@ namespace ShowerMonitor.Models; public class ShowerMonitorEntity : EntityCreateModel { - private string Domain { get; } - private string Identifier { get; } - private string Name { get; } - public ShowerMonitorEntity(string domain, string identifier, string name) { Domain = domain; @@ -22,4 +18,8 @@ public class ShowerMonitorEntity : EntityCreateModel Name = Name }; } -} + + private string Domain { get; } + private string Identifier { get; } + private string Name { get; } +} \ No newline at end of file diff --git a/ShowerMonitor.Models/ShowerSession.cs b/ShowerMonitor.Models/ShowerSession.cs index 80449f9..756d149 100644 --- a/ShowerMonitor.Models/ShowerSession.cs +++ b/ShowerMonitor.Models/ShowerSession.cs @@ -14,4 +14,4 @@ public sealed class ShowerSession { return (EndTime ?? asOf) - StartTime; } -} +} \ No newline at end of file