Compare commits

..

1 Commits

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

Some files were not shown because too many files have changed in this diff Show More