Compare commits
2 Commits
77458383d1
...
635e9625ea
| Author | SHA1 | Date | |
|---|---|---|---|
| 635e9625ea | |||
| f919d6b25b |
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using BatteryMonitor.Models;
|
||||
@@ -5,6 +7,8 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -20,7 +24,7 @@ internal static class BatteryMonitorTestData
|
||||
/// (threshold, state, expected) rows straddling the strict <c>level < threshold</c>
|
||||
/// boundary, including zero/negative thresholds and int min/max thresholds.
|
||||
/// </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, "5", false },
|
||||
@@ -59,7 +63,7 @@ internal static class BatteryMonitorTestData
|
||||
"unknown",
|
||||
"UNAVAILABLE",
|
||||
"UNKNOWN",
|
||||
"",
|
||||
string.Empty,
|
||||
" ",
|
||||
"\t",
|
||||
"not_a_number",
|
||||
@@ -85,8 +89,10 @@ internal static class BatteryMonitorTestData
|
||||
}
|
||||
|
||||
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
|
||||
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state,
|
||||
string? friendlyName = DefaultFriendlyName)
|
||||
public static EntitySpec Sensor(string entityId,
|
||||
string? deviceClass,
|
||||
string? state,
|
||||
string? friendlyName = DefaultFriendlyName)
|
||||
{
|
||||
return new EntitySpec
|
||||
{
|
||||
@@ -101,9 +107,15 @@ internal static class BatteryMonitorTestData
|
||||
{
|
||||
var attributes = new Dictionary<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
|
||||
{
|
||||
@@ -122,7 +134,10 @@ internal static class BatteryMonitorTestData
|
||||
|
||||
foreach (var spec in entities)
|
||||
{
|
||||
if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
|
||||
if (spec.HasState)
|
||||
{
|
||||
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
|
||||
}
|
||||
|
||||
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
|
||||
}
|
||||
@@ -159,10 +174,10 @@ internal static class BatteryMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => Battery(
|
||||
$"sensor.generated_battery_{i:D3}",
|
||||
i.ToString(CultureInfo.InvariantCulture),
|
||||
$"Generated Battery {i:D3}"))
|
||||
.Select(i => Battery(
|
||||
$"sensor.generated_battery_{i:D3}",
|
||||
i.ToString(CultureInfo.InvariantCulture),
|
||||
$"Generated Battery {i:D3}"))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -175,10 +190,10 @@ internal static class BatteryMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => CreateSensorInfo(
|
||||
$"sensor.generated_{i:D3}",
|
||||
i * 37 % 101,
|
||||
$"Generated Device {i:D3}"))
|
||||
.Select(i => CreateSensorInfo(
|
||||
$"sensor.generated_{i:D3}",
|
||||
i * 37 % 101,
|
||||
$"Generated Device {i:D3}"))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -202,7 +217,7 @@ internal static class BatteryMonitorTestData
|
||||
data.Add("sensor.boiler_temp_battery", false);
|
||||
data.Add("sensor.aquarium_leak_sensor_battery", false);
|
||||
data.Add("sensor.temperature", false);
|
||||
data.Add("", false);
|
||||
data.Add(string.Empty, false);
|
||||
data.Add(" ", false);
|
||||
|
||||
return data;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using BatteryMonitor.Models;
|
||||
using BatteryMonitorManager;
|
||||
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitor.Manager.Tests;
|
||||
|
||||
public class BatteryNotificationServiceTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new Mock<ILogger<BatteryNotificationService>>();
|
||||
|
||||
private BatteryNotificationService CreateSut()
|
||||
{
|
||||
@@ -23,10 +27,10 @@ public class BatteryNotificationServiceTests
|
||||
private void VerifyCallService(string service, Times times)
|
||||
{
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
service,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), times);
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
service,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), times);
|
||||
}
|
||||
|
||||
#region NotifyLowBattery
|
||||
@@ -38,7 +42,7 @@ public class BatteryNotificationServiceTests
|
||||
var devices = CreateSensorInfos(
|
||||
[
|
||||
.. Enumerable.Range(0, deviceCount)
|
||||
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
|
||||
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
|
||||
]);
|
||||
|
||||
var sut = CreateSut();
|
||||
@@ -54,17 +58,18 @@ public class BatteryNotificationServiceTests
|
||||
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray)
|
||||
{
|
||||
IReadOnlyList<BatterySensorInfo> devices = useArray
|
||||
? Array.Empty<BatterySensorInfo>()
|
||||
: new List<BatterySensorInfo>();
|
||||
? Array.Empty<BatterySensorInfo>()
|
||||
: new List<BatterySensorInfo>();
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.NotifyLowBattery(devices);
|
||||
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Never);
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Never);
|
||||
|
||||
_loggerMock.Invocations.Should().BeEmpty();
|
||||
}
|
||||
|
||||
@@ -72,18 +77,20 @@ public class BatteryNotificationServiceTests
|
||||
public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary()
|
||||
{
|
||||
object? payload = null;
|
||||
|
||||
_haContextMock
|
||||
.Setup(h => h.CallService(
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data);
|
||||
.Setup(h => h.CallService(
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data);
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.NotifyLowBattery(CreateSensorInfos(
|
||||
("sensor.a", "Device A", 4),
|
||||
("sensor.b", "Device B", 1)));
|
||||
("sensor.a", "Device A", 4),
|
||||
("sensor.b", "Device B", 1)));
|
||||
|
||||
payload.Should().NotBeNull();
|
||||
|
||||
@@ -101,16 +108,19 @@ public class BatteryNotificationServiceTests
|
||||
public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount()
|
||||
{
|
||||
_loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true);
|
||||
|
||||
var devices = CreateSensorInfos(
|
||||
("sensor.a", "Device A", 2),
|
||||
("sensor.b", "Device B", 3));
|
||||
("sensor.a", "Device A", 2),
|
||||
("sensor.b", "Device B", 3));
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.NotifyLowBattery(devices);
|
||||
|
||||
var logInvocation = _loggerMock.Invocations
|
||||
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
|
||||
.Should().ContainSingle().Subject;
|
||||
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
|
||||
.Should()
|
||||
.ContainSingle()
|
||||
.Subject;
|
||||
|
||||
logInvocation.Arguments[0].Should().Be(LogLevel.Information);
|
||||
logInvocation.Arguments[2].Should().NotBeNull();
|
||||
@@ -139,7 +149,10 @@ public class BatteryNotificationServiceTests
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
for (var i = 0; i < calls; i++) sut.DismissNotification();
|
||||
for (var i = 0; i < calls; i++)
|
||||
{
|
||||
sut.DismissNotification();
|
||||
}
|
||||
|
||||
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
|
||||
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
||||
@@ -153,9 +166,9 @@ public class BatteryNotificationServiceTests
|
||||
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
|
||||
{
|
||||
var devices = CreateSensorInfos(
|
||||
("sensor.a", "Device A", 4),
|
||||
("sensor.b", "Device B", 1),
|
||||
("sensor.c", "Device C", 3));
|
||||
("sensor.a", "Device A", 4),
|
||||
("sensor.b", "Device B", 1),
|
||||
("sensor.c", "Device C", 3));
|
||||
|
||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||
|
||||
@@ -170,9 +183,9 @@ public class BatteryNotificationServiceTests
|
||||
public void BuildNotificationMessage_ShouldKeepInsertionOrderForEqualLevels()
|
||||
{
|
||||
var devices = CreateSensorInfos(
|
||||
("sensor.first", "First Device", 4),
|
||||
("sensor.second", "Second Device", 4),
|
||||
("sensor.third", "Third Device", 1));
|
||||
("sensor.first", "First Device", 4),
|
||||
("sensor.second", "Second Device", 4),
|
||||
("sensor.third", "Third Device", 1));
|
||||
|
||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||
|
||||
@@ -191,8 +204,8 @@ public class BatteryNotificationServiceTests
|
||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||
|
||||
var expectedLines = devices
|
||||
.OrderBy(d => d.BatteryLevel)
|
||||
.Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%");
|
||||
.OrderBy(d => d.BatteryLevel)
|
||||
.Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%");
|
||||
|
||||
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||
lines.Should().HaveCount(devices.Count + 1);
|
||||
@@ -219,8 +232,9 @@ public class BatteryNotificationServiceTests
|
||||
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
|
||||
[InlineData("", 5, "- ****: 5%")]
|
||||
[InlineData(" ", 4, "- ** **: 4%")]
|
||||
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel,
|
||||
string expectedLine)
|
||||
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName,
|
||||
double batteryLevel,
|
||||
string expectedLine)
|
||||
{
|
||||
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
|
||||
|
||||
@@ -256,8 +270,8 @@ public class BatteryNotificationServiceTests
|
||||
public void BuildNotificationMessage_WithDuplicateDevices_ShouldListEveryDevice()
|
||||
{
|
||||
var devices = CreateSensorInfos(
|
||||
("sensor.duplicate_battery", "Duplicate Battery", 2),
|
||||
("sensor.duplicate_battery", "Duplicate Battery", 2));
|
||||
("sensor.duplicate_battery", "Duplicate Battery", 2),
|
||||
("sensor.duplicate_battery", "Duplicate Battery", 2));
|
||||
|
||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using BatteryMonitor.Models;
|
||||
using BatteryMonitorManager;
|
||||
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitor.Manager.Tests;
|
||||
|
||||
public class BatterySensorDiscoveryServiceTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
|
||||
|
||||
private BatterySensorDiscoveryService CreateSut()
|
||||
{
|
||||
@@ -42,10 +46,10 @@ public class BatterySensorDiscoveryServiceTests
|
||||
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
|
||||
{
|
||||
SetupEntities(
|
||||
Battery("sensor.bathroom_battery", "3", "Bathroom Battery"),
|
||||
Battery("sensor.bedroom_battery", "80", "Bedroom Battery"),
|
||||
Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery")
|
||||
);
|
||||
Battery("sensor.bathroom_battery", "3", "Bathroom Battery"),
|
||||
Battery("sensor.bedroom_battery", "80", "Bedroom Battery"),
|
||||
Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -70,9 +74,9 @@ public class BatterySensorDiscoveryServiceTests
|
||||
public void DiscoverLowBatterySensors_ShouldExcludePersonalDevices(string excludedEntityId, string friendlyName)
|
||||
{
|
||||
SetupEntities(
|
||||
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
|
||||
Battery(excludedEntityId, "1", friendlyName)
|
||||
);
|
||||
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
|
||||
Battery(excludedEntityId, "1", friendlyName)
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -89,12 +93,12 @@ public class BatterySensorDiscoveryServiceTests
|
||||
[InlineData("sensorx.bathroom_battery", "battery")]
|
||||
[InlineData("switch.bathroom_battery", "battery")]
|
||||
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId,
|
||||
string? deviceClass)
|
||||
string? deviceClass)
|
||||
{
|
||||
SetupEntities(
|
||||
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
|
||||
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||
);
|
||||
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
|
||||
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -108,9 +112,9 @@ public class BatterySensorDiscoveryServiceTests
|
||||
public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state)
|
||||
{
|
||||
SetupEntities(
|
||||
Battery("sensor.bathroom_battery", state, "Bathroom Battery"),
|
||||
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||
);
|
||||
Battery("sensor.bathroom_battery", state, "Bathroom Battery"),
|
||||
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -123,10 +127,10 @@ public class BatterySensorDiscoveryServiceTests
|
||||
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
|
||||
{
|
||||
SetupEntities(
|
||||
new EntitySpec
|
||||
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
|
||||
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||
);
|
||||
new EntitySpec
|
||||
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
|
||||
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -137,8 +141,9 @@ public class BatterySensorDiscoveryServiceTests
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state,
|
||||
bool expectedIncluded)
|
||||
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
|
||||
string state,
|
||||
bool expectedIncluded)
|
||||
{
|
||||
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
|
||||
|
||||
@@ -147,7 +152,10 @@ public class BatterySensorDiscoveryServiceTests
|
||||
|
||||
result.Should().HaveCount(expectedIncluded ? 1 : 0);
|
||||
|
||||
if (!expectedIncluded) return;
|
||||
if (!expectedIncluded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
result[0].EntityId.Should().Be("sensor.boundary_battery");
|
||||
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
|
||||
@@ -157,9 +165,9 @@ public class BatterySensorDiscoveryServiceTests
|
||||
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
|
||||
{
|
||||
SetupEntities(
|
||||
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
|
||||
Sensor("switch.some_switch", null, "on", "Switch")
|
||||
);
|
||||
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
|
||||
Sensor("switch.some_switch", null, "on", "Switch")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -171,10 +179,10 @@ public class BatterySensorDiscoveryServiceTests
|
||||
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
|
||||
{
|
||||
SetupEntities(
|
||||
Battery("sensor.bathroom_battery", "5", "Bathroom Battery"),
|
||||
Battery("sensor.bedroom_battery", "50", "Bedroom Battery"),
|
||||
Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery")
|
||||
);
|
||||
Battery("sensor.bathroom_battery", "5", "Bathroom Battery"),
|
||||
Battery("sensor.bedroom_battery", "50", "Bedroom Battery"),
|
||||
Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -198,9 +206,9 @@ public class BatterySensorDiscoveryServiceTests
|
||||
public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence()
|
||||
{
|
||||
SetupEntities(
|
||||
Battery("sensor.duplicate_battery", "2", "Duplicate Battery"),
|
||||
Battery("sensor.duplicate_battery", "2", "Duplicate Battery")
|
||||
);
|
||||
Battery("sensor.duplicate_battery", "2", "Duplicate Battery"),
|
||||
Battery("sensor.duplicate_battery", "2", "Duplicate Battery")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||
@@ -250,8 +258,10 @@ public class BatterySensorDiscoveryServiceTests
|
||||
|
||||
result.Should().HaveCount(7);
|
||||
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
|
||||
result.Select(s => s.FriendlyName).Should()
|
||||
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
|
||||
|
||||
result.Select(s => s.FriendlyName)
|
||||
.Should()
|
||||
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Reactive.Concurrency;
|
||||
using BatteryMonitor.Models;
|
||||
using BatteryMonitorManager.Interface;
|
||||
@@ -7,6 +9,8 @@ using Microsoft.Extensions.Options;
|
||||
using NetDaemon.AppModel;
|
||||
using NetDaemon.Extensions.Scheduler;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -58,12 +62,13 @@ public sealed class BatteryMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
|
||||
_options.BatteryThresholdPercent);
|
||||
_options.BatteryThresholdPercent);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing BatteryMonitor");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -71,17 +76,17 @@ public sealed class BatteryMonitorInit
|
||||
private void ScheduleDailyCheck()
|
||||
{
|
||||
_scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Running scheduled daily battery check");
|
||||
CheckAndNotify();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during scheduled battery check");
|
||||
}
|
||||
});
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Running scheduled daily battery check");
|
||||
CheckAndNotify();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during scheduled battery check");
|
||||
}
|
||||
});
|
||||
|
||||
_logger.LogInformation("Scheduled daily battery check at 08:00");
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using BatteryMonitorManager.Interface;
|
||||
using BatteryMonitorManager.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitorManager;
|
||||
|
||||
public static class BatteryMonitorServiceRegistration
|
||||
@@ -11,15 +15,19 @@ public static class BatteryMonitorServiceRegistration
|
||||
public static IServiceCollection AddBatteryMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var options = configuration
|
||||
.GetSection(BatteryMonitorOptions.SectionName)
|
||||
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
|
||||
.GetSection(BatteryMonitorOptions.SectionName)
|
||||
.Get<BatteryMonitorOptions>() ??
|
||||
new BatteryMonitorOptions();
|
||||
|
||||
if (!options.Enabled) return services;
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
}
|
||||
|
||||
services
|
||||
.AddNetDaemonApp<BatteryMonitorInit>()
|
||||
.AddScoped<IBatterySensorDiscoveryService, BatterySensorDiscoveryService>()
|
||||
.AddScoped<IBatteryNotificationService, BatteryNotificationService>();
|
||||
.AddNetDaemonApp<BatteryMonitorInit>()
|
||||
.AddScoped<IBatterySensorDiscoveryService, BatterySensorDiscoveryService>()
|
||||
.AddScoped<IBatteryNotificationService, BatteryNotificationService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using System.Text;
|
||||
using BatteryMonitor.Models;
|
||||
using BatteryMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NetDaemon.HassModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitorManager;
|
||||
|
||||
public sealed class BatteryNotificationService(
|
||||
@@ -12,37 +16,40 @@ public sealed class BatteryNotificationService(
|
||||
{
|
||||
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
||||
{
|
||||
if (lowBatteryDevices.Count == 0) return;
|
||||
if (lowBatteryDevices.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var message = BuildNotificationMessage(lowBatteryDevices);
|
||||
|
||||
haContext.CallService(
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = BatteryMonitorConsts.NotificationTitle,
|
||||
message,
|
||||
notification_id = BatteryMonitorConsts.NotificationId
|
||||
});
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = BatteryMonitorConsts.NotificationTitle,
|
||||
message,
|
||||
notification_id = BatteryMonitorConsts.NotificationId
|
||||
});
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Sent low battery notification for {Count} device(s)",
|
||||
lowBatteryDevices.Count);
|
||||
"Sent low battery notification for {Count} device(s)",
|
||||
lowBatteryDevices.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public void DismissNotification()
|
||||
{
|
||||
haContext.CallService(
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
BatteryMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new
|
||||
{
|
||||
notification_id = BatteryMonitorConsts.NotificationId
|
||||
});
|
||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||
BatteryMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new
|
||||
{
|
||||
notification_id = BatteryMonitorConsts.NotificationId
|
||||
});
|
||||
|
||||
logger.LogDebug("Dismissed low battery notification");
|
||||
}
|
||||
@@ -54,7 +61,9 @@ public sealed class BatteryNotificationService(
|
||||
sb.AppendLine();
|
||||
|
||||
foreach (var device in devices.OrderBy(d => d.BatteryLevel))
|
||||
{
|
||||
sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%");
|
||||
}
|
||||
|
||||
return sb.ToString().TrimEnd();
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using BatteryMonitor.Models;
|
||||
@@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitorManager;
|
||||
|
||||
public sealed class BatterySensorDiscoveryService(
|
||||
@@ -17,17 +21,17 @@ public sealed class BatterySensorDiscoveryService(
|
||||
var allEntities = haContext.GetAllEntities();
|
||||
|
||||
var lowBatterySensors = allEntities
|
||||
.Where(IsBatterySensor)
|
||||
.Where(e => !IsExcludedDevice(e.EntityId))
|
||||
.Select(e => TryCreateSensorInfo(e, thresholdPercent))
|
||||
.Where(info => info is not null)
|
||||
.ToList();
|
||||
.Where(IsBatterySensor)
|
||||
.Where(e => !IsExcludedDevice(e.EntityId))
|
||||
.Select(e => TryCreateSensorInfo(e, thresholdPercent))
|
||||
.Where(info => info is not null)
|
||||
.ToList();
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Battery check: found {Count} sensors below {Threshold}%",
|
||||
lowBatterySensors.Count, thresholdPercent);
|
||||
"Battery check: found {Count} sensors below {Threshold}%",
|
||||
lowBatterySensors.Count, thresholdPercent);
|
||||
}
|
||||
|
||||
return lowBatterySensors!;
|
||||
@@ -50,7 +54,7 @@ public sealed class BatterySensorDiscoveryService(
|
||||
var lowerEntityId = entityId.ToLowerInvariant();
|
||||
|
||||
return BatteryMonitorConsts.ExcludedKeywords
|
||||
.Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||
.Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private BatterySensorInfo? TryCreateSensorInfo(Entity entity, int thresholdPercent)
|
||||
@@ -62,7 +66,7 @@ public sealed class BatterySensorDiscoveryService(
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
|
||||
state ?? "null");
|
||||
state ?? "null");
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -73,16 +77,18 @@ public sealed class BatterySensorDiscoveryService(
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
|
||||
state);
|
||||
state);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (batteryLevel >= thresholdPercent) return null;
|
||||
if (batteryLevel >= thresholdPercent)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
|
||||
?? entity.EntityId;
|
||||
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId;
|
||||
|
||||
return new BatterySensorInfo
|
||||
{
|
||||
@@ -94,10 +100,13 @@ public sealed class BatterySensorDiscoveryService(
|
||||
|
||||
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||
{
|
||||
if (element is null) return null;
|
||||
if (element is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return element.Value.TryGetProperty(propertyName, out var value)
|
||||
? value.GetString()
|
||||
: null;
|
||||
? value.GetString()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BatteryMonitor.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitorManager.Interface;
|
||||
|
||||
public interface IBatteryNotificationService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BatteryMonitor.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitorManager.Interface;
|
||||
|
||||
public interface IBatterySensorDiscoveryService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BatteryMonitor.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BatteryMonitorManager.Models;
|
||||
|
||||
public sealed class BatteryMonitorOptions
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models.Enums;
|
||||
using BoilerMonitorManager;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerControlServiceTests
|
||||
{
|
||||
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new();
|
||||
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
|
||||
|
||||
private BoilerControlService CreateSut()
|
||||
{
|
||||
@@ -34,8 +38,9 @@ public class BoilerControlServiceTests
|
||||
bool budgetExhausted,
|
||||
bool budgetOverride)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(BoilerAction.NoChange);
|
||||
}
|
||||
@@ -57,9 +62,10 @@ public class BoilerControlServiceTests
|
||||
[InlineData("0")]
|
||||
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
true, false, switchState,
|
||||
false, false);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
true, false, switchState,
|
||||
false, false);
|
||||
|
||||
result.Should().Be(BoilerAction.TurnOn);
|
||||
}
|
||||
@@ -75,9 +81,10 @@ public class BoilerControlServiceTests
|
||||
string? switchState,
|
||||
BoilerAction expectedAction)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
true, false, switchState,
|
||||
true, true);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
true, false, switchState,
|
||||
true, true);
|
||||
|
||||
result.Should().Be(expectedAction);
|
||||
}
|
||||
@@ -93,9 +100,10 @@ public class BoilerControlServiceTests
|
||||
[InlineData("oN")]
|
||||
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
false, false, switchState,
|
||||
false, false);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
false, false, switchState,
|
||||
false, false);
|
||||
|
||||
result.Should().Be(BoilerAction.TurnOff);
|
||||
}
|
||||
@@ -109,9 +117,10 @@ public class BoilerControlServiceTests
|
||||
bool budgetExhausted,
|
||||
bool budgetOverride)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
true, waterReady, "on",
|
||||
budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
true, waterReady, "on",
|
||||
budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(BoilerAction.TurnOff);
|
||||
}
|
||||
@@ -124,7 +133,7 @@ public class BoilerControlServiceTests
|
||||
/// Complete truth table for a boiler that is currently ON: it may only stay on when
|
||||
/// it is cheap, water is not ready and the budget is available (or overridden).
|
||||
/// </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, true, BoilerAction.TurnOff },
|
||||
@@ -153,8 +162,9 @@ public class BoilerControlServiceTests
|
||||
bool budgetOverride,
|
||||
BoilerAction expectedAction)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(expectedAction);
|
||||
}
|
||||
@@ -163,7 +173,7 @@ public class BoilerControlServiceTests
|
||||
/// Complete truth table for a boiler that is currently OFF: it may only turn on when
|
||||
/// it is cheap, water is not ready and the budget is available (or overridden).
|
||||
/// </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, true, BoilerAction.NoChange },
|
||||
@@ -192,8 +202,9 @@ public class BoilerControlServiceTests
|
||||
bool budgetOverride,
|
||||
BoilerAction expectedAction)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(expectedAction);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerMonitorConfigTests
|
||||
@@ -7,7 +11,7 @@ public class BoilerMonitorConfigTests
|
||||
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
|
||||
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
|
||||
|
||||
public static TheoryData<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 },
|
||||
{ "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true },
|
||||
@@ -18,11 +22,11 @@ public class BoilerMonitorConfigTests
|
||||
{ "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true },
|
||||
|
||||
{ "power entity id null", null, SwitchEntityId, 30, 5.0, false },
|
||||
{ "power entity id empty", "", SwitchEntityId, 30, 5.0, false },
|
||||
{ "power entity id empty", string.Empty, SwitchEntityId, 30, 5.0, false },
|
||||
{ "power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false },
|
||||
{ "power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false },
|
||||
{ "switch entity id null", PowerEntityId, null, 30, 5.0, false },
|
||||
{ "switch entity id empty", PowerEntityId, "", 30, 5.0, false },
|
||||
{ "switch entity id empty", PowerEntityId, string.Empty, 30, 5.0, false },
|
||||
{ "switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false },
|
||||
{ "both entity ids null", null, null, 30, 5.0, false },
|
||||
|
||||
@@ -50,10 +54,10 @@ public class BoilerMonitorConfigTests
|
||||
bool expected)
|
||||
{
|
||||
var config = BoilerMonitorTestData.CreateConfig(
|
||||
powerEntityId,
|
||||
switchEntityId,
|
||||
pollIntervalSeconds,
|
||||
heatingPowerThresholdWatts);
|
||||
powerEntityId,
|
||||
switchEntityId,
|
||||
pollIntervalSeconds,
|
||||
heatingPowerThresholdWatts);
|
||||
|
||||
config.IsFullyConfigured.Should().Be(expected, scenario);
|
||||
}
|
||||
@@ -62,8 +66,8 @@ public class BoilerMonitorConfigTests
|
||||
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
|
||||
{
|
||||
var config = BoilerMonitorTestData.CreateConfig(
|
||||
" sensor.sonoff_1002230e32_power ",
|
||||
"SWITCH.SONOFF_1002230E32");
|
||||
" sensor.sonoff_1002230e32_power ",
|
||||
"SWITCH.SONOFF_1002230E32");
|
||||
|
||||
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using BoilerMonitorManager;
|
||||
using FluentAssertions;
|
||||
@@ -8,6 +10,8 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerMonitorEntityServiceTests
|
||||
@@ -31,28 +35,31 @@ public class BoilerMonitorEntityServiceTests
|
||||
AutoManagementEntityId
|
||||
];
|
||||
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new();
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
||||
|
||||
public BoilerMonitorEntityServiceTests()
|
||||
{
|
||||
_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>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_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);
|
||||
.Returns(Task.CompletedTask);
|
||||
}
|
||||
|
||||
private BoilerMonitorEntityService CreateSut()
|
||||
{
|
||||
return new BoilerMonitorEntityService(
|
||||
_entityManagerMock.Object,
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object);
|
||||
_entityManagerMock.Object,
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object);
|
||||
}
|
||||
|
||||
#region ReadPersistedState
|
||||
@@ -64,13 +71,14 @@ public class BoilerMonitorEntityServiceTests
|
||||
TimeSpan? expectedRunTime)
|
||||
{
|
||||
_haContextMock.SetupEntityStates(
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
if (expectedRunTime is null)
|
||||
{
|
||||
result.Should().BeNull();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,13 +94,14 @@ public class BoilerMonitorEntityServiceTests
|
||||
int? expectedSessionCount)
|
||||
{
|
||||
_haContextMock.SetupEntityStates(
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
if (expectedSessionCount is null)
|
||||
{
|
||||
result.Should().BeNull();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,7 +114,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
||||
{
|
||||
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||
"7200", "3", "ON"));
|
||||
"7200", "3", "ON"));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
@@ -125,7 +134,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState)
|
||||
{
|
||||
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||
skipPriceCap: switchState, budgetOverride: switchState));
|
||||
skipPriceCap: switchState, budgetOverride: switchState));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
@@ -138,7 +147,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
|
||||
{
|
||||
_haContextMock.SetupEntityStates(
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||
|
||||
CreateSut().ReadPersistedState().Should().BeNull();
|
||||
}
|
||||
@@ -151,9 +160,10 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp()
|
||||
{
|
||||
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30);
|
||||
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
|
||||
|
||||
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||
|
||||
@@ -164,9 +174,10 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
|
||||
{
|
||||
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
|
||||
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
|
||||
|
||||
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||
|
||||
@@ -193,9 +204,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull()
|
||||
{
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateEntityStateWithAttributes(
|
||||
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateEntityStateWithAttributes(
|
||||
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
|
||||
|
||||
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||
}
|
||||
@@ -212,8 +223,8 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince)
|
||||
{
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
|
||||
|
||||
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||
}
|
||||
@@ -222,7 +233,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull()
|
||||
{
|
||||
_haContextMock.Setup(h => h.GetState(WaterReadyEntityId))
|
||||
.Throws(new InvalidOperationException("Home Assistant unavailable"));
|
||||
.Throws(new InvalidOperationException("Home Assistant unavailable"));
|
||||
|
||||
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||
}
|
||||
@@ -245,12 +256,12 @@ public class BoilerMonitorEntityServiceTests
|
||||
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
|
||||
{
|
||||
var context = BoilerMonitorTestData.CreateUpdateContext(
|
||||
TimeSpan.FromSeconds(3723.9),
|
||||
TimeSpan.FromSeconds(42.9),
|
||||
150.0,
|
||||
true,
|
||||
4,
|
||||
waterReady: true);
|
||||
TimeSpan.FromSeconds(3723.9),
|
||||
TimeSpan.FromSeconds(42.9),
|
||||
150.0,
|
||||
true,
|
||||
4,
|
||||
waterReady: true);
|
||||
|
||||
await CreateSut().UpdateEntitiesAsync(context);
|
||||
|
||||
@@ -260,8 +271,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||
Times.Exactly(5));
|
||||
Times.Exactly(5));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -276,11 +288,12 @@ public class BoilerMonitorEntityServiceTests
|
||||
double budgetPercentage,
|
||||
string expectedState)
|
||||
{
|
||||
await CreateSut().UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
|
||||
await CreateSut()
|
||||
.UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
|
||||
|
||||
_entityManagerMock.Verify(
|
||||
em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once);
|
||||
em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -291,8 +304,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
[InlineData(3600, "3600")]
|
||||
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState)
|
||||
{
|
||||
await CreateSut().UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
|
||||
await CreateSut()
|
||||
.UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once);
|
||||
}
|
||||
@@ -305,8 +319,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
[InlineData(86_400.0, "86400")]
|
||||
public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState)
|
||||
{
|
||||
await CreateSut().UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
|
||||
await CreateSut()
|
||||
.UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once);
|
||||
}
|
||||
@@ -315,15 +330,17 @@ public class BoilerMonitorEntityServiceTests
|
||||
public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes()
|
||||
{
|
||||
object? capturedAttributes = null;
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(
|
||||
waterReady: false,
|
||||
boilerSwitchState: null,
|
||||
boilerPowerWatts: 1234.5));
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await CreateSut()
|
||||
.UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(
|
||||
waterReady: false,
|
||||
boilerSwitchState: null,
|
||||
boilerPowerWatts: 1234.5));
|
||||
|
||||
capturedAttributes.Should().NotBeNull();
|
||||
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
|
||||
@@ -338,13 +355,15 @@ public class BoilerMonitorEntityServiceTests
|
||||
{
|
||||
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15);
|
||||
object? capturedAttributes = null;
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await CreateSut().UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince));
|
||||
_entityManagerMock
|
||||
.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!);
|
||||
attributes.GetProperty("cooldown_since").GetString().Should().Be(cooldownSince.ToString("O"));
|
||||
@@ -358,49 +377,54 @@ public class BoilerMonitorEntityServiceTests
|
||||
public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce()
|
||||
{
|
||||
var createdEntityIds = new List<string?>();
|
||||
|
||||
_entityManagerMock
|
||||
.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||
.Callback<EntityCreateModel>(entity => createdEntityIds.Add(entity.EntityId))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||
.Callback<EntityCreateModel>(entity => createdEntityIds.Add(entity.EntityId))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await CreateSut().CreateEntitiesAsync();
|
||||
|
||||
createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems();
|
||||
createdEntityIds.Should().Contain(
|
||||
[
|
||||
ConfigPowerEntityId,
|
||||
ConfigSwitchEntityId,
|
||||
ConfigPollIntervalEntityId,
|
||||
ConfigHeatingThresholdEntityId,
|
||||
CleanupButtonEntityId,
|
||||
WaterReadyEntityId,
|
||||
TodayRuntimeEntityId,
|
||||
BudgetExhaustedEntityId,
|
||||
AutoManagementEntityId
|
||||
]);
|
||||
|
||||
createdEntityIds.Should()
|
||||
.Contain(
|
||||
[
|
||||
ConfigPowerEntityId,
|
||||
ConfigSwitchEntityId,
|
||||
ConfigPollIntervalEntityId,
|
||||
ConfigHeatingThresholdEntityId,
|
||||
CleanupButtonEntityId,
|
||||
WaterReadyEntityId,
|
||||
TodayRuntimeEntityId,
|
||||
BudgetExhaustedEntityId,
|
||||
AutoManagementEntityId
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity()
|
||||
{
|
||||
_entityManagerMock
|
||||
.Setup(em =>
|
||||
em.CreateEntityAsync(It.Is<EntityCreateModel>(entity => entity.EntityId == CleanupButtonEntityId)))
|
||||
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||
.Setup(em =>
|
||||
em.CreateEntityAsync(It.Is<EntityCreateModel>(entity => entity.EntityId == CleanupButtonEntityId)))
|
||||
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||
|
||||
var act = () => CreateSut().CreateEntitiesAsync();
|
||||
|
||||
await act.Should().NotThrowAsync();
|
||||
|
||||
_entityManagerMock.Invocations
|
||||
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
|
||||
.Should().Be(15);
|
||||
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
|
||||
.Should()
|
||||
.Be(15);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ResetEntitiesAsync
|
||||
|
||||
public static TheoryData<string, string> ResetEntityStates => new()
|
||||
public static TheoryData<string, string> ResetEntityStates => new TheoryData<string, string>
|
||||
{
|
||||
{ StatusEntityId, StatusAwaitingConfiguration },
|
||||
{ WaterReadyEntityId, "unknown" },
|
||||
@@ -422,16 +446,17 @@ public class BoilerMonitorEntityServiceTests
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(10));
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||
Times.Exactly(5));
|
||||
Times.Exactly(5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetEntitiesAsync_WhenEntityManagerThrows_ShouldNotThrow()
|
||||
{
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||
|
||||
var act = () => CreateSut().ResetEntitiesAsync();
|
||||
|
||||
@@ -486,7 +511,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
await CreateSut().CleanupEntitiesAsync();
|
||||
|
||||
foreach (var entityId in CleanableEntityIds)
|
||||
{
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once);
|
||||
}
|
||||
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never);
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(CleanableEntityIds.Length));
|
||||
@@ -496,8 +523,8 @@ public class BoilerMonitorEntityServiceTests
|
||||
public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow()
|
||||
{
|
||||
_entityManagerMock
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Throws(new InvalidOperationException("MQTT unavailable"));
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Throws(new InvalidOperationException("MQTT unavailable"));
|
||||
|
||||
var act = () => CreateSut().CleanupEntitiesAsync();
|
||||
|
||||
@@ -536,12 +563,13 @@ public class BoilerMonitorEntityServiceTests
|
||||
{
|
||||
var canceledToken = new CancellationToken(true);
|
||||
var sut = CreateSut();
|
||||
|
||||
Func<Task> act = operation switch
|
||||
{
|
||||
CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken),
|
||||
CancelableOperation.ResetEntities => () => sut.ResetEntitiesAsync(canceledToken),
|
||||
CancelableOperation.UpdateEntities => () => sut.UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(), canceledToken),
|
||||
BoilerMonitorTestData.CreateUpdateContext(), canceledToken),
|
||||
CancelableOperation.ResetTransientEntities => () => sut.ResetTransientEntitiesAsync(canceledToken),
|
||||
_ => () => sut.CleanupEntitiesAsync(canceledToken)
|
||||
};
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Models;
|
||||
using FluentAssertions;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerMonitorOptionsTests
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using BoilerMonitorManager.Models;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
@@ -6,6 +8,8 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -19,7 +23,7 @@ internal static class BoilerMonitorTestData
|
||||
public const string SwitchEntityId = "switch.sonoff_1002230e32";
|
||||
|
||||
/// <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)
|
||||
{
|
||||
@@ -147,7 +151,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("1e9", TimeSpan.FromSeconds(1e9));
|
||||
|
||||
data.Add(null, null);
|
||||
data.Add("", null);
|
||||
data.Add(string.Empty, null);
|
||||
data.Add(" ", null);
|
||||
data.Add("\t", null);
|
||||
data.Add("unavailable", null);
|
||||
@@ -159,6 +163,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("1e308", null);
|
||||
data.Add("-1", null);
|
||||
data.Add("-0.001", null);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -175,7 +180,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("2147483647", int.MaxValue);
|
||||
|
||||
data.Add(null, null);
|
||||
data.Add("", null);
|
||||
data.Add(string.Empty, null);
|
||||
data.Add(" ", null);
|
||||
data.Add("\t", null);
|
||||
data.Add("unavailable", null);
|
||||
@@ -185,6 +190,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("-1", null);
|
||||
data.Add("2147483648", null);
|
||||
data.Add("1e3", null);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -204,6 +210,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("actively heating", 2_150.0, false);
|
||||
data.Add("maximum", double.MaxValue, false);
|
||||
data.Add("not-a-number", double.NaN, true);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -222,6 +229,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add(TimeSpan.FromHours(25));
|
||||
data.Add(TimeSpan.FromHours(48));
|
||||
data.Add(TimeSpan.FromHours(168));
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -246,33 +254,35 @@ internal static class BoilerMonitorTestData
|
||||
// Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST.
|
||||
// now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z.
|
||||
data.Add(
|
||||
"DST spring-forward, same UTC day",
|
||||
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
|
||||
true
|
||||
);
|
||||
"DST spring-forward, same UTC day",
|
||||
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
|
||||
true
|
||||
);
|
||||
|
||||
data.Add(
|
||||
"DST spring-forward, previous UTC day",
|
||||
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
|
||||
false
|
||||
);
|
||||
"DST spring-forward, previous UTC day",
|
||||
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
|
||||
false
|
||||
);
|
||||
|
||||
// Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice.
|
||||
// now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC.
|
||||
data.Add(
|
||||
"DST fall-back, ambiguous local hour",
|
||||
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
|
||||
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
|
||||
true
|
||||
);
|
||||
"DST fall-back, ambiguous local hour",
|
||||
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
|
||||
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
|
||||
true
|
||||
);
|
||||
|
||||
data.Add(
|
||||
"crossing midnight between restore and now",
|
||||
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
|
||||
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
|
||||
false
|
||||
);
|
||||
"crossing midnight between restore and now",
|
||||
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
|
||||
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
|
||||
false
|
||||
);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
using BoilerMonitorManager;
|
||||
using FluentAssertions;
|
||||
@@ -5,6 +7,8 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using Moq;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class WaterReadyServiceTests
|
||||
@@ -13,7 +17,7 @@ public class WaterReadyServiceTests
|
||||
private const double HighPowerWatts = 2150.0;
|
||||
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
|
||||
|
||||
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new();
|
||||
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new Mock<ILogger<WaterReadyService>>();
|
||||
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
|
||||
|
||||
private WaterReadyService CreateSut()
|
||||
@@ -25,6 +29,7 @@ public class WaterReadyServiceTests
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.RecordHeatingObserved();
|
||||
|
||||
return sut;
|
||||
}
|
||||
|
||||
@@ -36,7 +41,11 @@ public class WaterReadyServiceTests
|
||||
double heatingThresholdWatts = Threshold)
|
||||
{
|
||||
var result = false;
|
||||
for (var i = 0; i < count; i++) result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -119,8 +128,10 @@ public class WaterReadyServiceTests
|
||||
|
||||
sut.ResetCooldown();
|
||||
|
||||
FeedReadings(sut, RequiredReadings).Should().BeTrue(
|
||||
"ResetCooldown clears the cooldown and counter, not the heating observation");
|
||||
FeedReadings(sut, RequiredReadings)
|
||||
.Should()
|
||||
.BeTrue(
|
||||
"ResetCooldown clears the cooldown and counter, not the heating observation");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -261,9 +272,10 @@ public class WaterReadyServiceTests
|
||||
|
||||
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts);
|
||||
|
||||
result.Should().Be(
|
||||
expectedBelowThreshold,
|
||||
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
|
||||
result.Should()
|
||||
.Be(
|
||||
expectedBelowThreshold,
|
||||
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -283,7 +295,7 @@ public class WaterReadyServiceTests
|
||||
var sut = CreateSutWithHeatingObserved();
|
||||
|
||||
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts,
|
||||
heatingThresholdWatts: heatingThresholdWatts);
|
||||
heatingThresholdWatts: heatingThresholdWatts);
|
||||
|
||||
result.Should().Be(expected);
|
||||
}
|
||||
@@ -320,8 +332,12 @@ public class WaterReadyServiceTests
|
||||
_timeProvider.Advance(elapsed);
|
||||
|
||||
sut.IsInCooldown.Should().BeTrue();
|
||||
sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue(
|
||||
"cooldown only clears via explicit ResetCooldown, not by elapsed time");
|
||||
|
||||
sut.IsWaterReady("off", 0.0, Threshold)
|
||||
.Should()
|
||||
.BeTrue(
|
||||
"cooldown only clears via explicit ResetCooldown, not by elapsed time");
|
||||
|
||||
sut.WaterReadySince.Should().Be(triggeredAt);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using BoilerMonitor.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -5,6 +7,8 @@ using NetDaemon.HassModel;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
using static NordPool.Models.NordPoolConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
||||
@@ -14,15 +18,20 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
||||
public BoilerConfig ReadConfig()
|
||||
{
|
||||
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
||||
|
||||
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
|
||||
? dh
|
||||
: DefaultDailyHours;
|
||||
? dh
|
||||
: DefaultDailyHours;
|
||||
|
||||
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
||||
|
||||
if (intervalCount <= 0) intervalCount = IntervalsPerHour;
|
||||
if (intervalCount <= 0)
|
||||
{
|
||||
intervalCount = IntervalsPerHour;
|
||||
}
|
||||
|
||||
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
||||
|
||||
var priceCap =
|
||||
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
|
||||
? pc
|
||||
@@ -43,8 +52,8 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||
intervalCount, priceCap, skipPriceCap, deadline);
|
||||
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||
intervalCount, priceCap, skipPriceCap, deadline);
|
||||
}
|
||||
|
||||
var config = new BoilerConfig
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models.Enums;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
||||
@@ -25,8 +29,8 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||
currentSwitchState);
|
||||
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||
currentSwitchState);
|
||||
}
|
||||
|
||||
return BoilerAction.TurnOn;
|
||||
@@ -38,7 +42,7 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason,
|
||||
currentSwitchState);
|
||||
currentSwitchState);
|
||||
}
|
||||
|
||||
return BoilerAction.TurnOff;
|
||||
@@ -48,8 +52,8 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||
}
|
||||
|
||||
return BoilerAction.NoChange;
|
||||
@@ -58,10 +62,13 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
|
||||
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
|
||||
{
|
||||
if (waterReady) return "water is already ready";
|
||||
if (waterReady)
|
||||
{
|
||||
return "water is already ready";
|
||||
}
|
||||
|
||||
return effectiveBudgetExhausted
|
||||
? "daily budget is exhausted"
|
||||
: "not in a cheap interval";
|
||||
? "daily budget is exhausted"
|
||||
: "not in a cheap interval";
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using BoilerMonitor.Models;
|
||||
@@ -9,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager;
|
||||
using NetDaemon.HassModel;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class BoilerMonitorEntityService(
|
||||
@@ -41,21 +45,21 @@ public sealed class BoilerMonitorEntityService(
|
||||
var entities = GetAllEntities();
|
||||
|
||||
var createTasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(createTasks).ConfigureAwait(false);
|
||||
}
|
||||
@@ -67,17 +71,18 @@ public sealed class BoilerMonitorEntityService(
|
||||
logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults");
|
||||
|
||||
await Task.WhenAll(
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync(),
|
||||
ResetSkipPriceCapAsync(),
|
||||
ResetTodayRuntimeAsync(),
|
||||
ResetRemainingTimeAsync(),
|
||||
ResetBudgetPercentageAsync(),
|
||||
ResetBudgetExhaustedAsync(),
|
||||
ResetSessionCountAsync(),
|
||||
ResetBudgetOverrideAsync(),
|
||||
ResetAutoManagementAsync()
|
||||
).ConfigureAwait(false);
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync(),
|
||||
ResetSkipPriceCapAsync(),
|
||||
ResetTodayRuntimeAsync(),
|
||||
ResetRemainingTimeAsync(),
|
||||
ResetBudgetPercentageAsync(),
|
||||
ResetBudgetExhaustedAsync(),
|
||||
ResetSessionCountAsync(),
|
||||
ResetBudgetOverrideAsync(),
|
||||
ResetAutoManagementAsync()
|
||||
)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
||||
}
|
||||
@@ -118,6 +123,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -129,9 +135,10 @@ public sealed class BoilerMonitorEntityService(
|
||||
logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)");
|
||||
|
||||
await Task.WhenAll(
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync()
|
||||
).ConfigureAwait(false);
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync()
|
||||
)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public PersistedBoilerState? ReadPersistedState()
|
||||
@@ -149,8 +156,8 @@ public sealed class BoilerMonitorEntityService(
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||
runtimeState, sessionCountState);
|
||||
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||
runtimeState, sessionCountState);
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -167,9 +174,9 @@ public sealed class BoilerMonitorEntityService(
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||
persisted.BudgetOverrideState);
|
||||
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||
persisted.BudgetOverrideState);
|
||||
}
|
||||
|
||||
return persisted;
|
||||
@@ -177,6 +184,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -191,9 +199,16 @@ public sealed class BoilerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
var entity = haContext.GetState(WaterReadyEntityId);
|
||||
if (entity?.Attributes is not IDictionary<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
|
||||
{
|
||||
@@ -205,7 +220,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
|
||||
if (stringValue is not null &&
|
||||
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out var parsed))
|
||||
DateTimeStyles.RoundtripKind, out var parsed))
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
@@ -237,10 +252,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
||||
{
|
||||
seconds = 0;
|
||||
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state)
|
||||
&& state is not ("unavailable" or "unknown")
|
||||
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
|
||||
&& seconds >= 0;
|
||||
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
|
||||
|
||||
return tryParseEntitySeconds;
|
||||
}
|
||||
@@ -248,10 +260,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
private static bool TryParseEntityInt(string? state, out int value)
|
||||
{
|
||||
value = 0;
|
||||
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state)
|
||||
&& state is not ("unavailable" or "unknown")
|
||||
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
|
||||
&& value >= 0;
|
||||
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
|
||||
|
||||
return tryParseEntityInt;
|
||||
}
|
||||
@@ -283,7 +292,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
}
|
||||
},
|
||||
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
|
||||
"Heating power threshold (watts)")
|
||||
"Heating power threshold (watts)")
|
||||
{
|
||||
AdditionalConfig = new
|
||||
{
|
||||
@@ -362,14 +371,16 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task ResetWaterReadyAsync()
|
||||
{
|
||||
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||
{
|
||||
boiler_switch_state = "unknown",
|
||||
boiler_power_watts = 0.0,
|
||||
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
boiler_switch_state = "unknown",
|
||||
boiler_power_watts = 0.0,
|
||||
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetSkipPriceCapAsync()
|
||||
@@ -380,35 +391,41 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task ResetTodayRuntimeAsync()
|
||||
{
|
||||
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetRemainingTimeAsync()
|
||||
{
|
||||
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
budget_hours = 0.0,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
budget_hours = 0.0,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetBudgetPercentageAsync()
|
||||
{
|
||||
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetBudgetExhaustedAsync()
|
||||
@@ -419,11 +436,13 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task ResetSessionCountAsync()
|
||||
{
|
||||
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetBudgetOverrideAsync()
|
||||
@@ -439,54 +458,68 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||
{
|
||||
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(TodayRuntimeEntityId,
|
||||
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||
{
|
||||
formatted,
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted,
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours,
|
||||
string timestamp)
|
||||
private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
|
||||
string formatted,
|
||||
double budgetHours,
|
||||
string timestamp)
|
||||
{
|
||||
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
||||
|
||||
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||
{
|
||||
formatted,
|
||||
budget_hours = budgetHours,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted,
|
||||
budget_hours = budgetHours,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
||||
{
|
||||
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
||||
|
||||
await SetEntityStateSafe(BudgetPercentageEntityId,
|
||||
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
||||
@@ -497,12 +530,14 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task SetEntityStateSafe(string entityId, string state)
|
||||
@@ -510,6 +545,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
||||
@@ -526,6 +562,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Reactive.Concurrency;
|
||||
using System.Text.Json;
|
||||
@@ -13,6 +15,8 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -45,17 +49,17 @@ public sealed class BoilerMonitorInit
|
||||
IOptions<BoilerMonitorOptions> options,
|
||||
TimeProvider timeProvider)
|
||||
: this(
|
||||
haContext,
|
||||
logger,
|
||||
scheduler,
|
||||
mqttEntityManager,
|
||||
boilerControlService,
|
||||
tracker,
|
||||
entityService,
|
||||
waterReadyService,
|
||||
options,
|
||||
timeProvider,
|
||||
true)
|
||||
haContext,
|
||||
logger,
|
||||
scheduler,
|
||||
mqttEntityManager,
|
||||
boilerControlService,
|
||||
tracker,
|
||||
entityService,
|
||||
waterReadyService,
|
||||
options,
|
||||
timeProvider,
|
||||
true)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -83,7 +87,10 @@ public sealed class BoilerMonitorInit
|
||||
_options = options.Value;
|
||||
_timeProvider = timeProvider;
|
||||
|
||||
if (startBackgroundScheduling) _ = InitializeAndScheduleAsync();
|
||||
if (startBackgroundScheduling)
|
||||
{
|
||||
_ = InitializeAndScheduleAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task InitializeAndScheduleAsync()
|
||||
@@ -130,14 +137,18 @@ public sealed class BoilerMonitorInit
|
||||
{
|
||||
_tracker.RestoreFromSnapshot();
|
||||
|
||||
if (persistedCooldown.HasValue) _waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||
if (persistedCooldown.HasValue)
|
||||
{
|
||||
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||
}
|
||||
|
||||
await _entityService.ResetTransientEntitiesAsync();
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -156,6 +167,7 @@ public sealed class BoilerMonitorInit
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -171,105 +183,126 @@ public sealed class BoilerMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
|
||||
DefaultPollIntervalSeconds, nextPollTime);
|
||||
DefaultPollIntervalSeconds, nextPollTime);
|
||||
}
|
||||
|
||||
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
|
||||
() => _ = PollAndUpdateAsync());
|
||||
() => _ = PollAndUpdateAsync());
|
||||
}
|
||||
|
||||
private void ScheduleMidnightReset()
|
||||
{
|
||||
_scheduler.ScheduleCron("0 0 * * *", () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||
_tracker.Reset();
|
||||
_waterReadyService.ResetCooldown();
|
||||
_lastWaterReadyNotificationSentAt = null;
|
||||
_ = _entityService.ResetEntitiesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during midnight reset");
|
||||
}
|
||||
});
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||
_tracker.Reset();
|
||||
_waterReadyService.ResetCooldown();
|
||||
_lastWaterReadyNotificationSentAt = null;
|
||||
_ = _entityService.ResetEntitiesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during midnight reset");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ScheduleEndOfDayReminder()
|
||||
{
|
||||
_scheduler.ScheduleCron("0 22 * * *", () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return;
|
||||
{
|
||||
try
|
||||
{
|
||||
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||
|
||||
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||
{
|
||||
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
|
||||
title = "Boiler reminder"
|
||||
});
|
||||
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||
}
|
||||
});
|
||||
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||
{
|
||||
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
|
||||
title = "Boiler reminder"
|
||||
});
|
||||
|
||||
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToSkipPriceCapChanges()
|
||||
{
|
||||
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
||||
skipPriceCapSwitch.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State) return;
|
||||
|
||||
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
skipPriceCapSwitch.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToAutoManagementChanges()
|
||||
{
|
||||
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
|
||||
autoManagementSwitch.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State) return;
|
||||
|
||||
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
autoManagementSwitch.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToShowerState()
|
||||
{
|
||||
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
|
||||
|
||||
showerStateSensor.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) return;
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_waterReadyService.IsInCooldown) return;
|
||||
if (!_waterReadyService.IsInCooldown)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
|
||||
_waterReadyService.ResetCooldown();
|
||||
});
|
||||
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
|
||||
_waterReadyService.ResetCooldown();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToCleanupButton()
|
||||
{
|
||||
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
||||
|
||||
cleanupButton.StateChanges()
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
|
||||
Task.Run(HandleCleanupAsync);
|
||||
});
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
|
||||
Task.Run(HandleCleanupAsync);
|
||||
});
|
||||
}
|
||||
|
||||
private async Task SubscribeToConfigCommandsAsync()
|
||||
@@ -359,6 +392,7 @@ public sealed class BoilerMonitorInit
|
||||
if (_cleanedUp)
|
||||
{
|
||||
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -369,21 +403,27 @@ public sealed class BoilerMonitorInit
|
||||
if (!config.IsFullyConfigured)
|
||||
{
|
||||
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
||||
|
||||
_logger.LogWarning(
|
||||
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
||||
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
||||
|
||||
var isHeating = boilerPowerWatts.HasValue &&
|
||||
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
||||
|
||||
_tracker.RecordPollResult();
|
||||
|
||||
if (isHeating) _waterReadyService.RecordHeatingObserved();
|
||||
if (isHeating)
|
||||
{
|
||||
_waterReadyService.RecordHeatingObserved();
|
||||
}
|
||||
|
||||
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
||||
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
||||
@@ -397,7 +437,7 @@ public sealed class BoilerMonitorInit
|
||||
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
||||
|
||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
|
||||
config.HeatingPowerThresholdWatts!.Value);
|
||||
config.HeatingPowerThresholdWatts!.Value);
|
||||
|
||||
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
||||
{
|
||||
@@ -406,6 +446,7 @@ public sealed class BoilerMonitorInit
|
||||
message = "Hot water is ready.",
|
||||
title = "Boiler"
|
||||
});
|
||||
|
||||
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
||||
_logger.LogInformation("Water ready notification sent");
|
||||
}
|
||||
@@ -416,24 +457,28 @@ public sealed class BoilerMonitorInit
|
||||
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
||||
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
|
||||
|
||||
if (remainingTime < TimeSpan.Zero) remainingTime = TimeSpan.Zero;
|
||||
if (remainingTime < TimeSpan.Zero)
|
||||
{
|
||||
remainingTime = TimeSpan.Zero;
|
||||
}
|
||||
|
||||
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
||||
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
|
||||
: 0.0;
|
||||
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
|
||||
: 0.0;
|
||||
|
||||
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
||||
|
||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||
|
||||
var boilerAction = _boilerControlService.DetermineAction(
|
||||
effectiveIsNowCheap,
|
||||
waterReady,
|
||||
boilerSwitchState,
|
||||
budgetExhausted,
|
||||
budgetOverride);
|
||||
effectiveIsNowCheap,
|
||||
waterReady,
|
||||
boilerSwitchState,
|
||||
budgetExhausted,
|
||||
budgetOverride);
|
||||
|
||||
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
||||
|
||||
var autoManagementEnabled =
|
||||
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
@@ -468,8 +513,8 @@ public sealed class BoilerMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -485,12 +530,17 @@ public sealed class BoilerMonitorInit
|
||||
case BoilerAction.TurnOn:
|
||||
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
||||
_waterReadyService.NotifyTurnedOn();
|
||||
|
||||
break;
|
||||
|
||||
case BoilerAction.TurnOff:
|
||||
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
||||
|
||||
break;
|
||||
|
||||
case BoilerAction.NoChange:
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
||||
}
|
||||
@@ -504,9 +554,7 @@ public sealed class BoilerMonitorInit
|
||||
int? pollInterval = null;
|
||||
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(pollIntervalState)
|
||||
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
|
||||
&& pollIntervalValue > 0)
|
||||
if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
|
||||
{
|
||||
pollInterval = (int)pollIntervalValue;
|
||||
}
|
||||
@@ -514,9 +562,7 @@ public sealed class BoilerMonitorInit
|
||||
double? heatingThreshold = null;
|
||||
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(thresholdState)
|
||||
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
|
||||
&& thresholdValue > 0)
|
||||
if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
|
||||
{
|
||||
heatingThreshold = thresholdValue;
|
||||
}
|
||||
@@ -534,14 +580,20 @@ public sealed class BoilerMonitorInit
|
||||
{
|
||||
var state = _haContext.GetState(entityId);
|
||||
|
||||
if (state?.State is null or "unavailable" or "unknown") return null;
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
|
||||
}
|
||||
|
||||
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
||||
{
|
||||
if (entityState?.Attributes is not IDictionary<string, object> attributes) return false;
|
||||
if (entityState?.Attributes is not IDictionary<string, object> attributes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
@@ -569,9 +621,13 @@ public sealed class BoilerMonitorInit
|
||||
|
||||
private bool IsWithinNotificationCooldown()
|
||||
{
|
||||
if (_lastWaterReadyNotificationSentAt is null) return false;
|
||||
if (_lastWaterReadyNotificationSentAt is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
||||
|
||||
return elapsed < WaterReadyNotificationCooldown;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Interface;
|
||||
using BoilerMonitorManager.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public static class BoilerMonitorServiceRegistration
|
||||
@@ -11,17 +15,21 @@ public static class BoilerMonitorServiceRegistration
|
||||
public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var options = configuration
|
||||
.GetSection(BoilerMonitorOptions.SectionName)
|
||||
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
||||
.GetSection(BoilerMonitorOptions.SectionName)
|
||||
.Get<BoilerMonitorOptions>() ??
|
||||
new BoilerMonitorOptions();
|
||||
|
||||
if (!options.Enabled) return services;
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
}
|
||||
|
||||
services
|
||||
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Interface;
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models.Enums;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager.Interface;
|
||||
|
||||
public interface IBoilerControlService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager.Interface;
|
||||
|
||||
public interface IBoilerMonitorEntityService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager.Interface;
|
||||
|
||||
public interface IBoilerRunTimeTracker
|
||||
|
||||
@@ -7,9 +7,8 @@ public record BoilerMonitorConfig
|
||||
public int? PollIntervalSeconds { get; init; }
|
||||
public double? HeatingPowerThresholdWatts { get; init; }
|
||||
|
||||
public bool IsFullyConfigured =>
|
||||
!string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||
PollIntervalSeconds is > 0 &&
|
||||
HeatingPowerThresholdWatts is > 0;
|
||||
public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||
PollIntervalSeconds is > 0 &&
|
||||
HeatingPowerThresholdWatts is > 0;
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
||||
{
|
||||
private const string SwitchOnState = "on";
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Lock _lock = new Lock();
|
||||
private int _consecutiveBelowThresholdCount;
|
||||
private bool _hasObservedHeating;
|
||||
private DateTimeOffset? _waterReadySince;
|
||||
@@ -43,16 +47,22 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
|
||||
_waterReadySince);
|
||||
_waterReadySince);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (switchState is null || powerWatts is null) return false;
|
||||
if (switchState is null || powerWatts is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
@@ -61,7 +71,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
||||
powerWatts.Value);
|
||||
powerWatts.Value);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -70,6 +80,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (powerWatts.Value >= heatingThresholdWatts)
|
||||
{
|
||||
_consecutiveBelowThresholdCount = 0;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -80,9 +91,9 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
||||
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
||||
powerWatts.Value);
|
||||
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
||||
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
||||
powerWatts.Value);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -93,8 +104,8 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||
_consecutiveBelowThresholdCount);
|
||||
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||
_consecutiveBelowThresholdCount);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -110,14 +121,17 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
}
|
||||
|
||||
logger.LogDebug(
|
||||
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
||||
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
||||
}
|
||||
|
||||
public void RecordHeatingObserved()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_hasObservedHeating) return;
|
||||
if (_hasObservedHeating)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_hasObservedHeating = true;
|
||||
}
|
||||
@@ -141,18 +155,20 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
lock (_lock)
|
||||
{
|
||||
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
||||
|
||||
if (waterReadySince < todayMidnightUtc)
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
|
||||
waterReadySince);
|
||||
waterReadySince);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_waterReadySince = waterReadySince;
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using HomeAssistant.Models;
|
||||
using NetDaemon.Extensions.MqttEntityManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Models;
|
||||
|
||||
public class BoilerMonitorEntity : EntityCreateModel
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
#region
|
||||
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using HomeAssistant.Models;
|
||||
using HomeAssistantGenerated;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NetDaemon.Extensions.MqttEntityManager;
|
||||
using NetDaemon.HassModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace HomeAssistant.Entities;
|
||||
|
||||
public class EntityManager(
|
||||
@@ -53,12 +57,14 @@ public class EntityManager(
|
||||
var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix);
|
||||
|
||||
foreach (var suffix in CleanupTopicSuffixes)
|
||||
{
|
||||
haContext.CallService("mqtt", "publish", null, new MqttPublishParameters
|
||||
{
|
||||
Topic = $"{rootTopic}/{suffix}",
|
||||
Payload = string.Empty,
|
||||
Retain = true
|
||||
});
|
||||
}
|
||||
|
||||
// IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket.
|
||||
return Task.CompletedTask;
|
||||
@@ -67,11 +73,12 @@ public class EntityManager(
|
||||
private static string BuildRootTopic(string entityId, string discoveryPrefix)
|
||||
{
|
||||
var separatorIndex = entityId.IndexOf('.');
|
||||
|
||||
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
|
||||
nameof(entityId));
|
||||
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
|
||||
nameof(entityId));
|
||||
}
|
||||
|
||||
var domain = entityId[..separatorIndex];
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
using HomeAssistant.Models;
|
||||
#region
|
||||
|
||||
using HomeAssistant.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace HomeAssistant.Entities.Interfaces;
|
||||
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
using NetDaemon.Extensions.MqttEntityManager;
|
||||
#region
|
||||
|
||||
using NetDaemon.Extensions.MqttEntityManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace HomeAssistant.Models;
|
||||
|
||||
public class EntityCreateModel
|
||||
{
|
||||
public string? EntityId { get; protected init; }
|
||||
public EntityCreationOptions? Options { get; init; } = new();
|
||||
public EntityCreationOptions? Options { get; init; } = new EntityCreationOptions();
|
||||
public object? AdditionalConfig { get; init; }
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
#region
|
||||
|
||||
using System;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Serilog;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace HomeAssistantServer;
|
||||
|
||||
public static class CustomLoggingProvider
|
||||
@@ -10,14 +14,14 @@ public static class CustomLoggingProvider
|
||||
public static IHostBuilder UseCustomLogging(this IHostBuilder builder)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddJsonFile("appsettings.json")
|
||||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json",
|
||||
true)
|
||||
.Build();
|
||||
.AddJsonFile("appsettings.json")
|
||||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json",
|
||||
true)
|
||||
.Build();
|
||||
|
||||
var logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(configuration)
|
||||
.CreateLogger();
|
||||
.ReadFrom.Configuration(configuration)
|
||||
.CreateLogger();
|
||||
|
||||
return builder.UseSerilog(logger);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
@@ -13,6 +15,8 @@ using NordPoolManager.Interface;
|
||||
using PowerMonitorManager.Interface;
|
||||
using ShowerMonitorManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace HomeAssistantServer;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -50,23 +54,24 @@ public sealed class MqttRecreateApp
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
|
||||
await _mqttEntityManager.CreateAsync(
|
||||
RecreateButtonEntityId,
|
||||
new EntityCreationOptions
|
||||
{
|
||||
UniqueId = RecreateButtonEntityId,
|
||||
Name = "Recreate all MQTT entities"
|
||||
},
|
||||
new
|
||||
{
|
||||
icon = "mdi:refresh",
|
||||
device = new
|
||||
{
|
||||
identifiers = AppDaemonIdentifiers,
|
||||
name = "AppDaemon",
|
||||
model = "AppDaemon",
|
||||
manufacturer = "HomeAssistant App Daemon"
|
||||
}
|
||||
}).ConfigureAwait(false);
|
||||
RecreateButtonEntityId,
|
||||
new EntityCreationOptions
|
||||
{
|
||||
UniqueId = RecreateButtonEntityId,
|
||||
Name = "Recreate all MQTT entities"
|
||||
},
|
||||
new
|
||||
{
|
||||
icon = "mdi:refresh",
|
||||
device = new
|
||||
{
|
||||
identifiers = AppDaemonIdentifiers,
|
||||
name = "AppDaemon",
|
||||
model = "AppDaemon",
|
||||
manufacturer = "HomeAssistant App Daemon"
|
||||
}
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
@@ -74,12 +79,13 @@ public sealed class MqttRecreateApp
|
||||
}
|
||||
|
||||
var button = new Entity(_haContext, RecreateButtonEntityId);
|
||||
|
||||
button.StateChanges()
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Recreate-all button pressed, recreating all MQTT entities");
|
||||
Task.Run(HandleRecreateAsync);
|
||||
});
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Recreate-all button pressed, recreating all MQTT entities");
|
||||
Task.Run(HandleRecreateAsync);
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -107,9 +113,11 @@ public sealed class MqttRecreateApp
|
||||
private async Task RecreateNordPoolAsync()
|
||||
{
|
||||
var entityService = _serviceProvider.GetService<INordPoolEntityService>();
|
||||
|
||||
if (entityService is null)
|
||||
{
|
||||
_logger.LogDebug("NordPool entity service not registered (disabled), skipping");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -132,9 +140,11 @@ public sealed class MqttRecreateApp
|
||||
private async Task RecreateBoilerMonitorAsync()
|
||||
{
|
||||
var entityService = _serviceProvider.GetService<IBoilerMonitorEntityService>();
|
||||
|
||||
if (entityService is null)
|
||||
{
|
||||
_logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -155,9 +165,11 @@ public sealed class MqttRecreateApp
|
||||
private async Task RecreateShowerMonitorAsync()
|
||||
{
|
||||
var entityService = _serviceProvider.GetService<IShowerMonitorEntityService>();
|
||||
|
||||
if (entityService is null)
|
||||
{
|
||||
_logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -177,9 +189,11 @@ public sealed class MqttRecreateApp
|
||||
private async Task RecreatePowerMonitorAsync()
|
||||
{
|
||||
var entityService = _serviceProvider.GetService<IPowerMonitorEntityService>();
|
||||
|
||||
if (entityService is null)
|
||||
{
|
||||
_logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -202,14 +216,13 @@ public sealed class MqttRecreateApp
|
||||
try
|
||||
{
|
||||
var state = _haContext.GetState(NordPoolPriceEntityId);
|
||||
|
||||
if (state?.Attributes is IDictionary<string, object> attributes &&
|
||||
attributes.TryGetValue("unit_of_measurement", out var value))
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
string s => s,
|
||||
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
|
||||
_ => null
|
||||
string s => s, JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), _ => null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using BatteryMonitorManager;
|
||||
@@ -28,47 +30,50 @@ using PowerMonitorManager.Models;
|
||||
using ShowerMonitorManager;
|
||||
using ShowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
try
|
||||
{
|
||||
var app = Host.CreateDefaultBuilder(args)
|
||||
.UseNetDaemonAppSettings()
|
||||
.UseCustomLogging()
|
||||
.UseNetDaemonRuntime()
|
||||
.UseNetDaemonTextToSpeech()
|
||||
.ConfigureServices((context, services) =>
|
||||
{
|
||||
services
|
||||
.AddNetDaemonMqttEntityManagement()
|
||||
.AddAppsFromAssembly(Assembly.GetExecutingAssembly())
|
||||
.AddNetDaemonStateManager()
|
||||
.AddNetDaemonScheduler()
|
||||
.AddHomeAssistantGenerated()
|
||||
.AddAutoMapper(config =>
|
||||
{
|
||||
config.LicenseKey =
|
||||
"eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g";
|
||||
config.AddProfile<NordPoolMappingProfile>();
|
||||
config.AddProfile<GlobalMappingProfile>();
|
||||
})
|
||||
.AddTransient<IEntityManager, EntityManager>()
|
||||
.AddSingleton(TimeProvider.System)
|
||||
.AddScoped<IBoilerConfigReader, BoilerConfigReader>()
|
||||
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
||||
.AddNordPool()
|
||||
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||
.AddPowerMonitor()
|
||||
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
||||
.AddBoilerMonitor(context.Configuration)
|
||||
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
|
||||
.AddShowerMonitor(context.Configuration)
|
||||
.Configure<LightMonitorOptions>(context.Configuration.GetSection(LightMonitorOptions.SectionName))
|
||||
.AddLightMonitor(context.Configuration)
|
||||
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
|
||||
.AddBatteryMonitor(context.Configuration)
|
||||
.Configure<LeakMonitorOptions>(context.Configuration.GetSection(LeakMonitorOptions.SectionName))
|
||||
.AddLeakMonitor(context.Configuration);
|
||||
})
|
||||
.Build();
|
||||
.UseNetDaemonAppSettings()
|
||||
.UseCustomLogging()
|
||||
.UseNetDaemonRuntime()
|
||||
.UseNetDaemonTextToSpeech()
|
||||
.ConfigureServices((context, services) =>
|
||||
{
|
||||
services
|
||||
.AddNetDaemonMqttEntityManagement()
|
||||
.AddAppsFromAssembly(Assembly.GetExecutingAssembly())
|
||||
.AddNetDaemonStateManager()
|
||||
.AddNetDaemonScheduler()
|
||||
.AddHomeAssistantGenerated()
|
||||
.AddAutoMapper(config =>
|
||||
{
|
||||
config.LicenseKey =
|
||||
"eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g";
|
||||
|
||||
config.AddProfile<NordPoolMappingProfile>();
|
||||
config.AddProfile<GlobalMappingProfile>();
|
||||
})
|
||||
.AddTransient<IEntityManager, EntityManager>()
|
||||
.AddSingleton(TimeProvider.System)
|
||||
.AddScoped<IBoilerConfigReader, BoilerConfigReader>()
|
||||
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
||||
.AddNordPool()
|
||||
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||
.AddPowerMonitor()
|
||||
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
||||
.AddBoilerMonitor(context.Configuration)
|
||||
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
|
||||
.AddShowerMonitor(context.Configuration)
|
||||
.Configure<LightMonitorOptions>(context.Configuration.GetSection(LightMonitorOptions.SectionName))
|
||||
.AddLightMonitor(context.Configuration)
|
||||
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
|
||||
.AddBatteryMonitor(context.Configuration)
|
||||
.Configure<LeakMonitorOptions>(context.Configuration.GetSection(LeakMonitorOptions.SectionName))
|
||||
.AddLeakMonitor(context.Configuration);
|
||||
})
|
||||
.Build();
|
||||
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using LeakMonitor.Models;
|
||||
using LeakMonitorManager;
|
||||
@@ -9,14 +11,16 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LeakMonitor.Manager.Tests;
|
||||
|
||||
public class LeakMonitorInitTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new();
|
||||
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new();
|
||||
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new Mock<ILogger<LeakMonitorInit>>();
|
||||
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new Mock<ILeakNotificationService>();
|
||||
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new LeakMonitorTestData.TrackingObservable<StateChange>();
|
||||
|
||||
public LeakMonitorInitTests()
|
||||
{
|
||||
@@ -27,10 +31,10 @@ public class LeakMonitorInitTests
|
||||
private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null)
|
||||
{
|
||||
return new LeakMonitorInit(
|
||||
_haContextMock.Object,
|
||||
_notificationServiceMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(options ?? LeakMonitorTestData.CreateOptions()));
|
||||
_haContextMock.Object,
|
||||
_notificationServiceMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(options ?? LeakMonitorTestData.CreateOptions()));
|
||||
}
|
||||
|
||||
private void VerifyNotifications(Times expected)
|
||||
@@ -42,9 +46,9 @@ public class LeakMonitorInitTests
|
||||
private void VerifyLogged(LogLevel level, Times times)
|
||||
{
|
||||
var logCount = _loggerMock.Invocations.Count(invocation =>
|
||||
invocation.Method.Name == nameof(ILogger.Log) &&
|
||||
invocation.Arguments[0] is LogLevel loggedLevel &&
|
||||
loggedLevel == level);
|
||||
invocation.Method.Name == nameof(ILogger.Log) &&
|
||||
invocation.Arguments[0] is LogLevel loggedLevel &&
|
||||
loggedLevel == level);
|
||||
|
||||
times.Validate(logCount);
|
||||
}
|
||||
@@ -56,11 +60,12 @@ public class LeakMonitorInitTests
|
||||
public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
newState);
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
newState);
|
||||
|
||||
sut.HandleStateChange(sensorEntityId, change);
|
||||
|
||||
@@ -73,11 +78,12 @@ public class LeakMonitorInitTests
|
||||
public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState);
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState);
|
||||
|
||||
sut.HandleStateChange(sensorEntityId, change);
|
||||
|
||||
@@ -90,11 +96,12 @@ public class LeakMonitorInitTests
|
||||
public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState);
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState);
|
||||
|
||||
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||
|
||||
@@ -107,18 +114,20 @@ public class LeakMonitorInitTests
|
||||
// Deduplication is the notification service's job (cooldown); the init handler
|
||||
// forwards each "on" event it receives.
|
||||
var sut = CreateSut();
|
||||
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterDetectedState);
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterDetectedState);
|
||||
|
||||
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
|
||||
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never());
|
||||
}
|
||||
|
||||
@@ -127,11 +136,12 @@ public class LeakMonitorInitTests
|
||||
public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState);
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState);
|
||||
|
||||
sut.HandleStateChange(sensorEntityId, change);
|
||||
|
||||
@@ -160,9 +170,10 @@ public class LeakMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length);
|
||||
|
||||
_haContextMock.Verify(
|
||||
h => h.StateAllChanges(),
|
||||
Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||
h => h.StateAllChanges(),
|
||||
Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -174,10 +185,10 @@ public class LeakMonitorInitTests
|
||||
_stateChanges.SubscriptionCount.Should().Be(1);
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||
}
|
||||
@@ -186,22 +197,23 @@ public class LeakMonitorInitTests
|
||||
public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors()
|
||||
{
|
||||
CreateSut(LeakMonitorTestData.CreateOptions(
|
||||
[null!, LeakMonitorTestData.BoilerSensorId]));
|
||||
[null!, LeakMonitorTestData.BoilerSensorId]));
|
||||
|
||||
_stateChanges.SubscriptionCount.Should().Be(2);
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.BoilerSensorId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.BoilerSensorId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId),
|
||||
Times.Once());
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId),
|
||||
Times.Once());
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Never());
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -213,15 +225,16 @@ public class LeakMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
newState));
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
newState));
|
||||
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(It.Is<string>(id => id != sensorEntityId)),
|
||||
Times.Never());
|
||||
n => n.SendLeakAlert(It.Is<string>(id => id != sensorEntityId)),
|
||||
Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -233,10 +246,10 @@ public class LeakMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState));
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState));
|
||||
|
||||
_notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once());
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny<string>()), Times.Never());
|
||||
@@ -249,10 +262,10 @@ public class LeakMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState));
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState));
|
||||
|
||||
VerifyNotifications(Times.Never());
|
||||
}
|
||||
@@ -263,10 +276,10 @@ public class LeakMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
VerifyNotifications(Times.Never());
|
||||
}
|
||||
@@ -277,10 +290,10 @@ public class LeakMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
"binary_sensor.unrelated_motion",
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
_haContextMock.Object,
|
||||
"binary_sensor.unrelated_motion",
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
VerifyNotifications(Times.Never());
|
||||
}
|
||||
@@ -291,55 +304,58 @@ public class LeakMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
foreach (var change in LeakMonitorTestData.CreateStateChangeSequence(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorTestData.DetectionSequence))
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorTestData.DetectionSequence))
|
||||
{
|
||||
_stateChanges.Publish(change);
|
||||
}
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenNotificationServiceThrows_ShouldLogErrorAndKeepMonitoring()
|
||||
{
|
||||
_notificationServiceMock
|
||||
.Setup(n => n.SendLeakAlert(It.IsAny<string>()))
|
||||
.Throws(new InvalidOperationException("notification failed"));
|
||||
.Setup(n => n.SendLeakAlert(It.IsAny<string>()))
|
||||
.Throws(new InvalidOperationException("notification failed"));
|
||||
|
||||
CreateSut();
|
||||
|
||||
var act = () => _stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
act.Should().NotThrow();
|
||||
VerifyLogged(LogLevel.Error, Times.Once());
|
||||
|
||||
// The failed event must not tear down the subscription.
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterClearedState));
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterClearedState));
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Once());
|
||||
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Once());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenSubscriptionFails_ShouldSwallowAndLogError()
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(h => h.StateAllChanges())
|
||||
.Throws(new InvalidOperationException("home assistant offline"));
|
||||
.Setup(h => h.StateAllChanges())
|
||||
.Throws(new InvalidOperationException("home assistant offline"));
|
||||
|
||||
var act = () => CreateSut();
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using LeakMonitor.Models;
|
||||
using LeakMonitorManager.Models;
|
||||
@@ -5,6 +7,8 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LeakMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -20,12 +24,12 @@ internal static class LeakMonitorTestData
|
||||
|
||||
public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId];
|
||||
|
||||
private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
||||
private static readonly DateTimeOffset DefaultStart = new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <summary>
|
||||
/// Every casing of the "water detected" state, across both configured sensors.
|
||||
/// </summary>
|
||||
public static TheoryData<string, string?> WaterDetectedCases { get; } = new()
|
||||
public static TheoryData<string, string?> WaterDetectedCases { get; } = new TheoryData<string, string?>
|
||||
{
|
||||
{ AquariumSensorId, LeakMonitorConsts.WaterDetectedState },
|
||||
{ AquariumSensorId, "ON" },
|
||||
@@ -37,7 +41,7 @@ internal static class LeakMonitorTestData
|
||||
/// <summary>
|
||||
/// Every casing of the "water cleared" state, across both configured sensors.
|
||||
/// </summary>
|
||||
public static TheoryData<string, string?> WaterClearedCases { get; } = new()
|
||||
public static TheoryData<string, string?> WaterClearedCases { get; } = new TheoryData<string, string?>
|
||||
{
|
||||
{ AquariumSensorId, LeakMonitorConsts.WaterClearedState },
|
||||
{ AquariumSensorId, "OFF" },
|
||||
@@ -83,7 +87,7 @@ internal static class LeakMonitorTestData
|
||||
/// (sensor id, expected notification id) rows for the id sanitising rules:
|
||||
/// dots become underscores, other characters and blanks are preserved.
|
||||
/// </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" },
|
||||
{ BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" },
|
||||
@@ -100,7 +104,7 @@ internal static class LeakMonitorTestData
|
||||
/// rows straddling the strict <c>elapsed < cooldown</c> boundary, plus zero, negative
|
||||
/// and int-max cooldowns.
|
||||
/// </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, 299, 1 },
|
||||
@@ -172,7 +176,7 @@ internal static class LeakMonitorTestData
|
||||
string? newState)
|
||||
{
|
||||
return new StateChange(new Entity(haContext, entityId), CreateOptionalState(oldState),
|
||||
CreateOptionalState(newState));
|
||||
CreateOptionalState(newState));
|
||||
}
|
||||
|
||||
public static IReadOnlyList<StateChange> CreateStateChangeSequence(
|
||||
@@ -183,7 +187,7 @@ internal static class LeakMonitorTestData
|
||||
return
|
||||
[
|
||||
.. transitions.Select(transition =>
|
||||
CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))
|
||||
CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -196,13 +200,13 @@ internal static class LeakMonitorTestData
|
||||
var calls = new List<ServiceCall>();
|
||||
|
||||
haContextMock
|
||||
.Setup(h => h.CallService(
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((domain, service, target, data) =>
|
||||
calls.Add(new ServiceCall(domain, service, target, data)));
|
||||
.Setup(h => h.CallService(
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<string>(),
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((domain, service, target, data) =>
|
||||
calls.Add(new ServiceCall(domain, service, target, data)));
|
||||
|
||||
return calls;
|
||||
}
|
||||
@@ -258,7 +262,10 @@ internal static class LeakMonitorTestData
|
||||
|
||||
public void Publish(T value)
|
||||
{
|
||||
foreach (var observer in _observers.ToArray()) observer.OnNext(value);
|
||||
foreach (var observer in _observers.ToArray())
|
||||
{
|
||||
observer.OnNext(value);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Subscription(List<IObserver<T>> observers, IObserver<T> observer) : IDisposable
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using LeakMonitor.Models;
|
||||
using LeakMonitorManager;
|
||||
@@ -8,59 +10,61 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LeakMonitor.Manager.Tests;
|
||||
|
||||
public class LeakNotificationServiceTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new();
|
||||
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new Mock<ILogger<LeakNotificationService>>();
|
||||
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new LeakMonitorTestData.ManualTimeProvider();
|
||||
|
||||
private LeakNotificationService CreateSut(LeakMonitorOptions? options = null)
|
||||
{
|
||||
return new LeakNotificationService(
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(options ?? LeakMonitorTestData.CreateOptions()),
|
||||
_timeProvider);
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(options ?? LeakMonitorTestData.CreateOptions()),
|
||||
_timeProvider);
|
||||
}
|
||||
|
||||
private void VerifyMobilePush(Times times)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
}
|
||||
|
||||
private void VerifyPersistentCreate(Times times)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
}
|
||||
|
||||
private void VerifyPersistentDismiss(Times times)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
}
|
||||
|
||||
#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.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService }
|
||||
@@ -75,8 +79,8 @@ public class LeakNotificationServiceTests
|
||||
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(domain, service, It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Once());
|
||||
h => h.CallService(domain, service, It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Once());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -110,8 +114,11 @@ public class LeakNotificationServiceTests
|
||||
var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data);
|
||||
persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle);
|
||||
persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage);
|
||||
persistentPayload.GetProperty("notification_id").GetString().Should()
|
||||
.Be(LeakNotificationService.BuildNotificationId(sensorId));
|
||||
|
||||
persistentPayload.GetProperty("notification_id")
|
||||
.GetString()
|
||||
.Should()
|
||||
.Be(LeakNotificationService.BuildNotificationId(sensorId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -136,17 +143,17 @@ public class LeakNotificationServiceTests
|
||||
sut.SendLeakAlert(sensorId);
|
||||
|
||||
var persistentCall = calls.Single(c =>
|
||||
c is
|
||||
{
|
||||
Domain: LeakMonitorConsts.PersistentNotificationDomain,
|
||||
Service: LeakMonitorConsts.PersistentNotificationCreateService
|
||||
});
|
||||
c is
|
||||
{
|
||||
Domain: LeakMonitorConsts.PersistentNotificationDomain,
|
||||
Service: LeakMonitorConsts.PersistentNotificationCreateService
|
||||
});
|
||||
|
||||
LeakMonitorTestData.SerializePayload(persistentCall.Data)
|
||||
.GetProperty("notification_id")
|
||||
.GetString()
|
||||
.Should()
|
||||
.Be(expectedNotificationId);
|
||||
.GetProperty("notification_id")
|
||||
.GetString()
|
||||
.Should()
|
||||
.Be(expectedNotificationId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -156,7 +163,10 @@ public class LeakNotificationServiceTests
|
||||
var sut = CreateSut();
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId);
|
||||
for (var i = 0; i < repeats; i++)
|
||||
{
|
||||
sut.SendLeakAlert(sensorId);
|
||||
}
|
||||
|
||||
VerifyMobilePush(Times.Once());
|
||||
VerifyPersistentCreate(Times.Once());
|
||||
@@ -169,7 +179,10 @@ public class LeakNotificationServiceTests
|
||||
var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0));
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId);
|
||||
for (var i = 0; i < repeats; i++)
|
||||
{
|
||||
sut.SendLeakAlert(sensorId);
|
||||
}
|
||||
|
||||
VerifyMobilePush(Times.Exactly(repeats));
|
||||
VerifyPersistentCreate(Times.Exactly(repeats));
|
||||
@@ -214,7 +227,10 @@ public class LeakNotificationServiceTests
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds) sut.SendLeakAlert(sensorId);
|
||||
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds)
|
||||
{
|
||||
sut.SendLeakAlert(sensorId);
|
||||
}
|
||||
|
||||
VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||
VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||
@@ -236,11 +252,11 @@ public class LeakNotificationServiceTests
|
||||
VerifyMobilePush(Times.Exactly(2));
|
||||
|
||||
var boilerNotifications = calls
|
||||
.Where(c => c.Domain == LeakMonitorConsts.NotifyDomain)
|
||||
.Where(c => LeakMonitorTestData.SerializePayload(c.Data)
|
||||
.GetProperty("message")
|
||||
.GetString()!
|
||||
.Contains(LeakMonitorTestData.BoilerSensorId, StringComparison.Ordinal));
|
||||
.Where(c => c.Domain == LeakMonitorConsts.NotifyDomain)
|
||||
.Where(c => LeakMonitorTestData.SerializePayload(c.Data)
|
||||
.GetProperty("message")
|
||||
.GetString()!
|
||||
.Contains(LeakMonitorTestData.BoilerSensorId, StringComparison.Ordinal));
|
||||
|
||||
boilerNotifications.Should().ContainSingle();
|
||||
}
|
||||
@@ -286,11 +302,12 @@ public class LeakNotificationServiceTests
|
||||
dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain);
|
||||
dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService);
|
||||
dismissCall.Target.Should().BeNull();
|
||||
|
||||
LeakMonitorTestData.SerializePayload(dismissCall.Data)
|
||||
.GetProperty("notification_id")
|
||||
.GetString()
|
||||
.Should()
|
||||
.Be(expectedNotificationId);
|
||||
.GetProperty("notification_id")
|
||||
.GetString()
|
||||
.Should()
|
||||
.Be(expectedNotificationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using LeakMonitor.Models;
|
||||
using LeakMonitorManager.Interface;
|
||||
using LeakMonitorManager.Models;
|
||||
@@ -7,6 +9,8 @@ using NetDaemon.AppModel;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LeakMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -42,12 +46,15 @@ public sealed class LeakMonitorInit
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
foreach (var sensorEntityId in _options.SensorEntityIds) SubscribeToLeakSensor(sensorEntityId);
|
||||
foreach (var sensorEntityId in _options.SensorEntityIds)
|
||||
{
|
||||
SubscribeToLeakSensor(sensorEntityId);
|
||||
}
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)",
|
||||
_options.SensorEntityIds.Length);
|
||||
_options.SensorEntityIds.Length);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -63,17 +70,17 @@ public sealed class LeakMonitorInit
|
||||
var entity = new Entity(_haContext, sensorEntityId);
|
||||
|
||||
entity.StateChanges()
|
||||
.Subscribe(change =>
|
||||
{
|
||||
try
|
||||
{
|
||||
HandleStateChange(sensorEntityId, change);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling state change for {SensorId}", sensorEntityId);
|
||||
}
|
||||
});
|
||||
.Subscribe(change =>
|
||||
{
|
||||
try
|
||||
{
|
||||
HandleStateChange(sensorEntityId, change);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling state change for {SensorId}", sensorEntityId);
|
||||
}
|
||||
});
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using LeakMonitorManager.Interface;
|
||||
using LeakMonitorManager.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LeakMonitorManager;
|
||||
|
||||
public static class LeakMonitorServiceRegistration
|
||||
@@ -11,10 +15,14 @@ public static class LeakMonitorServiceRegistration
|
||||
public static void AddLeakMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var options = configuration
|
||||
.GetSection(LeakMonitorOptions.SectionName)
|
||||
.Get<LeakMonitorOptions>() ?? new LeakMonitorOptions();
|
||||
.GetSection(LeakMonitorOptions.SectionName)
|
||||
.Get<LeakMonitorOptions>() ??
|
||||
new LeakMonitorOptions();
|
||||
|
||||
if (!options.Enabled) return;
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using LeakMonitor.Models;
|
||||
using LeakMonitorManager.Interface;
|
||||
@@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NetDaemon.HassModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LeakMonitorManager;
|
||||
|
||||
public sealed class LeakNotificationService(
|
||||
@@ -14,7 +18,7 @@ public sealed class LeakNotificationService(
|
||||
IOptions<LeakMonitorOptions> options,
|
||||
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;
|
||||
|
||||
public void SendLeakAlert(string sensorEntityId)
|
||||
@@ -24,8 +28,8 @@ public sealed class LeakNotificationService(
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Skipping leak notification for {SensorId} -- within cooldown period",
|
||||
sensorEntityId);
|
||||
"Skipping leak notification for {SensorId} -- within cooldown period",
|
||||
sensorEntityId);
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -47,9 +51,9 @@ public sealed class LeakNotificationService(
|
||||
var notificationId = BuildNotificationId(sensorEntityId);
|
||||
|
||||
haContext.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new { notification_id = notificationId });
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new { notification_id = notificationId });
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
@@ -60,50 +64,55 @@ public sealed class LeakNotificationService(
|
||||
private void SendMobilePushNotification(string message)
|
||||
{
|
||||
haContext.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
data: new
|
||||
{
|
||||
message,
|
||||
title = LeakMonitorConsts.NotificationTitle,
|
||||
data = new
|
||||
{
|
||||
push = new
|
||||
{
|
||||
sound = new
|
||||
{
|
||||
critical = 1,
|
||||
volume = 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
data: new
|
||||
{
|
||||
message,
|
||||
title = LeakMonitorConsts.NotificationTitle,
|
||||
data = new
|
||||
{
|
||||
push = new
|
||||
{
|
||||
sound = new
|
||||
{
|
||||
critical = 1,
|
||||
volume = 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void CreatePersistentNotification(string notificationId, string message)
|
||||
{
|
||||
haContext.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = LeakMonitorConsts.NotificationTitle,
|
||||
message,
|
||||
notification_id = notificationId
|
||||
});
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = LeakMonitorConsts.NotificationTitle,
|
||||
message,
|
||||
notification_id = notificationId
|
||||
});
|
||||
}
|
||||
|
||||
private bool IsWithinCooldown(string sensorEntityId)
|
||||
{
|
||||
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime)) return false;
|
||||
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes);
|
||||
|
||||
return timeProvider.GetUtcNow() - lastTime < cooldown;
|
||||
}
|
||||
|
||||
internal static string BuildNotificationId(string sensorEntityId)
|
||||
{
|
||||
var sanitized = sensorEntityId.Replace('.', '_');
|
||||
|
||||
return $"{LeakMonitorConsts.NotificationIdPrefix}{sanitized}";
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using LeakMonitor.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LeakMonitorManager.Models;
|
||||
|
||||
public sealed class LeakMonitorOptions
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using LightMonitor.Models;
|
||||
using LightMonitorManager;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitor.Manager.Tests;
|
||||
|
||||
public class LightControlServiceTests
|
||||
@@ -15,20 +19,20 @@ public class LightControlServiceTests
|
||||
|
||||
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
|
||||
private LightControlService CreateService(LightMonitorOptions? options = null)
|
||||
{
|
||||
return new LightControlService(
|
||||
_haContextMock.Object,
|
||||
Mock.Of<ILogger<LightControlService>>(),
|
||||
Options.Create(options ?? _defaultOptions));
|
||||
_haContextMock.Object,
|
||||
Mock.Of<ILogger<LightControlService>>(),
|
||||
Options.Create(options ?? _defaultOptions));
|
||||
}
|
||||
|
||||
private void SetupState(string entityId, string? state)
|
||||
{
|
||||
_haContextMock.Setup(x => x.GetState(entityId))
|
||||
.Returns(LightMonitorTestData.CreateOptionalState(state));
|
||||
.Returns(LightMonitorTestData.CreateOptionalState(state));
|
||||
}
|
||||
|
||||
private void VerifyTurnOn(string entityId, bool shouldTurnOn)
|
||||
@@ -36,17 +40,17 @@ public class LightControlServiceTests
|
||||
if (!shouldTurnOn)
|
||||
{
|
||||
_haContextMock.Verify(x => x.CallService(
|
||||
It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_haContextMock.Verify(x => x.CallService("light", "turn_on",
|
||||
It.Is<ServiceTarget>(target => target.EntityIds != null && target.EntityIds.Contains(entityId)),
|
||||
It.IsAny<object?>()),
|
||||
Times.Once);
|
||||
It.Is<ServiceTarget>(target => target.EntityIds != null && target.EntityIds.Contains(entityId)),
|
||||
It.IsAny<object?>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Reactive.Subjects;
|
||||
using FluentAssertions;
|
||||
using LightMonitor.Models;
|
||||
@@ -9,6 +11,8 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitor.Manager.Tests;
|
||||
|
||||
public class LightMonitorInitTests
|
||||
@@ -18,30 +22,30 @@ public class LightMonitorInitTests
|
||||
|
||||
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILightControlService> _lightControlServiceMock = new();
|
||||
private readonly Mock<IPresenceService> _presenceServiceMock = new();
|
||||
private readonly Subject<StateChange> _stateChangesSubject = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILightControlService> _lightControlServiceMock = new Mock<ILightControlService>();
|
||||
private readonly Mock<IPresenceService> _presenceServiceMock = new Mock<IPresenceService>();
|
||||
private readonly Subject<StateChange> _stateChangesSubject = new Subject<StateChange>();
|
||||
|
||||
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
|
||||
{
|
||||
if (subscriptionException is null)
|
||||
{
|
||||
_haContextMock.Setup(x => x.StateAllChanges())
|
||||
.Returns(_stateChangesSubject);
|
||||
.Returns(_stateChangesSubject);
|
||||
}
|
||||
else
|
||||
{
|
||||
_haContextMock.Setup(x => x.StateAllChanges())
|
||||
.Throws(subscriptionException);
|
||||
.Throws(subscriptionException);
|
||||
}
|
||||
|
||||
return new LightMonitorInit(
|
||||
_haContextMock.Object,
|
||||
Mock.Of<ILogger<LightMonitorInit>>(),
|
||||
_presenceServiceMock.Object,
|
||||
_lightControlServiceMock.Object,
|
||||
Options.Create(options ?? _defaultOptions));
|
||||
_haContextMock.Object,
|
||||
Mock.Of<ILogger<LightMonitorInit>>(),
|
||||
_presenceServiceMock.Object,
|
||||
_lightControlServiceMock.Object,
|
||||
Options.Create(options ?? _defaultOptions));
|
||||
}
|
||||
|
||||
private void EmitStateChange(string entityId, string? oldState, string? newState)
|
||||
@@ -49,9 +53,9 @@ public class LightMonitorInitTests
|
||||
var entity = new Entity(_haContextMock.Object, entityId);
|
||||
|
||||
_stateChangesSubject.OnNext(new StateChange(
|
||||
entity,
|
||||
LightMonitorTestData.CreateOptionalState(oldState),
|
||||
LightMonitorTestData.CreateOptionalState(newState)));
|
||||
entity,
|
||||
LightMonitorTestData.CreateOptionalState(oldState),
|
||||
LightMonitorTestData.CreateOptionalState(newState)));
|
||||
}
|
||||
|
||||
private void VerifyTurnOn(bool shouldTurnOn)
|
||||
@@ -107,9 +111,9 @@ public class LightMonitorInitTests
|
||||
CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: [PersonEntityId]));
|
||||
|
||||
EmitStateChange(
|
||||
LightMonitorTestData.SecondaryPersonEntityId,
|
||||
"not_home",
|
||||
LightMonitorConsts.PersonHomeState);
|
||||
LightMonitorTestData.SecondaryPersonEntityId,
|
||||
"not_home",
|
||||
LightMonitorConsts.PersonHomeState);
|
||||
|
||||
VerifyTurnOn(false);
|
||||
}
|
||||
@@ -180,14 +184,15 @@ public class LightMonitorInitTests
|
||||
public void SunStateChange_WhenPresenceCheckThrows_ShouldKeepListening()
|
||||
{
|
||||
_presenceServiceMock.SetupSequence(x => x.IsAnyoneHome())
|
||||
.Throws(new InvalidOperationException("presence failed"))
|
||||
.Returns(true);
|
||||
.Throws(new InvalidOperationException("presence failed"))
|
||||
.Returns(true);
|
||||
|
||||
CreateSut();
|
||||
|
||||
var act = () => EmitStateChange(
|
||||
SunEntityId,
|
||||
LightMonitorConsts.SunAboveHorizon,
|
||||
LightMonitorConsts.SunBelowHorizon);
|
||||
SunEntityId,
|
||||
LightMonitorConsts.SunAboveHorizon,
|
||||
LightMonitorConsts.SunBelowHorizon);
|
||||
|
||||
act.Should().NotThrow();
|
||||
VerifyTurnOn(false);
|
||||
@@ -200,8 +205,9 @@ public class LightMonitorInitTests
|
||||
public void PersonStateChange_WhenTurnOnLightThrows_ShouldKeepListening()
|
||||
{
|
||||
_lightControlServiceMock.SetupSequence(x => x.TurnOnLight())
|
||||
.Throws(new InvalidOperationException("light failed"))
|
||||
.Pass();
|
||||
.Throws(new InvalidOperationException("light failed"))
|
||||
.Pass();
|
||||
|
||||
CreateSut();
|
||||
|
||||
var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
|
||||
@@ -238,7 +244,7 @@ public class LightMonitorInitTests
|
||||
CreateSut();
|
||||
|
||||
EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState,
|
||||
LightMonitorConsts.SunBelowHorizon);
|
||||
LightMonitorConsts.SunBelowHorizon);
|
||||
|
||||
VerifyTurnOn(false);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using LightMonitor.Models;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -37,7 +41,7 @@ internal static class LightMonitorTestData
|
||||
/// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and
|
||||
/// missing states must never turn the light on.
|
||||
/// </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.ToUpperInvariant(), true },
|
||||
@@ -55,7 +59,7 @@ internal static class LightMonitorTestData
|
||||
/// Light states evaluated while the sun is below the horizon. Only "on" (any casing)
|
||||
/// suppresses the turn on call; everything else, including missing state, turns it on.
|
||||
/// </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.ToUpperInvariant(), false },
|
||||
@@ -73,7 +77,7 @@ internal static class LightMonitorTestData
|
||||
/// Person states checked against the "arrived home" transition.
|
||||
/// Only "home" in any casing counts.
|
||||
/// </summary>
|
||||
public static TheoryData<string?, bool> PersonNewStateCases { get; } = new()
|
||||
public static TheoryData<string?, bool> PersonNewStateCases { get; } = new TheoryData<string?, bool>
|
||||
{
|
||||
{ LightMonitorConsts.PersonHomeState, true },
|
||||
{ "HOME", true },
|
||||
@@ -92,7 +96,7 @@ internal static class LightMonitorTestData
|
||||
/// Old person states for a transition to "home". Recovery from unavailable, unknown or
|
||||
/// missing state must be ignored; every other old state is a real arrival.
|
||||
/// </summary>
|
||||
public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new()
|
||||
public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new TheoryData<string?, bool>
|
||||
{
|
||||
{ "not_home", true },
|
||||
{ "work", true },
|
||||
@@ -106,7 +110,7 @@ internal static class LightMonitorTestData
|
||||
/// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown
|
||||
/// or missing state must be ignored.
|
||||
/// </summary>
|
||||
public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new()
|
||||
public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new TheoryData<string?, bool>
|
||||
{
|
||||
{ LightMonitorConsts.SunAboveHorizon, true },
|
||||
{ string.Empty, true },
|
||||
@@ -171,9 +175,15 @@ internal static class LightMonitorTestData
|
||||
var matrix = new TheoryData<string?[]>();
|
||||
|
||||
foreach (var first in PresenceStates)
|
||||
foreach (var second in PresenceStates)
|
||||
foreach (var third in PresenceStates)
|
||||
matrix.Add([first, second, third]);
|
||||
{
|
||||
foreach (var second in PresenceStates)
|
||||
{
|
||||
foreach (var third in PresenceStates)
|
||||
{
|
||||
matrix.Add([first, second, third]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matrix;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using LightMonitor.Models;
|
||||
using LightMonitorManager;
|
||||
@@ -6,19 +8,21 @@ using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitor.Manager.Tests;
|
||||
|
||||
public class PresenceServiceTests
|
||||
{
|
||||
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
|
||||
private PresenceService CreateService(LightMonitorOptions? options = null)
|
||||
{
|
||||
return new PresenceService(
|
||||
_haContextMock.Object,
|
||||
Mock.Of<ILogger<PresenceService>>(),
|
||||
Options.Create(options ?? _defaultOptions));
|
||||
_haContextMock.Object,
|
||||
Mock.Of<ILogger<PresenceService>>(),
|
||||
Options.Create(options ?? _defaultOptions));
|
||||
}
|
||||
|
||||
private void SetupStates(string?[] personStates)
|
||||
@@ -29,7 +33,7 @@ public class PresenceServiceTests
|
||||
var state = LightMonitorTestData.CreateOptionalState(personStates[index]);
|
||||
|
||||
_haContextMock.Setup(x => x.GetState(entityId))
|
||||
.Returns(state);
|
||||
.Returns(state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +44,7 @@ public class PresenceServiceTests
|
||||
SetupStates(personStates);
|
||||
|
||||
var expected = personStates.Any(state =>
|
||||
string.Equals(state, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase));
|
||||
string.Equals(state, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
CreateService().IsAnyoneHome().Should().Be(expected);
|
||||
}
|
||||
@@ -50,10 +54,10 @@ public class PresenceServiceTests
|
||||
public void IsAnyoneHome_ShouldOnlyTreatHomeStateAsPresent(string? state, bool expected)
|
||||
{
|
||||
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId))
|
||||
.Returns(LightMonitorTestData.CreateOptionalState(state));
|
||||
.Returns(LightMonitorTestData.CreateOptionalState(state));
|
||||
|
||||
var options = LightMonitorTestData.CreateOptions(
|
||||
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
|
||||
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
|
||||
|
||||
CreateService(options).IsAnyoneHome().Should().Be(expected);
|
||||
}
|
||||
@@ -81,7 +85,7 @@ public class PresenceServiceTests
|
||||
public void IsAnyoneHome_ShouldStopCheckingAfterTheFirstHomePerson()
|
||||
{
|
||||
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId))
|
||||
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
|
||||
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
|
||||
|
||||
CreateService().IsAnyoneHome().Should().BeTrue();
|
||||
|
||||
@@ -95,17 +99,19 @@ public class PresenceServiceTests
|
||||
CreateService().IsAnyoneHome().Should().BeFalse();
|
||||
|
||||
foreach (var personEntityId in LightMonitorTestData.PersonEntityIds)
|
||||
{
|
||||
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured()
|
||||
{
|
||||
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId))
|
||||
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
|
||||
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
|
||||
|
||||
var options = LightMonitorTestData.CreateOptions(
|
||||
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
|
||||
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
|
||||
|
||||
CreateService(options).IsAnyoneHome().Should().BeFalse();
|
||||
|
||||
@@ -120,6 +126,8 @@ public class PresenceServiceTests
|
||||
service.IsAnyoneHome().Should().BeFalse();
|
||||
|
||||
foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds)
|
||||
{
|
||||
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using LightMonitor.Models;
|
||||
using LightMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -5,6 +7,8 @@ using Microsoft.Extensions.Options;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitorManager;
|
||||
|
||||
public sealed class LightControlService(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using LightMonitor.Models;
|
||||
using LightMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using NetDaemon.AppModel;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -43,7 +47,7 @@ public sealed class LightMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons",
|
||||
_options.PersonEntityIds.Length);
|
||||
_options.PersonEntityIds.Length);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -57,36 +61,40 @@ public sealed class LightMonitorInit
|
||||
private void SubscribeToSunStateChanges()
|
||||
{
|
||||
var sunEntity = new Entity(_haContext, _options.SunEntityId);
|
||||
|
||||
sunEntity.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
.Subscribe(e =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsRecoveryTransition(e.Old?.State))
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State);
|
||||
}
|
||||
if (IsRecoveryTransition(e.Old?.State))
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Sun went below horizon, checking if anyone is home");
|
||||
_logger.LogInformation("Sun went below horizon, checking if anyone is home");
|
||||
|
||||
if (_presenceService.IsAnyoneHome()) _lightControlService.TurnOnLight();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling sun state change");
|
||||
}
|
||||
});
|
||||
if (_presenceService.IsAnyoneHome())
|
||||
{
|
||||
_lightControlService.TurnOnLight();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling sun state change");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToPersonStateChanges()
|
||||
@@ -94,41 +102,42 @@ public sealed class LightMonitorInit
|
||||
foreach (var personEntityId in _options.PersonEntityIds)
|
||||
{
|
||||
var personEntity = new Entity(_haContext, personEntityId);
|
||||
|
||||
personEntity.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
.Subscribe(e =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsRecoveryTransition(e.Old?.State))
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring",
|
||||
personEntityId, e.Old?.State);
|
||||
}
|
||||
if (IsRecoveryTransition(e.Old?.State))
|
||||
{
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring",
|
||||
personEntityId, e.Old?.State);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Person {EntityId} arrived home, checking if it is dark",
|
||||
personEntityId);
|
||||
}
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Person {EntityId} arrived home, checking if it is dark",
|
||||
personEntityId);
|
||||
}
|
||||
|
||||
_lightControlService.TurnOnLight();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId);
|
||||
}
|
||||
});
|
||||
_lightControlService.TurnOnLight();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using LightMonitor.Models;
|
||||
using LightMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitorManager;
|
||||
|
||||
public static class LightMonitorServiceRegistration
|
||||
@@ -11,14 +15,18 @@ public static class LightMonitorServiceRegistration
|
||||
public static IServiceCollection AddLightMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var options = configuration
|
||||
.GetSection(LightMonitorOptions.SectionName)
|
||||
.Get<LightMonitorOptions>() ?? new LightMonitorOptions();
|
||||
.GetSection(LightMonitorOptions.SectionName)
|
||||
.Get<LightMonitorOptions>() ??
|
||||
new LightMonitorOptions();
|
||||
|
||||
if (!options.Enabled) return services;
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
}
|
||||
|
||||
services.AddNetDaemonApp<LightMonitorInit>()
|
||||
.AddScoped<IPresenceService, PresenceService>()
|
||||
.AddScoped<ILightControlService, LightControlService>();
|
||||
.AddScoped<IPresenceService, PresenceService>()
|
||||
.AddScoped<ILightControlService, LightControlService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using LightMonitor.Models;
|
||||
using LightMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NetDaemon.HassModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitorManager;
|
||||
|
||||
public sealed class PresenceService(
|
||||
@@ -25,12 +29,15 @@ public sealed class PresenceService(
|
||||
}
|
||||
|
||||
if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Person {EntityId} is home", personEntityId);
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Person {EntityId} is home", personEntityId);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using static LightMonitor.Models.LightMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace LightMonitor.Models;
|
||||
|
||||
public sealed class LightMonitorOptions
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
using System.Globalization;
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using AutoMapper;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace Mappings.Converters;
|
||||
|
||||
public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
using AutoMapper;
|
||||
#region
|
||||
|
||||
using AutoMapper;
|
||||
using Mappings.Converters;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace Mappings;
|
||||
|
||||
public class GlobalMappingProfile : Profile
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
using AutoMapper;
|
||||
#region
|
||||
|
||||
using AutoMapper;
|
||||
using NordPool.Models;
|
||||
using NordPool.Models.Dtos;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace Mappings;
|
||||
|
||||
public class NordPoolMappingProfile : Profile
|
||||
@@ -9,7 +13,8 @@ public class NordPoolMappingProfile : Profile
|
||||
public NordPoolMappingProfile()
|
||||
{
|
||||
CreateMap<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>();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NordPool.Models;
|
||||
using NordPoolManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Manager.Tests;
|
||||
|
||||
public class CheapestIntervalsFinderTests
|
||||
@@ -13,7 +17,7 @@ public class CheapestIntervalsFinderTests
|
||||
private static readonly DateTime DayStart = NordPoolTestData.DayStart;
|
||||
private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1);
|
||||
|
||||
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new();
|
||||
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new Mock<ILogger<CheapestIntervalsFinder>>();
|
||||
|
||||
private CheapestIntervalsFinder CreateSut()
|
||||
{
|
||||
@@ -26,7 +30,7 @@ public class CheapestIntervalsFinderTests
|
||||
}
|
||||
|
||||
private static NordPoolPrice CreatePricesForDay(DateTime dayStart,
|
||||
int intervalCount = NordPoolConsts.MaxDailyIntervals)
|
||||
int intervalCount = NordPoolConsts.MaxDailyIntervals)
|
||||
{
|
||||
return new NordPoolPrice
|
||||
{
|
||||
@@ -55,7 +59,7 @@ public class CheapestIntervalsFinderTests
|
||||
|
||||
#region FindCheapestIntervals
|
||||
|
||||
public static TheoryData<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 excludes interval ending one second late", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_799.0, 1 },
|
||||
@@ -236,12 +240,13 @@ public class CheapestIntervalsFinderTests
|
||||
{
|
||||
// Arrange — duplicate payload entries are not deduplicated
|
||||
var sut = CreateSut();
|
||||
|
||||
var prices = new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice>
|
||||
{
|
||||
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 },
|
||||
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }
|
||||
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 },
|
||||
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -258,15 +263,16 @@ public class CheapestIntervalsFinderTests
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut();
|
||||
|
||||
var prices = new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice>
|
||||
{
|
||||
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 },
|
||||
new() { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null },
|
||||
new() { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 },
|
||||
new() { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 },
|
||||
new() { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 }
|
||||
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 },
|
||||
new NordPoolDayPrice { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null },
|
||||
new NordPoolDayPrice { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 },
|
||||
new NordPoolDayPrice { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 },
|
||||
new NordPoolDayPrice { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -287,12 +293,12 @@ public class CheapestIntervalsFinderTests
|
||||
const double priceCap = 12.0;
|
||||
|
||||
var expected = prices.Prices!
|
||||
.Where(p => p.Price <= priceCap)
|
||||
.OrderBy(p => p.Price)
|
||||
.ThenBy(p => p.Start)
|
||||
.Take(requestedIntervals)
|
||||
.OrderBy(p => p.Start)
|
||||
.ToList();
|
||||
.Where(p => p.Price <= priceCap)
|
||||
.OrderBy(p => p.Price)
|
||||
.ThenBy(p => p.Start)
|
||||
.Take(requestedIntervals)
|
||||
.OrderBy(p => p.Start)
|
||||
.ToList();
|
||||
|
||||
// Act
|
||||
var result = sut.FindCheapestIntervals(prices, requestedIntervals, priceCap, DeadlineEndOfDay);
|
||||
@@ -315,30 +321,31 @@ public class CheapestIntervalsFinderTests
|
||||
{
|
||||
// Arrange - xUnit cannot serialize CheapestIntervalResult rows, so the matrix is exercised in one test
|
||||
var sut = CreateSut();
|
||||
|
||||
(string Scenario, int NowSeconds, CheapestIntervalResult[] Intervals, bool Expected)[] cases =
|
||||
[
|
||||
("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
|
||||
("exactly at start", 10 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
|
||||
("exactly at end", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
|
||||
("outside all intervals", 12 * Hour,
|
||||
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false),
|
||||
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false),
|
||||
("boundary between adjacent intervals", 10 * Hour + Quarter,
|
||||
[
|
||||
Interval(10 * Hour, 10 * Hour + Quarter, 8.96),
|
||||
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, 6.20, 2)
|
||||
], true),
|
||||
[
|
||||
Interval(10 * Hour, 10 * Hour + Quarter, 8.96),
|
||||
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, 6.20, 2)
|
||||
], true),
|
||||
("unsorted intervals", 14 * Hour + 5 * 60,
|
||||
[Interval(14 * Hour, 14 * Hour + Quarter, 4.93, 2), Interval(10 * Hour, 10 * Hour + Quarter, 6.20)],
|
||||
true),
|
||||
[Interval(14 * Hour, 14 * Hour + Quarter, 4.93, 2), Interval(10 * Hour, 10 * Hour + Quarter, 6.20)],
|
||||
true),
|
||||
("before first interval", 10 * Hour - 1, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
|
||||
("in gap between intervals", 10 * Hour + 2 * Quarter,
|
||||
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false),
|
||||
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false),
|
||||
("middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60,
|
||||
[
|
||||
Interval(10 * Hour, 10 * Hour + Quarter, rank: 1),
|
||||
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2),
|
||||
Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3)
|
||||
], true),
|
||||
[
|
||||
Interval(10 * Hour, 10 * Hour + Quarter, rank: 1),
|
||||
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2),
|
||||
Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3)
|
||||
], true),
|
||||
("empty interval list", 12 * Hour, [], false)
|
||||
];
|
||||
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
#region
|
||||
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using NordPool.Models;
|
||||
using static NordPool.Models.NordPoolConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Manager.Tests;
|
||||
|
||||
public class CompactNordPoolDayPriceTests
|
||||
{
|
||||
private const int IntervalDurationSeconds = MinutesPerInterval * 60;
|
||||
|
||||
private static readonly DateTime TestStart = new(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime TestStart = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval);
|
||||
private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds();
|
||||
private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds();
|
||||
|
||||
public static TheoryData<string, string> InvalidJsonPayloads => new()
|
||||
public static TheoryData<string, string> InvalidJsonPayloads => new TheoryData<string, string>
|
||||
{
|
||||
{ "empty array", "[]" },
|
||||
{ "too few elements", "[1,2]" },
|
||||
@@ -157,8 +161,8 @@ public class CompactNordPoolDayPriceTests
|
||||
{
|
||||
var prices = new List<CompactNordPoolDayPrice>
|
||||
{
|
||||
new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
|
||||
new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
|
||||
new CompactNordPoolDayPrice { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
|
||||
new CompactNordPoolDayPrice { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(prices);
|
||||
@@ -198,8 +202,8 @@ public class CompactNordPoolDayPriceTests
|
||||
{
|
||||
var prices = new List<NordPoolDayPrice>
|
||||
{
|
||||
new() { Start = TestStart, End = TestEnd, Price = 12.50 },
|
||||
new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
|
||||
new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.50 },
|
||||
new NordPoolDayPrice { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
|
||||
};
|
||||
|
||||
var result = prices.ToCompact();
|
||||
@@ -240,8 +244,11 @@ public class CompactNordPoolDayPriceTests
|
||||
result.Should().HaveCount(96);
|
||||
result.Should().BeInAscendingOrder(p => p.Start);
|
||||
result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds());
|
||||
result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
|
||||
.ToUnixTimeSeconds());
|
||||
|
||||
result[95]
|
||||
.Start.Should()
|
||||
.Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
|
||||
.ToUnixTimeSeconds());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -262,7 +269,7 @@ public class CompactNordPoolDayPriceTests
|
||||
{
|
||||
var prices = new List<NordPoolDayPrice>
|
||||
{
|
||||
new() { Start = null, End = null, Price = null }
|
||||
new NordPoolDayPrice { Start = null, End = null, Price = null }
|
||||
};
|
||||
|
||||
var result = prices.ToCompact();
|
||||
@@ -280,6 +287,7 @@ public class CompactNordPoolDayPriceTests
|
||||
var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22);
|
||||
|
||||
var compactPrices = prices.ToCompact();
|
||||
|
||||
var attributePayload = new
|
||||
{
|
||||
prices = compactPrices,
|
||||
@@ -287,10 +295,12 @@ public class CompactNordPoolDayPriceTests
|
||||
friendly_name = "NordPool today and tomorrow prices",
|
||||
last_updated = DateTime.UtcNow.ToString("O")
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(attributePayload);
|
||||
var byteCount = Encoding.UTF8.GetByteCount(json);
|
||||
|
||||
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
|
||||
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
|
||||
byteCount.Should()
|
||||
.BeLessThan(haAttributeByteLimitBytes,
|
||||
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
@@ -8,6 +10,8 @@ using NordPool.Models;
|
||||
using NordPoolManager;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Manager.Tests;
|
||||
|
||||
public class NordPoolEntityServiceTests
|
||||
@@ -99,7 +103,7 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.CreateEntitiesAsync("EUR/kWh");
|
||||
@@ -113,14 +117,16 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var callCount = 0;
|
||||
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
|
||||
.Returns(() =>
|
||||
{
|
||||
callCount++;
|
||||
return callCount == 2
|
||||
? throw new InvalidOperationException("Entity creation failed")
|
||||
: Task.CompletedTask;
|
||||
});
|
||||
.Returns(() =>
|
||||
{
|
||||
callCount++;
|
||||
|
||||
return callCount == 2
|
||||
? throw new InvalidOperationException("Entity creation failed")
|
||||
: Task.CompletedTask;
|
||||
});
|
||||
|
||||
// Act
|
||||
await _sut.CreateEntitiesAsync("EUR/kWh");
|
||||
@@ -134,7 +140,7 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.CreateEntitiesAsync(null);
|
||||
@@ -152,7 +158,7 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.CleanupEntitiesAsync();
|
||||
@@ -172,7 +178,7 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Remove failed"));
|
||||
.ThrowsAsync(new InvalidOperationException("Remove failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.CleanupEntitiesAsync();
|
||||
@@ -190,7 +196,7 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.SetEntityStateSafe("sensor.test", "42");
|
||||
@@ -204,7 +210,7 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("State update failed"));
|
||||
.ThrowsAsync(new InvalidOperationException("State update failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
|
||||
@@ -222,8 +228,9 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var attributes = new { unit_of_measurement = "EUR/kWh" };
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.SetEntityAttributesSafe("sensor.test", attributes);
|
||||
@@ -237,8 +244,9 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var attributes = new { unit_of_measurement = "EUR/kWh" };
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Attributes update failed"));
|
||||
.ThrowsAsync(new InvalidOperationException("Attributes update failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.SetEntityAttributesSafe("sensor.test", attributes);
|
||||
@@ -256,20 +264,23 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ResetEntitiesAsync();
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", string.Empty), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("button.nordpool_fetch_prices", "unknown"), Times.Once);
|
||||
}
|
||||
@@ -279,28 +290,35 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ResetEntitiesAsync();
|
||||
|
||||
// Assert
|
||||
_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>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
|
||||
_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>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
|
||||
_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(
|
||||
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>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -308,12 +326,14 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_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 =>
|
||||
em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
var act = () => _sut.ResetEntitiesAsync();
|
||||
@@ -327,17 +347,19 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange - 7 entities get state and attributes
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ResetEntitiesAsync();
|
||||
|
||||
// Assert
|
||||
_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>()),
|
||||
Times.Exactly(7));
|
||||
Times.Exactly(7));
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -356,14 +378,16 @@ public class NordPoolEntityServiceTests
|
||||
DayQuartersIndex = 5,
|
||||
LastApiUpdateDate = DateTime.UtcNow,
|
||||
UsingCachedData = false,
|
||||
TodayNordPoolPrice = todayPrice ?? new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
|
||||
},
|
||||
TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
|
||||
},
|
||||
TodayNordPoolPrice = todayPrice ??
|
||||
new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
|
||||
},
|
||||
TomorrowNordPoolPrice = tomorrowPrice ??
|
||||
new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
|
||||
},
|
||||
CheapestIntervals = [],
|
||||
ConfiguredHours = 2.0,
|
||||
ConfiguredIntervalCount = 4,
|
||||
@@ -382,24 +406,28 @@ public class NordPoolEntityServiceTests
|
||||
var context = CreateDefaultContext();
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
// Assert
|
||||
_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_today_prices", "1"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(
|
||||
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices",
|
||||
It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
|
||||
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices",
|
||||
It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -409,22 +437,26 @@ public class NordPoolEntityServiceTests
|
||||
var context = CreateDefaultContext();
|
||||
|
||||
_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>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
// Assert
|
||||
_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>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
|
||||
_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]
|
||||
@@ -432,13 +464,14 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var context = CreateDefaultContext(
|
||||
todayPrice: new NordPoolPrice { Prices = null },
|
||||
tomorrowPrice: new NordPoolPrice { Prices = null });
|
||||
todayPrice: new NordPoolPrice { Prices = null },
|
||||
tomorrowPrice: new NordPoolPrice { Prices = null });
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
@@ -446,12 +479,12 @@ public class NordPoolEntityServiceTests
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
|
||||
_entityManagerMock.Verify(
|
||||
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<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]
|
||||
public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices()
|
||||
@@ -519,16 +552,19 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
object? capturedAttributes = null;
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var context = CreateDefaultContext() with
|
||||
{
|
||||
@@ -566,21 +602,23 @@ public class NordPoolEntityServiceTests
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(
|
||||
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
|
||||
o.GetType().GetProperty("prices")!.GetValue(o) is List<CompactNordPoolDayPrice>)),
|
||||
Times.Once);
|
||||
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
|
||||
o.GetType().GetProperty("prices")!.GetValue(o) is List<CompactNordPoolDayPrice>)),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -592,35 +630,42 @@ public class NordPoolEntityServiceTests
|
||||
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
|
||||
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 4.93 + i * 0.22
|
||||
}).ToList();
|
||||
var todayPrices = Enumerable.Range(0, intervalsPerDay)
|
||||
.Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 4.93 + i * 0.22
|
||||
})
|
||||
.ToList();
|
||||
|
||||
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 5.50 + i * 0.22
|
||||
}).ToList();
|
||||
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay)
|
||||
.Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 5.50 + i * 0.22
|
||||
})
|
||||
.ToList();
|
||||
|
||||
object? capturedAttributes = null;
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var context = CreateDefaultContext(
|
||||
todayPrice: new NordPoolPrice { Prices = todayPrices },
|
||||
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
|
||||
todayPrice: new NordPoolPrice { Prices = todayPrices },
|
||||
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
@@ -629,8 +674,10 @@ public class NordPoolEntityServiceTests
|
||||
capturedAttributes.Should().NotBeNull();
|
||||
var json = JsonSerializer.Serialize(capturedAttributes);
|
||||
var byteCount = Encoding.UTF8.GetByteCount(json);
|
||||
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
|
||||
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
|
||||
|
||||
byteCount.Should()
|
||||
.BeLessThan(haAttributeByteLimitBytes,
|
||||
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -640,15 +687,16 @@ public class NordPoolEntityServiceTests
|
||||
[InlineData(1234.5, "1234.50")]
|
||||
[InlineData(17.916, "17.92")]
|
||||
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price,
|
||||
string expected)
|
||||
string expected)
|
||||
{
|
||||
// Arrange
|
||||
var context = CreateDefaultContext(price);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
@@ -662,14 +710,17 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
object? capturedAttributes = null;
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var context = CreateDefaultContext() with
|
||||
{
|
||||
@@ -700,15 +751,18 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
object? capturedAttributes = null;
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var first = new CheapestIntervalResult
|
||||
{
|
||||
@@ -717,6 +771,7 @@ public class NordPoolEntityServiceTests
|
||||
Price = 4.93,
|
||||
Rank = 1
|
||||
};
|
||||
|
||||
var second = new CheapestIntervalResult
|
||||
{
|
||||
Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc),
|
||||
@@ -746,8 +801,10 @@ public class NordPoolEntityServiceTests
|
||||
capturedAttributes.Should().NotBeNull();
|
||||
var attributes = capturedAttributes!;
|
||||
var type = attributes.GetType();
|
||||
|
||||
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should()
|
||||
.HaveCount(2);
|
||||
.HaveCount(2);
|
||||
|
||||
type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30);
|
||||
type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true);
|
||||
type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O"));
|
||||
@@ -763,15 +820,18 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
object? capturedAttributes = null;
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var context = CreateDefaultContext() with { CheapestIntervals = null };
|
||||
|
||||
@@ -794,18 +854,22 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
object? capturedAttributes = null;
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
|
||||
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em =>
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||
It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var todayPrice = new NordPoolPrice
|
||||
{
|
||||
Prices =
|
||||
@@ -815,6 +879,7 @@ public class NordPoolEntityServiceTests
|
||||
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
|
||||
]
|
||||
};
|
||||
|
||||
var tomorrowPrice = new NordPoolPrice
|
||||
{
|
||||
Prices =
|
||||
@@ -823,6 +888,7 @@ public class NordPoolEntityServiceTests
|
||||
{ Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
|
||||
]
|
||||
};
|
||||
|
||||
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
|
||||
|
||||
// Act
|
||||
@@ -843,42 +909,49 @@ public class NordPoolEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_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 tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
var todayPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 10.0
|
||||
}).ToList();
|
||||
var tomorrowPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 10.0
|
||||
}).ToList();
|
||||
|
||||
var todayPrices = Enumerable.Range(0, 100)
|
||||
.Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 10.0
|
||||
})
|
||||
.ToList();
|
||||
|
||||
var tomorrowPrices = Enumerable.Range(0, 100)
|
||||
.Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = 10.0
|
||||
})
|
||||
.ToList();
|
||||
|
||||
var context = CreateDefaultContext(
|
||||
todayPrice: new NordPoolPrice { Prices = todayPrices },
|
||||
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
|
||||
todayPrice: new NordPoolPrice { Prices = todayPrices },
|
||||
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
// Assert
|
||||
_loggerMock.Verify(
|
||||
l => l.Log(
|
||||
LogLevel.Warning,
|
||||
It.IsAny<EventId>(),
|
||||
It.Is<It.IsAnyType>((state, _) =>
|
||||
state != null && state.ToString()!.Contains("exceeds expected maximum")),
|
||||
It.IsAny<Exception?>(),
|
||||
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
|
||||
Times.Once);
|
||||
l => l.Log(
|
||||
LogLevel.Warning,
|
||||
It.IsAny<EventId>(),
|
||||
It.Is<It.IsAnyType>((state, _) =>
|
||||
state != null && state.ToString()!.Contains("exceeds expected maximum")),
|
||||
It.IsAny<Exception?>(),
|
||||
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -895,6 +968,7 @@ public class NordPoolEntityServiceTests
|
||||
data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled));
|
||||
data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled));
|
||||
data.Add("cleanup entities", sut => sut.CleanupEntitiesAsync(cancelled));
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Reactive.Concurrency;
|
||||
using BoilerMonitor.Models;
|
||||
using FluentAssertions;
|
||||
@@ -11,6 +13,8 @@ using NordPoolManager;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Manager.Tests;
|
||||
|
||||
public class NordPoolInitTests
|
||||
@@ -39,14 +43,18 @@ public class NordPoolInitTests
|
||||
_services = new Services(_haContextMock.Object);
|
||||
|
||||
_priceServiceMock
|
||||
.Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_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.ResetEntitiesAsync()).Returns(Task.CompletedTask);
|
||||
|
||||
_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.ShouldFetchNewPrices(It.IsAny<DateOnly>())).Returns(false);
|
||||
_priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0);
|
||||
@@ -54,36 +62,39 @@ public class NordPoolInitTests
|
||||
_priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null);
|
||||
_priceServiceMock.SetupGet(p => p.CurrentPrice).Returns(0.0);
|
||||
_priceServiceMock.SetupGet(p => p.LastUpdatedDate).Returns((DateTime?)null);
|
||||
|
||||
_cheapestIntervalsFinderMock
|
||||
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
|
||||
It.IsAny<DateTime>()))
|
||||
.Returns(false);
|
||||
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig
|
||||
{
|
||||
IntervalCount = 4,
|
||||
PriceCap = double.MaxValue,
|
||||
Deadline = DateTime.Today.AddDays(1),
|
||||
SkipPriceCap = false
|
||||
});
|
||||
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
|
||||
It.IsAny<DateTime>()))
|
||||
.Returns(false);
|
||||
|
||||
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration())
|
||||
.Returns(new BoilerConfig
|
||||
{
|
||||
IntervalCount = 4,
|
||||
PriceCap = double.MaxValue,
|
||||
Deadline = DateTime.Today.AddDays(1),
|
||||
SkipPriceCap = false
|
||||
});
|
||||
}
|
||||
|
||||
private NordPoolInit CreateSut(NordPoolOptions? nordPoolOptions = null)
|
||||
{
|
||||
var options = Options.Create(
|
||||
nordPoolOptions ?? new NordPoolOptions { CleanupEntitiesOnStartup = false });
|
||||
nordPoolOptions ?? new NordPoolOptions { CleanupEntitiesOnStartup = false });
|
||||
|
||||
return new NordPoolInit(
|
||||
_entities,
|
||||
_services,
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
_priceServiceMock.Object,
|
||||
_entityServiceMock.Object,
|
||||
_schedulerMock.Object,
|
||||
_cheapestIntervalsFinderMock.Object,
|
||||
_boilerConfigProviderMock.Object,
|
||||
options,
|
||||
TimeProvider.System);
|
||||
_entities,
|
||||
_services,
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
_priceServiceMock.Object,
|
||||
_entityServiceMock.Object,
|
||||
_schedulerMock.Object,
|
||||
_cheapestIntervalsFinderMock.Object,
|
||||
_boilerConfigProviderMock.Object,
|
||||
options,
|
||||
TimeProvider.System);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -107,29 +118,34 @@ public class NordPoolInitTests
|
||||
|
||||
// The constructor also starts the same init flow in the background, so calls may happen more than once.
|
||||
_entityServiceMock.Verify(
|
||||
es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()),
|
||||
cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never());
|
||||
es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()),
|
||||
cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never());
|
||||
|
||||
_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.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
|
||||
Times.AtLeastOnce);
|
||||
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
|
||||
Times.AtLeastOnce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InitializeAsync_WhenCreatingEntitiesFails_ShouldRethrow()
|
||||
{
|
||||
var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false });
|
||||
|
||||
_entityServiceMock
|
||||
.Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new InvalidOperationException("create failed"));
|
||||
.Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new InvalidOperationException("create failed"));
|
||||
|
||||
var act = sut.InitializeAsync;
|
||||
|
||||
await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("create failed");
|
||||
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never);
|
||||
|
||||
_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 AutoMapper;
|
||||
using FluentAssertions;
|
||||
@@ -8,6 +10,8 @@ using NordPool.Models;
|
||||
using NordPool.Models.Dtos;
|
||||
using NordPoolManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Manager.Tests;
|
||||
|
||||
public class NordPoolPriceServiceTests
|
||||
@@ -110,12 +114,15 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
// Arrange & Act — iterate over a full UTC day; CET conversion produces 96 unique quarter indices
|
||||
var indices = new HashSet<int>();
|
||||
|
||||
for (var hour = 0; hour < 24; hour++)
|
||||
for (var minute = 0; minute < 60; minute += 15)
|
||||
{
|
||||
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
|
||||
var index = NordPoolPriceService.GetTimeQuarterIndex(date);
|
||||
indices.Add(index);
|
||||
for (var minute = 0; minute < 60; minute += 15)
|
||||
{
|
||||
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
|
||||
var index = NordPoolPriceService.GetTimeQuarterIndex(date);
|
||||
indices.Add(index);
|
||||
}
|
||||
}
|
||||
|
||||
// Assert
|
||||
@@ -127,8 +134,12 @@ public class NordPoolPriceServiceTests
|
||||
[Theory]
|
||||
[InlineData(2026, 1, 15, 8, 0, 36)] // CET winter (UTC+1): UTC 08:00 = CET 09:00 -> index 36
|
||||
[InlineData(2026, 7, 15, 8, 0, 40)] // CEST summer (UTC+2): UTC 08:00 = CEST 10:00 -> index 40
|
||||
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, int month, int day, int hour,
|
||||
int minute, int expectedIndex)
|
||||
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year,
|
||||
int month,
|
||||
int day,
|
||||
int hour,
|
||||
int minute,
|
||||
int expectedIndex)
|
||||
{
|
||||
// Arrange
|
||||
var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc);
|
||||
@@ -245,7 +256,7 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice>
|
||||
{
|
||||
new()
|
||||
new NordPoolDayPrice
|
||||
{
|
||||
Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture),
|
||||
End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0
|
||||
@@ -254,7 +265,7 @@ public class NordPoolPriceServiceTests
|
||||
};
|
||||
|
||||
_mapperMock.Setup(m => m.Map<NordPoolPriceResultDto, NordPoolPrice>(It.IsAny<NordPoolPriceResultDto>()))
|
||||
.Returns(expectedPrice);
|
||||
.Returns(expectedPrice);
|
||||
|
||||
// Act
|
||||
var result = _sut.ParseNordPoolResult(jsonElement);
|
||||
@@ -285,7 +296,7 @@ public class NordPoolPriceServiceTests
|
||||
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonString);
|
||||
|
||||
_mapperMock.Setup(m => m.Map<NordPoolPriceResultDto, NordPoolPrice>(It.IsAny<NordPoolPriceResultDto>()))
|
||||
.Returns((NordPoolPrice)null!);
|
||||
.Returns((NordPoolPrice)null!);
|
||||
|
||||
// Act
|
||||
var result = _sut.ParseNordPoolResult(jsonElement);
|
||||
@@ -301,7 +312,7 @@ public class NordPoolPriceServiceTests
|
||||
var jsonElement = JsonSerializer.Deserialize<JsonElement>("{}");
|
||||
|
||||
_mapperMock.Setup(m => m.Map<NordPoolPriceResultDto, NordPoolPrice>(It.IsAny<NordPoolPriceResultDto>()))
|
||||
.Returns(new NordPoolPrice());
|
||||
.Returns(new NordPoolPrice());
|
||||
|
||||
// Act
|
||||
var result = _sut.ParseNordPoolResult(jsonElement);
|
||||
@@ -322,9 +333,9 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice>
|
||||
{
|
||||
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
|
||||
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
|
||||
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -347,9 +358,9 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice>
|
||||
{
|
||||
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
|
||||
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
|
||||
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -388,7 +399,7 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
Prices = new List<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>
|
||||
{
|
||||
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null },
|
||||
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null },
|
||||
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -445,7 +456,7 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
Prices = new List<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>();
|
||||
|
||||
for (var i = 0; i < 96; i++)
|
||||
{
|
||||
prices.Add(new NordPoolDayPrice
|
||||
{
|
||||
Start = now.AddMinutes(i * 15),
|
||||
End = now.AddMinutes((i + 1) * 15),
|
||||
Price = 5.0 + i * 0.22
|
||||
});
|
||||
}
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
|
||||
@@ -532,8 +545,11 @@ public class NordPoolPriceServiceTests
|
||||
var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
var prices = new List<NordPoolDayPrice>();
|
||||
|
||||
for (var i = 0; i < 96; i++)
|
||||
{
|
||||
prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 });
|
||||
}
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
_sut.DayQuartersIndex = expectedIndex;
|
||||
@@ -552,8 +568,11 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var prices = new List<NordPoolDayPrice>();
|
||||
|
||||
for (var i = 0; i < 96; i++)
|
||||
{
|
||||
prices.Add(new NordPoolDayPrice { Price = null });
|
||||
}
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
_sut.CurrentPrice = 17.91;
|
||||
@@ -572,8 +591,11 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var prices = new List<NordPoolDayPrice>();
|
||||
|
||||
for (var i = 0; i < 96; i++)
|
||||
{
|
||||
prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 });
|
||||
}
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
_sut.DayQuartersIndex = -1;
|
||||
@@ -595,9 +617,10 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
// Arrange — negative and zero spot prices are valid NordPool scenarios
|
||||
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
var prices = NordPoolTestData.CreateIntervals(
|
||||
NordPoolConsts.MaxDailyIntervals,
|
||||
i => i == index ? expectedPrice : 10.0);
|
||||
NordPoolConsts.MaxDailyIntervals,
|
||||
i => i == index ? expectedPrice : 10.0);
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
_sut.CurrentPrice = 17.91;
|
||||
@@ -616,9 +639,10 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
// Arrange — fewer prices than the current quarter index (e.g. partial day payload)
|
||||
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
var prices = Enumerable.Range(0, index)
|
||||
.Select(i => new NordPoolDayPrice { Price = 10.0 + i })
|
||||
.ToList();
|
||||
.Select(i => new NordPoolDayPrice { Price = 10.0 + i })
|
||||
.ToList();
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
_sut.CurrentPrice = 17.91;
|
||||
@@ -637,9 +661,10 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
|
||||
.Select(_ => new NordPoolDayPrice { Price = 99.0 })
|
||||
.ToList();
|
||||
.Select(_ => new NordPoolDayPrice { Price = 99.0 })
|
||||
.ToList();
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
_sut.DayQuartersIndex = index;
|
||||
@@ -658,9 +683,10 @@ public class NordPoolPriceServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
|
||||
.Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 })
|
||||
.ToList();
|
||||
.Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 })
|
||||
.ToList();
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
|
||||
_sut.CurrentPrice = 17.91;
|
||||
@@ -687,6 +713,7 @@ public class NordPoolPriceServiceTests
|
||||
Task<NordPoolPrice> Fetch(DateOnly date)
|
||||
{
|
||||
requestedDates.Add(date);
|
||||
|
||||
return Task.FromResult(CreatePrices(1.5));
|
||||
}
|
||||
|
||||
@@ -718,10 +745,11 @@ public class NordPoolPriceServiceTests
|
||||
|
||||
// Act
|
||||
await _sut.FetchPricesAsync(_ =>
|
||||
{
|
||||
delegateCalled = true;
|
||||
return Task.FromResult(CreatePrices(3.0));
|
||||
});
|
||||
{
|
||||
delegateCalled = true;
|
||||
|
||||
return Task.FromResult(CreatePrices(3.0));
|
||||
});
|
||||
|
||||
// Assert
|
||||
delegateCalled.Should().BeFalse();
|
||||
@@ -761,7 +789,7 @@ public class NordPoolPriceServiceTests
|
||||
("today prices are empty", today, new NordPoolPrice { Prices = [] }, CreatePrices(18.71), true),
|
||||
("today and tomorrow prices present", today, CreatePrices(12.50), CreatePrices(18.71), false),
|
||||
("price values are null but entries exist", today, CreatePrices((double?)null),
|
||||
CreatePrices((double?)null), false),
|
||||
CreatePrices((double?)null), false),
|
||||
("all price payloads are null", today, null, null, true)
|
||||
];
|
||||
|
||||
@@ -786,10 +814,12 @@ public class NordPoolPriceServiceTests
|
||||
// Arrange — tomorrow's prices are not published before 13:00, so cached data is acceptable until then
|
||||
var today = DateOnly.FromDateTime(DateTime.Now);
|
||||
_sut.LastFetchedDate = today;
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
|
||||
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
|
||||
};
|
||||
|
||||
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null };
|
||||
|
||||
// Act
|
||||
@@ -805,10 +835,12 @@ public class NordPoolPriceServiceTests
|
||||
// Arrange
|
||||
var today = DateOnly.FromDateTime(DateTime.Now);
|
||||
_sut.LastFetchedDate = today;
|
||||
|
||||
_sut.TodayNordPoolPrice = new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
|
||||
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
|
||||
};
|
||||
|
||||
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
|
||||
|
||||
// Act
|
||||
@@ -828,13 +860,14 @@ public class NordPoolPriceServiceTests
|
||||
// Arrange
|
||||
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
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
|
||||
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
|
||||
};
|
||||
|
||||
_sut.TomorrowNordPoolPrice = tomorrow;
|
||||
_sut.DayQuartersIndex = 48;
|
||||
var today = new DateOnly(2026, 4, 1);
|
||||
@@ -855,7 +888,7 @@ public class NordPoolPriceServiceTests
|
||||
[Fact]
|
||||
public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice()
|
||||
{
|
||||
NordPoolPrice?[] unusablePrices = [null, new() { Prices = null }, new() { Prices = [] }];
|
||||
NordPoolPrice?[] unusablePrices = [null, new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = [] }];
|
||||
|
||||
foreach (var tomorrow in unusablePrices)
|
||||
{
|
||||
@@ -900,11 +933,12 @@ public class NordPoolPriceServiceTests
|
||||
// Arrange
|
||||
var previousToday = new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
|
||||
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
|
||||
};
|
||||
|
||||
var tomorrow = new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
|
||||
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
|
||||
};
|
||||
|
||||
_sut.TodayNordPoolPrice = previousToday;
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using NordPool.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -8,7 +12,7 @@ namespace NordPool.Manager.Tests;
|
||||
/// </summary>
|
||||
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>
|
||||
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart" />.
|
||||
@@ -23,12 +27,12 @@ internal static class NordPoolTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = priceFactory(i)
|
||||
})
|
||||
.Select(i => new NordPoolDayPrice
|
||||
{
|
||||
Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
|
||||
End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
|
||||
Price = priceFactory(i)
|
||||
})
|
||||
];
|
||||
}
|
||||
|
||||
@@ -41,8 +45,8 @@ internal static class NordPoolTestData
|
||||
var start = dayStart ?? DayStart;
|
||||
|
||||
return CreateIntervals(
|
||||
NordPoolConsts.MaxDailyIntervals,
|
||||
i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2),
|
||||
start);
|
||||
NordPoolConsts.MaxDailyIntervals,
|
||||
i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2),
|
||||
start);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
||||
@@ -23,24 +27,24 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) :
|
||||
}
|
||||
|
||||
var eligible = prices.Prices
|
||||
.Where(p => p is { Start: not null, End: not null, Price: not null })
|
||||
.Where(p => p.End!.Value <= deadline)
|
||||
.Where(p => p.Price!.Value <= priceCap)
|
||||
.OrderBy(p => p.Price!.Value)
|
||||
.ThenBy(p => p.Start!.Value)
|
||||
.Take(numberOfIntervals)
|
||||
.ToList();
|
||||
.Where(p => p is { Start: not null, End: not null, Price: not null })
|
||||
.Where(p => p.End!.Value <= deadline)
|
||||
.Where(p => p.Price!.Value <= priceCap)
|
||||
.OrderBy(p => p.Price!.Value)
|
||||
.ThenBy(p => p.Start!.Value)
|
||||
.Take(numberOfIntervals)
|
||||
.ToList();
|
||||
|
||||
var ranked = eligible
|
||||
.Select((p, index) => new CheapestIntervalResult
|
||||
{
|
||||
Start = p.Start!.Value,
|
||||
End = p.End!.Value,
|
||||
Price = p.Price!.Value,
|
||||
Rank = index + 1
|
||||
})
|
||||
.OrderBy(r => r.Start)
|
||||
.ToList();
|
||||
.Select((p, index) => new CheapestIntervalResult
|
||||
{
|
||||
Start = p.Start!.Value,
|
||||
End = p.End!.Value,
|
||||
Price = p.Price!.Value,
|
||||
Rank = index + 1
|
||||
})
|
||||
.OrderBy(r => r.Start)
|
||||
.ToList();
|
||||
|
||||
return ranked;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
#region
|
||||
|
||||
using NordPool.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface ICheapestIntervalsFinder
|
||||
{
|
||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
|
||||
double priceCap, DateTime deadline);
|
||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices,
|
||||
int numberOfIntervals,
|
||||
double priceCap,
|
||||
DateTime deadline);
|
||||
|
||||
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface INordPoolEntityService
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using NordPool.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface INordPoolPriceService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using NordPool.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Models;
|
||||
|
||||
public record EntityUpdateContext
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger)
|
||||
@@ -35,16 +39,16 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
var entitiesToCreate = GetInitEntitiesList(unitOfMeasurement);
|
||||
|
||||
var createTasks = entitiesToCreate.Select(async nordPoolEntity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", nordPoolEntity.EntityId);
|
||||
}
|
||||
});
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", nordPoolEntity.EntityId);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(createTasks).ConfigureAwait(false);
|
||||
}
|
||||
@@ -54,14 +58,15 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await Task.WhenAll(
|
||||
ResetLastUpdateTimeAsync(),
|
||||
ResetCurrentPriceAsync(),
|
||||
ResetTodayPricesAsync(),
|
||||
ResetTomorrowPricesAsync(),
|
||||
ResetTodayTomorrowPricesAsync(),
|
||||
ResetCheapestIntervalsAsync(),
|
||||
ResetFetchPricesButtonAsync()
|
||||
).ConfigureAwait(false);
|
||||
ResetLastUpdateTimeAsync(),
|
||||
ResetCurrentPriceAsync(),
|
||||
ResetTodayPricesAsync(),
|
||||
ResetTomorrowPricesAsync(),
|
||||
ResetTodayTomorrowPricesAsync(),
|
||||
ResetCheapestIntervalsAsync(),
|
||||
ResetFetchPricesButtonAsync()
|
||||
)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||
@@ -79,8 +84,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
||||
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
||||
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||
}
|
||||
|
||||
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
|
||||
@@ -88,8 +93,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
|
||||
cheapestCount, ctx.IsNowCheap);
|
||||
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
|
||||
cheapestCount, ctx.IsNowCheap);
|
||||
}
|
||||
|
||||
var updateTasks = new[]
|
||||
@@ -117,6 +122,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up NordPool entities");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -124,87 +130,101 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
private async Task ResetLastUpdateTimeAsync()
|
||||
{
|
||||
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(LastUpdateTimeEntityId, new
|
||||
{
|
||||
friendly_name = "NordPool last update time"
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "NordPool last update time"
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetCurrentPriceAsync()
|
||||
{
|
||||
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
|
||||
{
|
||||
unit_of_measurement = (string?)null,
|
||||
device_class = "monetary",
|
||||
state_class = "measurement",
|
||||
friendly_name = "NordPool current price",
|
||||
last_updated = (string?)null,
|
||||
last_api_fetch = (string?)null,
|
||||
using_cached_data = false,
|
||||
current_quarter_index = 0
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = (string?)null,
|
||||
device_class = "monetary",
|
||||
state_class = "measurement",
|
||||
friendly_name = "NordPool current price",
|
||||
last_updated = (string?)null,
|
||||
last_api_fetch = (string?)null,
|
||||
using_cached_data = false,
|
||||
current_quarter_index = 0
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetTodayPricesAsync()
|
||||
{
|
||||
await SetEntityStateSafe(TodayPricesEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayPricesEntityId, new
|
||||
{
|
||||
prices = Array.Empty<CompactNordPoolDayPrice>(),
|
||||
friendly_name = "NordPool today prices",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
prices = Array.Empty<CompactNordPoolDayPrice>(),
|
||||
friendly_name = "NordPool today prices",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetTomorrowPricesAsync()
|
||||
{
|
||||
await SetEntityStateSafe(TomorrowPricesEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
|
||||
{
|
||||
prices = Array.Empty<CompactNordPoolDayPrice>(),
|
||||
friendly_name = "NordPool tomorrow prices",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
prices = Array.Empty<CompactNordPoolDayPrice>(),
|
||||
friendly_name = "NordPool tomorrow prices",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetTodayTomorrowPricesAsync()
|
||||
{
|
||||
await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
|
||||
{
|
||||
prices = Array.Empty<CompactNordPoolDayPrice>(),
|
||||
prices_count = 0,
|
||||
friendly_name = "NordPool today and tomorrow prices",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
prices = Array.Empty<CompactNordPoolDayPrice>(),
|
||||
prices_count = 0,
|
||||
friendly_name = "NordPool today and tomorrow prices",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetCheapestIntervalsAsync()
|
||||
{
|
||||
await SetEntityStateSafe(CheapestIntervalsEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
|
||||
{
|
||||
intervals = Array.Empty<CheapestIntervalResult>(),
|
||||
configured_hours = 0.0,
|
||||
configured_interval_count = 0,
|
||||
configured_price_cap = 0.0,
|
||||
configured_ready_by = "",
|
||||
total_heating_minutes = 0,
|
||||
is_now_cheap = false,
|
||||
next_cheap_interval = (string?)null,
|
||||
friendly_name = "NordPool cheapest boiler intervals",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
intervals = Array.Empty<CheapestIntervalResult>(),
|
||||
configured_hours = 0.0,
|
||||
configured_interval_count = 0,
|
||||
configured_price_cap = 0.0,
|
||||
configured_ready_by = string.Empty,
|
||||
total_heating_minutes = 0,
|
||||
is_now_cheap = false,
|
||||
next_cheap_interval = (string?)null,
|
||||
friendly_name = "NordPool cheapest boiler intervals",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetFetchPricesButtonAsync()
|
||||
{
|
||||
await SetEntityStateSafe(NordPoolConsts.FetchPricesButtonEntityId, "unknown").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(NordPoolConsts.FetchPricesButtonEntityId, new
|
||||
{
|
||||
friendly_name = "NordPool fetch prices"
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "NordPool fetch prices"
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
|
||||
@@ -215,71 +235,82 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
|
||||
{
|
||||
unit_of_measurement = ctx.UnitOfMeasurement,
|
||||
device_class = "monetary",
|
||||
state_class = "measurement",
|
||||
friendly_name = "NordPool current price",
|
||||
last_updated = timestamp,
|
||||
last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture),
|
||||
using_cached_data = ctx.UsingCachedData,
|
||||
current_quarter_index = ctx.DayQuartersIndex
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = ctx.UnitOfMeasurement,
|
||||
device_class = "monetary",
|
||||
state_class = "measurement",
|
||||
friendly_name = "NordPool current price",
|
||||
last_updated = timestamp,
|
||||
last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture),
|
||||
using_cached_data = ctx.UsingCachedData,
|
||||
current_quarter_index = ctx.DayQuartersIndex
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateTodayPricesAsync(EntityUpdateContext ctx, int todayPricesCount, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(TodayPricesEntityId, todayPricesCount.ToString()).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayPricesEntityId, new
|
||||
{
|
||||
prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(),
|
||||
friendly_name = "NordPool today prices",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(),
|
||||
friendly_name = "NordPool today prices",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateTomorrowPricesAsync(EntityUpdateContext ctx, int tomorrowPricesCount, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
|
||||
{
|
||||
prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(),
|
||||
friendly_name = "NordPool tomorrow prices",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(),
|
||||
friendly_name = "NordPool tomorrow prices",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState,
|
||||
string timestamp)
|
||||
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices,
|
||||
string updateTimeState,
|
||||
string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
|
||||
{
|
||||
prices = mergedPrices.ToCompact(),
|
||||
prices_count = mergedPrices.Count,
|
||||
friendly_name = "NordPool today and tomorrow prices",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
prices = mergedPrices.ToCompact(),
|
||||
prices_count = mergedPrices.Count,
|
||||
friendly_name = "NordPool today and tomorrow prices",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateCheapestIntervalsAsync(EntityUpdateContext ctx, int cheapestCount, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
|
||||
{
|
||||
intervals = ctx.CheapestIntervals ?? [],
|
||||
configured_hours = ctx.ConfiguredHours,
|
||||
configured_interval_count = ctx.ConfiguredIntervalCount,
|
||||
configured_price_cap = ctx.ConfiguredPriceCap,
|
||||
skip_price_cap = ctx.SkipPriceCap,
|
||||
configured_ready_by = ctx.ConfiguredReadyBy,
|
||||
total_heating_minutes = cheapestCount * NordPoolConsts.MinutesPerInterval,
|
||||
is_now_cheap = ctx.IsNowCheap,
|
||||
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture),
|
||||
friendly_name = "NordPool cheapest boiler intervals",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
intervals = ctx.CheapestIntervals ?? [],
|
||||
configured_hours = ctx.ConfiguredHours,
|
||||
configured_interval_count = ctx.ConfiguredIntervalCount,
|
||||
configured_price_cap = ctx.ConfiguredPriceCap,
|
||||
skip_price_cap = ctx.SkipPriceCap,
|
||||
configured_ready_by = ctx.ConfiguredReadyBy,
|
||||
total_heating_minutes = cheapestCount * NordPoolConsts.MinutesPerInterval,
|
||||
is_now_cheap = ctx.IsNowCheap,
|
||||
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture),
|
||||
friendly_name = "NordPool cheapest boiler intervals",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
|
||||
@@ -321,9 +352,9 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
return
|
||||
[
|
||||
.. todayList
|
||||
.Concat(tomorrowList)
|
||||
.Where(p => p is { Start: not null })
|
||||
.OrderBy(p => p.Start!.Value)
|
||||
.Concat(tomorrowList)
|
||||
.Where(p => p is { Start: not null })
|
||||
.OrderBy(p => p.Start!.Value)
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Reactive.Concurrency;
|
||||
using BoilerMonitor.Models;
|
||||
@@ -12,6 +14,8 @@ using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -67,7 +71,10 @@ public class NordPoolInit
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync();
|
||||
if (_options.CleanupEntitiesOnStartup)
|
||||
{
|
||||
await _entityService.CleanupEntitiesAsync();
|
||||
}
|
||||
|
||||
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
|
||||
await _entityService.ResetEntitiesAsync();
|
||||
@@ -78,6 +85,7 @@ public class NordPoolInit
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing NordPool prices");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -123,7 +131,7 @@ public class NordPoolInit
|
||||
}
|
||||
|
||||
await _priceService.FetchPricesAsync(FetchPricesForDateAsync);
|
||||
|
||||
|
||||
_priceService.UpdateCurrentPrice();
|
||||
|
||||
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
|
||||
@@ -139,13 +147,13 @@ public class NordPoolInit
|
||||
private async Task<NordPoolPrice> FetchPricesForDateAsync(DateOnly date)
|
||||
{
|
||||
var nordPoolPricesDto = await _services.Nordpool.GetPricesForDateAsync(
|
||||
new NordpoolGetPricesForDateParameters
|
||||
{
|
||||
Areas = "LT",
|
||||
ConfigEntry = NordPoolConsts.ConfigEntry,
|
||||
Currency = "EUR",
|
||||
Date = date
|
||||
});
|
||||
new NordpoolGetPricesForDateParameters
|
||||
{
|
||||
Areas = "LT",
|
||||
ConfigEntry = NordPoolConsts.ConfigEntry,
|
||||
Currency = "EUR",
|
||||
Date = date
|
||||
});
|
||||
|
||||
return _priceService.ParseAndAdjust(nordPoolPricesDto);
|
||||
}
|
||||
@@ -153,12 +161,13 @@ public class NordPoolInit
|
||||
private void SubscribeToFetchPricesButton()
|
||||
{
|
||||
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
|
||||
|
||||
button.StateChanges()
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update");
|
||||
Task.Run(UpdatePricesAsync);
|
||||
});
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update");
|
||||
Task.Run(UpdatePricesAsync);
|
||||
});
|
||||
}
|
||||
|
||||
private void UpdateCheapestIntervals(BoilerConfig config)
|
||||
@@ -198,9 +207,9 @@ public class NordPoolInit
|
||||
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
|
||||
|
||||
var nextCheapInterval = CheapestIntervals?
|
||||
.Where(i => i.Start > currentDateTime)
|
||||
.OrderBy(i => i.Start)
|
||||
.FirstOrDefault();
|
||||
.Where(i => i.Start > currentDateTime)
|
||||
.OrderBy(i => i.Start)
|
||||
.FirstOrDefault();
|
||||
|
||||
var context = new EntityUpdateContext
|
||||
{
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using AutoMapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using NordPool.Models.Dtos;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
if (DayQuartersIndex == index) return;
|
||||
if (DayQuartersIndex == index)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
|
||||
{
|
||||
@@ -91,13 +98,25 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
|
||||
public bool ShouldFetchNewPrices(DateOnly date)
|
||||
{
|
||||
if (!LastFetchedDate.HasValue) return true;
|
||||
if (!LastFetchedDate.HasValue)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (LastFetchedDate.Value < date) return true;
|
||||
if (LastFetchedDate.Value < date)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true;
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false;
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var currentHour = DateTime.Now.Hour;
|
||||
|
||||
@@ -107,8 +126,8 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
public void RollOverPrices(DateOnly date)
|
||||
{
|
||||
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 }
|
||||
? TomorrowNordPoolPrice
|
||||
: new NordPoolPrice();
|
||||
? TomorrowNordPoolPrice
|
||||
: new NordPoolPrice();
|
||||
|
||||
TomorrowNordPoolPrice = null;
|
||||
|
||||
@@ -125,13 +144,16 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
|
||||
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
||||
{
|
||||
if (!element.HasValue) return new NordPoolPrice();
|
||||
if (!element.HasValue)
|
||||
{
|
||||
return new NordPoolPrice();
|
||||
}
|
||||
|
||||
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
||||
|
||||
return priceResult != null
|
||||
? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult)
|
||||
: new NordPoolPrice();
|
||||
? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult)
|
||||
: new NordPoolPrice();
|
||||
}
|
||||
|
||||
internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
|
||||
@@ -141,11 +163,17 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
Prices = new List<NordPoolDayPrice>()
|
||||
};
|
||||
|
||||
if (todayNordPoolPrice.Prices is null) return recalculatedPrice;
|
||||
if (todayNordPoolPrice.Prices is null)
|
||||
{
|
||||
return recalculatedPrice;
|
||||
}
|
||||
|
||||
foreach (var price in todayNordPoolPrice.Prices)
|
||||
{
|
||||
if (price.Price is null) continue;
|
||||
if (price.Price is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
recalculatedPrice.Prices.Add(new NordPoolDayPrice
|
||||
{
|
||||
@@ -179,6 +207,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
|
||||
{
|
||||
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await fetchPricesForDate(date);
|
||||
@@ -193,8 +222,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date);
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public static class NordPoolServiceRegistration
|
||||
@@ -9,13 +13,14 @@ public static class NordPoolServiceRegistration
|
||||
public static IServiceCollection AddNordPool(this IServiceCollection services)
|
||||
{
|
||||
services
|
||||
.AddNetDaemonApp<NordPoolInit>()
|
||||
.AddNetDaemonApp<NordPoolInit>()
|
||||
|
||||
// Singleton is safe: NordPoolPriceService holds no IHaContext/generated
|
||||
// entity dependency. The HA price fetch call lives in NordPoolInit.
|
||||
.AddSingleton<INordPoolPriceService, NordPoolPriceService>()
|
||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||
.AddTransient<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>();
|
||||
.AddSingleton<INordPoolPriceService, NordPoolPriceService>()
|
||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||
.AddTransient<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Models;
|
||||
|
||||
public class CheapestIntervalResult
|
||||
{
|
||||
[JsonPropertyName("start")] public DateTime Start { get; init; }
|
||||
[JsonPropertyName("start")]
|
||||
public DateTime Start { get; init; }
|
||||
|
||||
[JsonPropertyName("end")] public DateTime End { get; init; }
|
||||
[JsonPropertyName("end")]
|
||||
public DateTime End { get; init; }
|
||||
|
||||
[JsonPropertyName("price")] public double Price { get; init; }
|
||||
[JsonPropertyName("price")]
|
||||
public double Price { get; init; }
|
||||
|
||||
[JsonPropertyName("rank")] public int Rank { get; init; }
|
||||
[JsonPropertyName("rank")]
|
||||
public int Rank { get; init; }
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Models;
|
||||
|
||||
[JsonConverter(typeof(CompactNordPoolDayPriceConverter))]
|
||||
@@ -19,11 +23,11 @@ public readonly struct CompactNordPoolDayPrice
|
||||
return new CompactNordPoolDayPrice
|
||||
{
|
||||
Start = dayPrice.Start.HasValue
|
||||
? ToUnixSeconds(dayPrice.Start.Value)
|
||||
: NullTimestampSentinel,
|
||||
? ToUnixSeconds(dayPrice.Start.Value)
|
||||
: NullTimestampSentinel,
|
||||
End = dayPrice.End.HasValue
|
||||
? ToUnixSeconds(dayPrice.End.Value)
|
||||
: NullTimestampSentinel,
|
||||
? ToUnixSeconds(dayPrice.End.Value)
|
||||
: NullTimestampSentinel,
|
||||
Price = dayPrice.Price
|
||||
};
|
||||
}
|
||||
@@ -31,8 +35,8 @@ public readonly struct CompactNordPoolDayPrice
|
||||
private static long ToUnixSeconds(DateTime dateTime)
|
||||
{
|
||||
var utc = dateTime.Kind == DateTimeKind.Utc
|
||||
? dateTime
|
||||
: dateTime.ToUniversalTime();
|
||||
? dateTime
|
||||
: dateTime.ToUniversalTime();
|
||||
|
||||
return new DateTimeOffset(utc, TimeSpan.Zero).ToUnixTimeSeconds();
|
||||
}
|
||||
@@ -40,10 +44,14 @@ public readonly struct CompactNordPoolDayPrice
|
||||
|
||||
internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNordPoolDayPrice>
|
||||
{
|
||||
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert,
|
||||
JsonSerializerOptions options)
|
||||
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader,
|
||||
Type typeToConvert,
|
||||
JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("Expected start of array.");
|
||||
if (reader.TokenType != JsonTokenType.StartArray)
|
||||
{
|
||||
throw new JsonException("Expected start of array.");
|
||||
}
|
||||
|
||||
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
||||
{
|
||||
@@ -69,8 +77,8 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNo
|
||||
reader.Read();
|
||||
|
||||
return reader.TokenType == JsonTokenType.EndArray
|
||||
? new CompactNordPoolDayPrice { Start = start, End = end, Price = price }
|
||||
: throw new JsonException("Expected end of array.");
|
||||
? new CompactNordPoolDayPrice { Start = start, End = end, Price = price }
|
||||
: throw new JsonException("Expected end of array.");
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, CompactNordPoolDayPrice value, JsonSerializerOptions options)
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
using System.Text.Json.Serialization;
|
||||
#region
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Models.Dtos;
|
||||
|
||||
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;
|
||||
|
||||
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)
|
||||
{
|
||||
return prices is null
|
||||
? []
|
||||
: [.. prices.Select(CompactNordPoolDayPrice.FromDayPrice)];
|
||||
? []
|
||||
: [.. prices.Select(CompactNordPoolDayPrice.FromDayPrice)];
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using HomeAssistant.Models;
|
||||
using NetDaemon.Extensions.MqttEntityManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPool.Models;
|
||||
|
||||
public class NordPoolEntity : EntityCreateModel
|
||||
@@ -39,8 +43,9 @@ public class NordPoolEntity : EntityCreateModel
|
||||
/// </summary>
|
||||
public static object CreateAdditionalConfig(object extraProperties)
|
||||
{
|
||||
var extras = extraProperties.GetType().GetProperties()
|
||||
.ToDictionary(p => p.Name, p => p.GetValue(extraProperties));
|
||||
var extras = extraProperties.GetType()
|
||||
.GetProperties()
|
||||
.ToDictionary(p => p.Name, p => p.GetValue(extraProperties));
|
||||
|
||||
extras["device"] = DeviceBlock;
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class CostAccumulatorTests
|
||||
@@ -27,11 +31,14 @@ public class CostAccumulatorTests
|
||||
|
||||
// Act
|
||||
var tasks = Enumerable.Range(0, threadCount)
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
||||
}))
|
||||
.ToArray();
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++)
|
||||
{
|
||||
sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
||||
}
|
||||
}))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
@@ -47,11 +54,7 @@ public class CostAccumulatorTests
|
||||
{
|
||||
return window switch
|
||||
{
|
||||
CostWindow.FifteenMinutes => snapshot.Cost15Min,
|
||||
CostWindow.Hour => snapshot.Cost1Hour,
|
||||
CostWindow.Day => snapshot.CostDaily,
|
||||
CostWindow.Month => snapshot.CostMonthly,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(window))
|
||||
CostWindow.FifteenMinutes => snapshot.Cost15Min, CostWindow.Hour => snapshot.Cost1Hour, CostWindow.Day => snapshot.CostDaily, CostWindow.Month => snapshot.CostMonthly, _ => throw new ArgumentOutOfRangeException(nameof(window))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -116,12 +119,16 @@ public class CostAccumulatorTests
|
||||
// Arrange
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
var sut = new CostAccumulator(now);
|
||||
|
||||
var increments = PowerMonitorTestData.CreatePowerSampleSeries(50)
|
||||
.Select(watts => watts / 100_000.0)
|
||||
.ToArray();
|
||||
.Select(watts => watts / 100_000.0)
|
||||
.ToArray();
|
||||
|
||||
// Act
|
||||
foreach (var increment in increments) sut.AddCost(increment, now.AddSeconds(1));
|
||||
foreach (var increment in increments)
|
||||
{
|
||||
sut.AddCost(increment, now.AddSeconds(1));
|
||||
}
|
||||
|
||||
// Assert
|
||||
var expected = increments.Sum();
|
||||
@@ -191,7 +198,7 @@ public class CostAccumulatorTests
|
||||
|
||||
#region Window rollovers
|
||||
|
||||
public static TheoryData<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),
|
||||
@@ -323,7 +330,7 @@ public class CostAccumulatorTests
|
||||
|
||||
#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, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false },
|
||||
@@ -344,7 +351,7 @@ public class CostAccumulatorTests
|
||||
CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
public static TheoryData<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 },
|
||||
{
|
||||
@@ -366,7 +373,7 @@ public class CostAccumulatorTests
|
||||
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 day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false },
|
||||
@@ -385,7 +392,7 @@ public class CostAccumulatorTests
|
||||
CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
public static TheoryData<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, 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 Microsoft.Extensions.Options;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class OtherPowerCalculationServiceTests
|
||||
@@ -13,12 +17,13 @@ public class OtherPowerCalculationServiceTests
|
||||
{
|
||||
SmoothingWindowSize = smoothingWindowSize
|
||||
});
|
||||
|
||||
return new OtherPowerCalculationService(options);
|
||||
}
|
||||
|
||||
#region Basic calculation
|
||||
|
||||
public static TheoryData<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" },
|
||||
{ "no devices", 341.97, [], 341.97, "ok" },
|
||||
@@ -42,9 +47,10 @@ public class OtherPowerCalculationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(1);
|
||||
|
||||
var devices = deviceWatts
|
||||
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
|
||||
.ToDictionary(entry => entry.entityId, entry => entry.watts);
|
||||
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
|
||||
.ToDictionary(entry => entry.entityId, entry => entry.watts);
|
||||
|
||||
// Act
|
||||
var result = sut.Calculate(totalPowerWatts, devices);
|
||||
@@ -166,7 +172,11 @@ public class OtherPowerCalculationServiceTests
|
||||
|
||||
// Act
|
||||
PowerCalculationResult? result = null;
|
||||
for (var i = 0; i < 200; i++) result = sut.Calculate(200.0, new Dictionary<string, double>());
|
||||
|
||||
for (var i = 0; i < 200; i++)
|
||||
{
|
||||
result = sut.Calculate(200.0, new Dictionary<string, double>());
|
||||
}
|
||||
|
||||
// Assert
|
||||
result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1);
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerCostCalculationServiceTests
|
||||
@@ -12,7 +16,7 @@ public class PowerCostCalculationServiceTests
|
||||
Other
|
||||
}
|
||||
|
||||
private readonly PowerCostCalculationService _sut = new();
|
||||
private readonly PowerCostCalculationService _sut = new PowerCostCalculationService();
|
||||
|
||||
#region Snapshot defaults
|
||||
|
||||
@@ -23,8 +27,8 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// Act
|
||||
var snapshot = bucket == CostBucket.Total
|
||||
? _sut.GetTotalCostSnapshot()
|
||||
: _sut.GetOtherCostSnapshot();
|
||||
? _sut.GetTotalCostSnapshot()
|
||||
: _sut.GetOtherCostSnapshot();
|
||||
|
||||
// Assert
|
||||
snapshot.Cost15Min.Should().Be(0);
|
||||
@@ -49,12 +53,14 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
var tasks = Enumerable.Range(0, threadCount)
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++)
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
|
||||
}))
|
||||
.ToArray();
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++)
|
||||
{
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
|
||||
}
|
||||
}))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
@@ -73,14 +79,12 @@ public class PowerCostCalculationServiceTests
|
||||
double pricePerKwh,
|
||||
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds)
|
||||
{
|
||||
return powerWatts / PowerMonitorConsts.WattsPerKilowatt
|
||||
* pricePerKwh
|
||||
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
return powerWatts / PowerMonitorConsts.WattsPerKilowatt * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
}
|
||||
|
||||
#region CalculateCostIncrement
|
||||
|
||||
public static TheoryData<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 },
|
||||
{ "one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0 },
|
||||
@@ -121,14 +125,17 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
var costs = samples
|
||||
.Select(watts =>
|
||||
PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds))
|
||||
.ToArray();
|
||||
.Select(watts =>
|
||||
PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds))
|
||||
.ToArray();
|
||||
|
||||
// Assert
|
||||
costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one");
|
||||
|
||||
for (var i = 0; i < samples.Count; i++)
|
||||
{
|
||||
costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -144,13 +151,14 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var expectedTotal =
|
||||
ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||
|
||||
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts,
|
||||
PowerMonitorTestData.DefaultPricePerKwh);
|
||||
PowerMonitorTestData.DefaultPricePerKwh);
|
||||
|
||||
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12);
|
||||
_sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12);
|
||||
@@ -168,7 +176,7 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var snapshot = _sut.GetDeviceCostSnapshot(entityId);
|
||||
@@ -187,7 +195,7 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var total = _sut.GetTotalCostSnapshot();
|
||||
@@ -218,15 +226,16 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
|
||||
var firstResult = PowerMonitorTestData.CreateCalculation(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
|
||||
|
||||
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15,
|
||||
now.AddSeconds(15));
|
||||
now.AddSeconds(15));
|
||||
|
||||
// Assert
|
||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
|
||||
@@ -242,7 +251,8 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
var singleDeviceResult = PowerMonitorTestData.CreateCalculation(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
|
||||
|
||||
_sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
|
||||
|
||||
// Assert
|
||||
@@ -270,10 +280,11 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
0,
|
||||
0,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
||||
0,
|
||||
0,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||
@@ -290,8 +301,9 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// Arrange - a sensor glitch must flow through the pure cost math unchanged.
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0)));
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||
@@ -382,17 +394,19 @@ public class PowerCostCalculationServiceTests
|
||||
const double pricePerKwh = 0.2;
|
||||
var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96);
|
||||
var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries();
|
||||
|
||||
var expectedPerSlot = timestamps
|
||||
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh))
|
||||
.ToArray();
|
||||
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh))
|
||||
.ToArray();
|
||||
|
||||
// Act
|
||||
for (var slot = 0; slot < timestamps.Count; slot++)
|
||||
{
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
wattSamples[slot],
|
||||
wattSamples[slot] / 2,
|
||||
new Dictionary<string, double>());
|
||||
wattSamples[slot],
|
||||
wattSamples[slot] / 2,
|
||||
new Dictionary<string, double>());
|
||||
|
||||
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
|
||||
}
|
||||
|
||||
@@ -416,10 +430,12 @@ public class PowerCostCalculationServiceTests
|
||||
foreach (var (start, pricePerKwh) in windows)
|
||||
{
|
||||
var watts = 500.0 + start.Hour * 125.0;
|
||||
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
watts,
|
||||
watts / 4,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
|
||||
watts,
|
||||
watts / 4,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
|
||||
|
||||
_sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start);
|
||||
expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds));
|
||||
}
|
||||
@@ -476,8 +492,10 @@ public class PowerCostCalculationServiceTests
|
||||
// Assert
|
||||
_sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh);
|
||||
_sut.PriceSource.Should().Be("live");
|
||||
|
||||
var expected =
|
||||
2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||
|
||||
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -9,6 +11,8 @@ using NetDaemon.HassModel.Entities;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerLimitEnforcementServiceTests
|
||||
@@ -16,53 +20,53 @@ public class PowerLimitEnforcementServiceTests
|
||||
private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId;
|
||||
private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId;
|
||||
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
|
||||
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
|
||||
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
|
||||
private readonly FakeTimeProvider _timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow);
|
||||
|
||||
private PowerLimitEnforcementService CreateSut()
|
||||
{
|
||||
return new PowerLimitEnforcementService(
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options),
|
||||
_timeProvider);
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options),
|
||||
_timeProvider);
|
||||
}
|
||||
|
||||
private void VerifyNoServiceCalls()
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
private void VerifyTurnOff(string entityId, int expectedCalls)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
||||
Times.Exactly(expectedCalls));
|
||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
||||
Times.Exactly(expectedCalls));
|
||||
}
|
||||
|
||||
private void VerifyTurnOn(string entityId, int expectedCalls)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
||||
Times.Exactly(expectedCalls));
|
||||
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
||||
Times.Exactly(expectedCalls));
|
||||
}
|
||||
|
||||
private void VerifyNotificationCreated(int expectedCalls)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(expectedCalls));
|
||||
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(expectedCalls));
|
||||
}
|
||||
|
||||
private void VerifyNotificationDismissed(int expectedCalls)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(expectedCalls));
|
||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(expectedCalls));
|
||||
}
|
||||
|
||||
#region EnforceLimit
|
||||
@@ -131,11 +135,13 @@ public class PowerLimitEnforcementServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var calls = new List<(string domain, string service, string? entityId)>();
|
||||
|
||||
_haContextMock
|
||||
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(),
|
||||
It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((d, s, t, _) =>
|
||||
calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
|
||||
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(),
|
||||
It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((d, s, t, _) =>
|
||||
calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
@@ -144,8 +150,12 @@ public class PowerLimitEnforcementServiceTests
|
||||
// Assert
|
||||
var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList();
|
||||
turnOffCalls.Should().HaveCount(2);
|
||||
turnOffCalls[0].entityId.Should().Be(BoilerSwitch,
|
||||
"boiler switch must be turned off before auto_management (race-safe order)");
|
||||
|
||||
turnOffCalls[0]
|
||||
.entityId.Should()
|
||||
.Be(BoilerSwitch,
|
||||
"boiler switch must be turned off before auto_management (race-safe order)");
|
||||
|
||||
turnOffCalls[1].entityId.Should().Be(AutoManagement);
|
||||
}
|
||||
|
||||
@@ -156,10 +166,12 @@ public class PowerLimitEnforcementServiceTests
|
||||
_options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"];
|
||||
_options.PauseAndRestoreEntityIds = ["switch.monitor_c"];
|
||||
var calls = new List<string?>();
|
||||
|
||||
_haContextMock
|
||||
.Setup(x => x.CallService(It.IsAny<string>(), "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((_, _, target, _) =>
|
||||
calls.Add(target?.EntityIds?.FirstOrDefault()));
|
||||
.Setup(x => x.CallService(It.IsAny<string>(), "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((_, _, target, _) =>
|
||||
calls.Add(target?.EntityIds?.FirstOrDefault()));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
@@ -184,16 +196,17 @@ public class PowerLimitEnforcementServiceTests
|
||||
// Assert
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
VerifyNotificationCreated(1);
|
||||
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#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 },
|
||||
{ "one second before due", 599, 3000.0, true, 0 },
|
||||
@@ -268,7 +281,7 @@ public class PowerLimitEnforcementServiceTests
|
||||
[InlineData(31, true)]
|
||||
[InlineData(600, true)]
|
||||
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery,
|
||||
bool expectedLimitActive)
|
||||
bool expectedLimitActive)
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut();
|
||||
@@ -379,9 +392,11 @@ public class PowerLimitEnforcementServiceTests
|
||||
|
||||
// Assert
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(3));
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(3));
|
||||
|
||||
VerifyTurnOff(BoilerSwitch, 1);
|
||||
VerifyTurnOff(AutoManagement, 1);
|
||||
VerifyNotificationCreated(1);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -5,6 +7,8 @@ using Moq;
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerMonitorEntityServiceTests
|
||||
@@ -27,18 +31,22 @@ public class PowerMonitorEntityServiceTests
|
||||
"button.powermonitor_trigger_limit_breach"
|
||||
];
|
||||
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new();
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
|
||||
private readonly PowerMonitorEntityService _sut;
|
||||
|
||||
public PowerMonitorEntityServiceTests()
|
||||
{
|
||||
var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
|
||||
|
||||
_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>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_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);
|
||||
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object);
|
||||
}
|
||||
@@ -56,6 +64,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
result.Should().HaveCount(4);
|
||||
|
||||
string[] expectedEntityIds =
|
||||
[
|
||||
$"sensor.powermonitor_{deviceName}_cost_15min",
|
||||
@@ -63,6 +72,7 @@ public class PowerMonitorEntityServiceTests
|
||||
$"sensor.powermonitor_{deviceName}_cost_daily",
|
||||
$"sensor.powermonitor_{deviceName}_cost_monthly"
|
||||
];
|
||||
|
||||
result.Should().BeEquivalentTo(expectedEntityIds);
|
||||
}
|
||||
|
||||
@@ -79,15 +89,15 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var sensors = Enumerable.Range(0, sensorCount)
|
||||
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
|
||||
.ToList();
|
||||
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
|
||||
.ToList();
|
||||
|
||||
// Act
|
||||
await _sut.CreateDeviceEntitiesAsync(sensors);
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()),
|
||||
Times.Exactly(expectedCreates));
|
||||
Times.Exactly(expectedCreates));
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -152,7 +162,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
#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" },
|
||||
{ "simple device", "sensor.tv_power", "TV Power", "tv" },
|
||||
@@ -176,6 +186,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
result.Should().HaveCount(4, $"scenario: {scenario}");
|
||||
|
||||
string[] expectedEntityIds =
|
||||
[
|
||||
$"sensor.powermonitor_{expectedDeviceName}_cost_15min",
|
||||
@@ -183,8 +194,10 @@ public class PowerMonitorEntityServiceTests
|
||||
$"sensor.powermonitor_{expectedDeviceName}_cost_daily",
|
||||
$"sensor.powermonitor_{expectedDeviceName}_cost_monthly"
|
||||
];
|
||||
|
||||
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}");
|
||||
result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}");
|
||||
|
||||
string[] expectedNames =
|
||||
[
|
||||
$"{friendlyName} cost (15 min)",
|
||||
@@ -192,6 +205,7 @@ public class PowerMonitorEntityServiceTests
|
||||
$"{friendlyName} cost (daily)",
|
||||
$"{friendlyName} cost (monthly)"
|
||||
];
|
||||
|
||||
result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
@@ -228,9 +242,9 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange - both 1h cost entities fail, the remaining twelve must still be created.
|
||||
_entityManagerMock
|
||||
.Setup(em =>
|
||||
em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
|
||||
.Setup(em =>
|
||||
em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
|
||||
|
||||
// Act
|
||||
await _sut.CreateSystemEntitiesAsync();
|
||||
@@ -282,8 +296,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.ResetEntitiesAsync();
|
||||
@@ -305,7 +319,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))),
|
||||
Times.Exactly(14));
|
||||
Times.Exactly(14));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -313,8 +327,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.RemoveSystemEntitiesAsync();
|
||||
@@ -335,8 +349,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var deviceNames = Enumerable.Range(0, deviceCount)
|
||||
.Select(index => $"device_{index}")
|
||||
.ToList();
|
||||
.Select(index => $"device_{index}")
|
||||
.ToList();
|
||||
|
||||
// Act
|
||||
await _sut.RemoveDeviceEntitiesAsync(deviceNames);
|
||||
@@ -350,8 +364,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.RemoveEntity(It.Is<string>(id => id.Contains("_cost_daily"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
.Setup(em => em.RemoveEntity(It.Is<string>(id => id.Contains("_cost_daily"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.RemoveDeviceEntitiesAsync(["device_a", "device_b"]);
|
||||
@@ -398,16 +412,18 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var context = PowerMonitorTestData.CreateUpdateContext(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings((entityId, 42.0)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings((entityId, 42.0)));
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
// Assert
|
||||
foreach (var window in new[] { "15min", "1h", "daily", "monthly" })
|
||||
{
|
||||
_entityManagerMock.Verify(
|
||||
em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny<string>()),
|
||||
Times.Once);
|
||||
em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny<string>()),
|
||||
Times.Once);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -423,7 +439,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -447,7 +463,7 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var context = PowerMonitorTestData.CreateUpdateContext(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0)));
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
@@ -455,8 +471,10 @@ public class PowerMonitorEntityServiceTests
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "342.0"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "128.5"), Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once);
|
||||
}
|
||||
|
||||
@@ -465,8 +483,9 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
var context = PowerMonitorTestData.CreateUpdateContext();
|
||||
|
||||
// Act
|
||||
@@ -475,8 +494,9 @@ public class PowerMonitorEntityServiceTests
|
||||
// Assert
|
||||
await act.Should().NotThrowAsync();
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -488,8 +508,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
|
||||
@@ -503,8 +523,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { });
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerMonitorOptionsTests
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -21,11 +25,11 @@ internal static class PowerMonitorTestData
|
||||
public const string AutoManagementEntityId = "switch.boilermonitor_auto_management";
|
||||
public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power";
|
||||
|
||||
public static readonly DateTime FixedNow = new(2026, 3, 17, 10, 0, 0);
|
||||
public static readonly DateTime FixedNow = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
|
||||
public static readonly DateTime FixedDayStart = new(2026, 3, 17, 0, 0, 0);
|
||||
public static readonly DateTime FixedDayStart = new DateTime(2026, 3, 17, 0, 0, 0);
|
||||
|
||||
public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
|
||||
public static readonly DateTimeOffset FixedUtcNow = new DateTimeOffset(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <summary>
|
||||
/// Two-device reading set used by the cost calculation tests.
|
||||
@@ -107,13 +111,14 @@ internal static class PowerMonitorTestData
|
||||
string priceSource = "live")
|
||||
{
|
||||
var readings = deviceReadings ?? CreateDeviceReadings();
|
||||
|
||||
var deviceCosts = readings
|
||||
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
|
||||
0.0005 * (index + 1),
|
||||
0.002 * (index + 1),
|
||||
0.03 * (index + 1),
|
||||
0.9 * (index + 1))))
|
||||
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
|
||||
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
|
||||
0.0005 * (index + 1),
|
||||
0.002 * (index + 1),
|
||||
0.03 * (index + 1),
|
||||
0.9 * (index + 1))))
|
||||
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
|
||||
|
||||
return new PowerUpdateContext
|
||||
{
|
||||
@@ -143,21 +148,22 @@ internal static class PowerMonitorTestData
|
||||
};
|
||||
|
||||
configure?.Invoke(options);
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null)
|
||||
{
|
||||
return CreateOptions(options =>
|
||||
{
|
||||
options.EnforceLimitEnabled = true;
|
||||
options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts;
|
||||
options.RecoverySeconds = PowerMonitorConsts.DefaultRecoverySeconds;
|
||||
options.LimitCooldownSeconds = PowerMonitorConsts.DefaultLimitCooldownSeconds;
|
||||
options.EnforceSwitchOffEntityIds = [BoilerSwitchEntityId];
|
||||
options.PauseAndRestoreEntityIds = [AutoManagementEntityId];
|
||||
configure?.Invoke(options);
|
||||
});
|
||||
{
|
||||
options.EnforceLimitEnabled = true;
|
||||
options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts;
|
||||
options.RecoverySeconds = PowerMonitorConsts.DefaultRecoverySeconds;
|
||||
options.LimitCooldownSeconds = PowerMonitorConsts.DefaultLimitCooldownSeconds;
|
||||
options.EnforceSwitchOffEntityIds = [BoilerSwitchEntityId];
|
||||
options.PauseAndRestoreEntityIds = [AutoManagementEntityId];
|
||||
configure?.Invoke(options);
|
||||
});
|
||||
}
|
||||
|
||||
public static PowerSensorInfo CreateSensor(
|
||||
@@ -182,11 +188,20 @@ internal static class PowerMonitorTestData
|
||||
{
|
||||
var attributes = new Dictionary<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);
|
||||
}
|
||||
@@ -200,7 +215,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
|
||||
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -212,7 +227,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
|
||||
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -223,7 +238,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, prices.Count)
|
||||
.Select(hour => (dayStart.AddHours(hour), prices[hour]))
|
||||
.Select(hour => (dayStart.AddHours(hour), prices[hour]))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -232,7 +247,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => start.AddMinutes(i * intervalMinutes))
|
||||
.Select(i => start.AddMinutes(i * intervalMinutes))
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -6,22 +8,25 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using PowerMonitorManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new Mock<ILogger<PowerSensorDiscoveryService>>();
|
||||
|
||||
private PowerSensorDiscoveryService CreateSut(
|
||||
string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId,
|
||||
string[]? excludedPatterns = null)
|
||||
{
|
||||
var options = Options.Create(PowerMonitorTestData.CreateOptions(option =>
|
||||
{
|
||||
option.MainMeterEntityId = mainMeterEntityId;
|
||||
option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"];
|
||||
}));
|
||||
{
|
||||
option.MainMeterEntityId = mainMeterEntityId;
|
||||
option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"];
|
||||
}));
|
||||
|
||||
return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object);
|
||||
}
|
||||
|
||||
@@ -33,6 +38,7 @@ public class PowerSensorDiscoveryServiceTests
|
||||
};
|
||||
|
||||
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||
|
||||
return new Entity(_haContextMock.Object, entityId);
|
||||
}
|
||||
|
||||
@@ -40,18 +46,18 @@ public class PowerSensorDiscoveryServiceTests
|
||||
params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities)
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([
|
||||
.. entities.Select(entity =>
|
||||
SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))
|
||||
SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))
|
||||
]);
|
||||
}
|
||||
|
||||
private void SetupEntitiesWithoutState(params string[] entityIds)
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
|
||||
}
|
||||
|
||||
#region ExtractDeviceName
|
||||
@@ -102,10 +108,10 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
|
||||
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"),
|
||||
("sensor.temperature", "temperature", "°C", "Temperature"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
|
||||
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"),
|
||||
("sensor.temperature", "temperature", "°C", "Temperature"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -123,8 +129,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -141,8 +147,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
|
||||
var sut = CreateSut(string.Empty);
|
||||
|
||||
@@ -159,10 +165,10 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.nordpool_some_power", "power", "W", "NordPool"),
|
||||
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.nordpool_some_power", "power", "W", "NordPool"),
|
||||
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -179,8 +185,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
|
||||
|
||||
var sut = CreateSut(excludedPatterns: []);
|
||||
|
||||
@@ -225,9 +231,9 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
("sensor.temperature", "temperature", "°C", "Temp"),
|
||||
("switch.some_switch", null, null, "Switch"),
|
||||
("sensor.energy_usage", "energy", "kWh", "Energy"));
|
||||
("sensor.temperature", "temperature", "°C", "Temp"),
|
||||
("switch.some_switch", null, null, "Switch"),
|
||||
("sensor.energy_usage", "energy", "kWh", "Energy"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -243,9 +249,10 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange - HA can report entities whose state has not been published yet.
|
||||
var tv = SetupEntity("sensor.tv_power", "power", "W", "TV Power");
|
||||
|
||||
_haContextMock
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns(new List<Entity> { new(_haContextMock.Object, "sensor.ghost_power"), tv });
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns(new List<Entity> { new Entity(_haContextMock.Object, "sensor.ghost_power"), tv });
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -262,8 +269,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange - discovery is a projection of HA's entity list; de-duplication is not its job.
|
||||
SetupEntities(
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -280,8 +287,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.akvariumas_power", "power", "W", "Akvariumas Power"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.akvariumas_power", "power", "W", "Akvariumas Power"));
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.CurrentDeviceSensors.Should().BeEmpty();
|
||||
@@ -298,17 +305,17 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"));
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.DiscoverDeviceSensors();
|
||||
sut.CurrentDeviceSensors.Should().HaveCount(1);
|
||||
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
|
||||
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
|
||||
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"));
|
||||
|
||||
// Act
|
||||
sut.DiscoverDeviceSensors();
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IOtherPowerCalculationService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerCostCalculationService
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerMonitorEntityService
|
||||
@@ -8,12 +12,12 @@ public interface IPowerMonitorEntityService
|
||||
Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors,
|
||||
CancellationToken cancellationToken = default);
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default);
|
||||
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
Task RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames,
|
||||
CancellationToken cancellationToken = default);
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using PowerMonitor.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerSensorDiscoveryService
|
||||
|
||||
@@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models;
|
||||
|
||||
public sealed class CostAccumulator(DateTime now)
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Lock _lock = new Lock();
|
||||
|
||||
private double _cost15Min;
|
||||
private double _cost1Hour;
|
||||
@@ -77,7 +77,10 @@ public sealed class CostAccumulator(DateTime now)
|
||||
_lastDailyReset = now;
|
||||
}
|
||||
|
||||
if (!IsNewMonthWindow(now, _lastMonthlyReset)) return;
|
||||
if (!IsNewMonthWindow(now, _lastMonthlyReset))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_previousMonthly = _costMonthly;
|
||||
_costMonthly = 0;
|
||||
@@ -88,6 +91,7 @@ public sealed class CostAccumulator(DateTime now)
|
||||
{
|
||||
var currentSlot = now.Minute / 15;
|
||||
var lastSlot = lastReset.Minute / 15;
|
||||
|
||||
return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager.Models;
|
||||
|
||||
public sealed class PowerMonitorOptions
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
#region
|
||||
|
||||
using Microsoft.Extensions.Options;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
||||
{
|
||||
private readonly double _alpha;
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Lock _lock = new Lock();
|
||||
private double? _previousSmoothed;
|
||||
|
||||
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
|
||||
@@ -29,11 +33,13 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
||||
}
|
||||
|
||||
double smoothed;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
smoothed = _previousSmoothed.HasValue
|
||||
? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
|
||||
: rawOther;
|
||||
? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
|
||||
: rawOther;
|
||||
|
||||
_previousSmoothed = smoothed;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
#region
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
{
|
||||
private readonly Lock _accumulatorLock = new();
|
||||
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
|
||||
private readonly Lock _priceLock = new();
|
||||
private readonly Lock _accumulatorLock = new Lock();
|
||||
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new ConcurrentDictionary<string, CostAccumulator>();
|
||||
private readonly Lock _priceLock = new Lock();
|
||||
|
||||
private double _lastKnownPrice;
|
||||
private CostAccumulator? _otherAccumulator;
|
||||
@@ -38,8 +42,10 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
}
|
||||
}
|
||||
|
||||
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds,
|
||||
DateTime now)
|
||||
public void RecordCosts(PowerCalculationResult calculation,
|
||||
double nordPoolPrice,
|
||||
int pollIntervalSeconds,
|
||||
DateTime now)
|
||||
{
|
||||
lock (_priceLock)
|
||||
{
|
||||
@@ -57,6 +63,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
|
||||
var otherCost =
|
||||
CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
|
||||
|
||||
GetOrCreateOtherAccumulator(now).AddCost(otherCost, now);
|
||||
|
||||
foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings)
|
||||
@@ -86,8 +93,8 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
public IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots()
|
||||
{
|
||||
return _deviceAccumulators.ToDictionary(
|
||||
kvp => kvp.Key,
|
||||
kvp => kvp.Value.GetSnapshot());
|
||||
kvp => kvp.Key,
|
||||
kvp => kvp.Value.GetSnapshot());
|
||||
}
|
||||
|
||||
public void SetPrice(double price)
|
||||
@@ -102,13 +109,14 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
public CostSnapshot GetDeviceCostSnapshot(string entityId)
|
||||
{
|
||||
return _deviceAccumulators.TryGetValue(entityId, out var accumulator)
|
||||
? accumulator.GetSnapshot()
|
||||
: CreateEmptySnapshot();
|
||||
? accumulator.GetSnapshot()
|
||||
: CreateEmptySnapshot();
|
||||
}
|
||||
|
||||
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
|
||||
{
|
||||
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
|
||||
|
||||
return powerKw * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -7,6 +9,8 @@ using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerLimitEnforcementService(
|
||||
@@ -25,13 +29,17 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
public void EnforceLimit(double currentPowerWatts)
|
||||
{
|
||||
if (!_options.EnforceLimitEnabled) return;
|
||||
if (!_options.EnforceLimitEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
|
||||
if (!IsLimitActive)
|
||||
{
|
||||
TryEnforce(currentPowerWatts, now);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -43,6 +51,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
if (IsLimitActive)
|
||||
{
|
||||
logger.LogInformation("Debug: trigger requested but limit already active");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -55,6 +64,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
if (!IsLimitActive)
|
||||
{
|
||||
logger.LogInformation("Debug: reset requested but limit not active");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -64,9 +74,15 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
private void ExecuteEnforce(double currentPowerWatts)
|
||||
{
|
||||
foreach (var entityId in _options.EnforceSwitchOffEntityIds) TurnOff(entityId);
|
||||
foreach (var entityId in _options.EnforceSwitchOffEntityIds)
|
||||
{
|
||||
TurnOff(entityId);
|
||||
}
|
||||
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOff(entityId);
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
||||
{
|
||||
TurnOff(entityId);
|
||||
}
|
||||
|
||||
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
|
||||
|
||||
@@ -78,7 +94,10 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
private void ExecuteRecover()
|
||||
{
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
||||
{
|
||||
TurnOn(entityId);
|
||||
}
|
||||
|
||||
DismissLimitNotification();
|
||||
|
||||
@@ -88,22 +107,25 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
private void TryEnforce(double currentPowerWatts, DateTimeOffset now)
|
||||
{
|
||||
if (currentPowerWatts <= _options.PowerLimitWatts) return;
|
||||
if (currentPowerWatts <= _options.PowerLimitWatts)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping",
|
||||
currentPowerWatts, _options.PowerLimitWatts);
|
||||
"Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping",
|
||||
currentPowerWatts, _options.PowerLimitWatts);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts,
|
||||
_options.PowerLimitWatts);
|
||||
_options.PowerLimitWatts);
|
||||
|
||||
ExecuteEnforce(currentPowerWatts);
|
||||
}
|
||||
@@ -112,12 +134,16 @@ public sealed class PowerLimitEnforcementService(
|
||||
{
|
||||
var elapsed = now - _enforcedAt;
|
||||
|
||||
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds)) return;
|
||||
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentPowerWatts >= _options.PowerLimitWatts)
|
||||
{
|
||||
logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced",
|
||||
currentPowerWatts, _options.PowerLimitWatts);
|
||||
currentPowerWatts, _options.PowerLimitWatts);
|
||||
|
||||
_enforcedAt = now;
|
||||
|
||||
return;
|
||||
@@ -126,11 +152,14 @@ public sealed class PowerLimitEnforcementService(
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors",
|
||||
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
|
||||
"Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors",
|
||||
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
||||
{
|
||||
TurnOn(entityId);
|
||||
}
|
||||
|
||||
DismissLimitNotification();
|
||||
|
||||
@@ -141,46 +170,46 @@ public sealed class PowerLimitEnforcementService(
|
||||
private void TurnOff(string entityId)
|
||||
{
|
||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService,
|
||||
ServiceTarget.FromEntity(entityId));
|
||||
ServiceTarget.FromEntity(entityId));
|
||||
}
|
||||
|
||||
private void TurnOn(string entityId)
|
||||
{
|
||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService,
|
||||
ServiceTarget.FromEntity(entityId));
|
||||
ServiceTarget.FromEntity(entityId));
|
||||
}
|
||||
|
||||
private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts)
|
||||
{
|
||||
var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt,
|
||||
limitWatts / PowerMonitorConsts.WattsPerKilowatt);
|
||||
limitWatts / PowerMonitorConsts.WattsPerKilowatt);
|
||||
|
||||
haContext.CallService(
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = PowerMonitorConsts.PowerLimitNotificationTitle,
|
||||
message,
|
||||
notification_id = PowerMonitorConsts.PowerLimitNotificationId
|
||||
});
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = PowerMonitorConsts.PowerLimitNotificationTitle,
|
||||
message,
|
||||
notification_id = PowerMonitorConsts.PowerLimitNotificationId
|
||||
});
|
||||
}
|
||||
|
||||
private void DismissLimitNotification()
|
||||
{
|
||||
haContext.CallService(
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new
|
||||
{
|
||||
notification_id = PowerMonitorConsts.PowerLimitNotificationId
|
||||
});
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new
|
||||
{
|
||||
notification_id = PowerMonitorConsts.PowerLimitNotificationId
|
||||
});
|
||||
}
|
||||
|
||||
internal static string BuildLimitMessage(double currentKw, double limitKw)
|
||||
{
|
||||
return string.Format(CultureInfo.InvariantCulture,
|
||||
"Home power usage **{0:F2} kW** exceeded the limit of **{1:F1} kW**.\n\nHigh-power appliances have been turned off and automatic control paused. Normal control resumes after power drops below the limit.",
|
||||
currentKw, limitKw);
|
||||
"Home power usage **{0:F2} kW** exceeded the limit of **{1:F1} kW**.\n\nHigh-power appliances have been turned off and automatic control paused. Normal control resumes after power drops below the limit.",
|
||||
currentKw, limitKw);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerMonitorEntityService(
|
||||
@@ -44,48 +48,50 @@ public sealed class PowerMonitorEntityService(
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var entities = GetSystemEntitiesList();
|
||||
var tasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
var tasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors,
|
||||
CancellationToken cancellationToken = default)
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var entities = sensors.SelectMany(GetPowerDeviceEntitiesNames).ToList();
|
||||
var tasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create device cost entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
var tasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create device cost entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
@@ -100,22 +106,22 @@ public sealed class PowerMonitorEntityService(
|
||||
{
|
||||
UpdateTotalPowerAsync(context, timestamp),
|
||||
UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost,
|
||||
"Total cost (15 min)", timestamp),
|
||||
"Total cost (15 min)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost,
|
||||
"Total cost (1h)", timestamp),
|
||||
"Total cost (1h)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost,
|
||||
"Total cost (daily)", timestamp),
|
||||
"Total cost (daily)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost,
|
||||
"Total cost (monthly)", timestamp),
|
||||
"Total cost (monthly)", timestamp),
|
||||
UpdateOtherPowerAsync(context, timestamp),
|
||||
UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost,
|
||||
"Other cost (15 min)", timestamp),
|
||||
"Other cost (15 min)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost,
|
||||
"Other cost (1h)", timestamp),
|
||||
"Other cost (1h)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost,
|
||||
"Other cost (daily)", timestamp),
|
||||
"Other cost (daily)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost,
|
||||
"Other cost (monthly)", timestamp),
|
||||
"Other cost (monthly)", timestamp),
|
||||
UpdateAnomalyAsync(context, timestamp),
|
||||
UpdateStatusAsync(context, timestamp)
|
||||
};
|
||||
@@ -123,14 +129,18 @@ public sealed class PowerMonitorEntityService(
|
||||
foreach (var (entityId, costSnapshot) in context.DeviceCosts)
|
||||
{
|
||||
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(entityId);
|
||||
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min,
|
||||
costSnapshot, $"{deviceName} cost (15 min)", timestamp));
|
||||
costSnapshot, $"{deviceName} cost (15 min)", timestamp));
|
||||
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour,
|
||||
costSnapshot, $"{deviceName} cost (1h)", timestamp));
|
||||
costSnapshot, $"{deviceName} cost (1h)", timestamp));
|
||||
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily,
|
||||
costSnapshot, $"{deviceName} cost (daily)", timestamp));
|
||||
costSnapshot, $"{deviceName} cost (daily)", timestamp));
|
||||
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly,
|
||||
costSnapshot, $"{deviceName} cost (monthly)", timestamp));
|
||||
costSnapshot, $"{deviceName} cost (monthly)", timestamp));
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
@@ -175,40 +185,43 @@ public sealed class PowerMonitorEntityService(
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up PowerMonitor entities");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames,
|
||||
CancellationToken cancellationToken = default)
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var entityIds = removedDeviceNames.SelectMany(GetDeviceCostEntityIds).ToList();
|
||||
|
||||
var tasks = entityIds.Select(async id =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.RemoveEntity(id).ConfigureAwait(false);
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.RemoveEntity(id).ConfigureAwait(false);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Entity removed: {EntityId}", id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to remove device entity: {EntityId}", id);
|
||||
}
|
||||
});
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Entity removed: {EntityId}", id);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to remove device entity: {EntityId}", id);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList()
|
||||
{
|
||||
return new List<PowerMonitorEntity>
|
||||
{
|
||||
new("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
||||
new PowerMonitorEntity("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
||||
{
|
||||
AdditionalConfig = new
|
||||
{
|
||||
@@ -221,7 +234,7 @@ public sealed class PowerMonitorEntityService(
|
||||
CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"),
|
||||
CreateCostEntity("powermonitor_total_cost_daily", "PowerMonitor total cost (daily)"),
|
||||
CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"),
|
||||
new("sensor", "powermonitor_other_power", "PowerMonitor other power")
|
||||
new PowerMonitorEntity("sensor", "powermonitor_other_power", "PowerMonitor other power")
|
||||
{
|
||||
AdditionalConfig = new
|
||||
{
|
||||
@@ -234,13 +247,13 @@ public sealed class PowerMonitorEntityService(
|
||||
CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"),
|
||||
CreateCostEntity("powermonitor_other_cost_daily", "PowerMonitor other cost (daily)"),
|
||||
CreateCostEntity("powermonitor_other_cost_monthly", "PowerMonitor other cost (monthly)"),
|
||||
new("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"),
|
||||
new("sensor", "powermonitor_status", "PowerMonitor status"),
|
||||
new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
|
||||
new PowerMonitorEntity("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"),
|
||||
new PowerMonitorEntity("sensor", "powermonitor_status", "PowerMonitor status"),
|
||||
new PowerMonitorEntity("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
|
||||
{
|
||||
AdditionalConfig = new { icon = "mdi:refresh" }
|
||||
},
|
||||
new("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
|
||||
new PowerMonitorEntity("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
|
||||
{
|
||||
AdditionalConfig = new { icon = "mdi:flash-alert" }
|
||||
}
|
||||
@@ -263,6 +276,7 @@ public sealed class PowerMonitorEntityService(
|
||||
internal static IEnumerable<PowerMonitorEntity> GetPowerDeviceEntitiesNames(PowerSensorInfo sensor)
|
||||
{
|
||||
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId);
|
||||
|
||||
return
|
||||
[
|
||||
CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"),
|
||||
@@ -287,76 +301,89 @@ public sealed class PowerMonitorEntityService(
|
||||
{
|
||||
var value = context.Calculation.TotalPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
|
||||
await SetEntityStateSafe(TotalPowerEntityId, value).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TotalPowerEntityId, new
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||
state_class = PowerMonitorConsts.MeasurementStateClass,
|
||||
friendly_name = "PowerMonitor total power",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||
state_class = PowerMonitorConsts.MeasurementStateClass,
|
||||
friendly_name = "PowerMonitor total power",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateOtherPowerAsync(PowerUpdateContext context, string timestamp)
|
||||
{
|
||||
var value = context.Calculation.SmoothedOtherPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
|
||||
await SetEntityStateSafe(OtherPowerEntityId, value).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(OtherPowerEntityId, new
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||
state_class = PowerMonitorConsts.MeasurementStateClass,
|
||||
friendly_name = "PowerMonitor other power",
|
||||
raw_power = context.Calculation.RawOtherPowerWatts,
|
||||
smoothed_power = context.Calculation.SmoothedOtherPowerWatts,
|
||||
data_quality = context.Calculation.DataQuality,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||
state_class = PowerMonitorConsts.MeasurementStateClass,
|
||||
friendly_name = "PowerMonitor other power",
|
||||
raw_power = context.Calculation.RawOtherPowerWatts,
|
||||
smoothed_power = context.Calculation.SmoothedOtherPowerWatts,
|
||||
data_quality = context.Calculation.DataQuality,
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateCostEntityAsync(string entityId, double costValue, CostSnapshot snapshot,
|
||||
string friendlyName, string timestamp)
|
||||
private async Task UpdateCostEntityAsync(string entityId,
|
||||
double costValue,
|
||||
CostSnapshot snapshot,
|
||||
string friendlyName,
|
||||
string timestamp)
|
||||
{
|
||||
var value = costValue.ToString("F4", CultureInfo.InvariantCulture);
|
||||
await SetEntityStateSafe(entityId, value).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(entityId, new
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.EurUnit,
|
||||
device_class = PowerMonitorConsts.MonetaryDeviceClass,
|
||||
state_class = PowerMonitorConsts.TotalStateClass,
|
||||
friendly_name = friendlyName,
|
||||
partial_window = snapshot.PartialWindow,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.EurUnit,
|
||||
device_class = PowerMonitorConsts.MonetaryDeviceClass,
|
||||
state_class = PowerMonitorConsts.TotalStateClass,
|
||||
friendly_name = friendlyName,
|
||||
partial_window = snapshot.PartialWindow,
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateAnomalyAsync(PowerUpdateContext context, string timestamp)
|
||||
{
|
||||
var state = context.IsAnomaly ? "on" : "off";
|
||||
await SetEntityStateSafe(AnomalyEntityId, state).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(AnomalyEntityId, new
|
||||
{
|
||||
friendly_name = "PowerMonitor anomaly",
|
||||
smoothed_watts = context.Calculation.SmoothedOtherPowerWatts,
|
||||
threshold = context.AnomalyThresholdWatts,
|
||||
duration_above = context.AnomalyDuration.TotalSeconds,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "PowerMonitor anomaly",
|
||||
smoothed_watts = context.Calculation.SmoothedOtherPowerWatts,
|
||||
threshold = context.AnomalyThresholdWatts,
|
||||
duration_above = context.AnomalyDuration.TotalSeconds,
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateStatusAsync(PowerUpdateContext context, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(StatusEntityId, context.SystemStatus).ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(StatusEntityId, new
|
||||
{
|
||||
friendly_name = "PowerMonitor status",
|
||||
tracked_sensors_count = context.TrackedSensorCount,
|
||||
degraded_sensors = context.DegradedSensors,
|
||||
price_source = context.PriceSource,
|
||||
current_price = context.CurrentNordPoolPrice,
|
||||
price_unit = context.PriceUnit,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "PowerMonitor status",
|
||||
tracked_sensors_count = context.TrackedSensorCount,
|
||||
degraded_sensors = context.DegradedSensors,
|
||||
price_source = context.PriceSource,
|
||||
current_price = context.CurrentNordPoolPrice,
|
||||
price_unit = context.PriceUnit,
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal async Task SetEntityStateSafe(string entityId, string state)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -10,6 +12,8 @@ using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -108,6 +112,7 @@ public sealed class PowerMonitorInit
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing PowerMonitor");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -129,17 +134,22 @@ public sealed class PowerMonitorInit
|
||||
if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId))
|
||||
{
|
||||
_logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var meter = new Entity(_haContext, _options.MainMeterEntityId);
|
||||
meter.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State) return;
|
||||
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
meter.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
@@ -150,31 +160,33 @@ public sealed class PowerMonitorInit
|
||||
private void SubscribeToRediscoverButton()
|
||||
{
|
||||
var button = new Entity(_haContext, "button.powermonitor_rediscover_sensors");
|
||||
|
||||
button.StateChanges()
|
||||
.Subscribe(change =>
|
||||
{
|
||||
_logger.LogInformation("Re-discovery button pressed, scanning for power sensors");
|
||||
_ = HandleRediscoveryAsync();
|
||||
});
|
||||
.Subscribe(change =>
|
||||
{
|
||||
_logger.LogInformation("Re-discovery button pressed, scanning for power sensors");
|
||||
_ = HandleRediscoveryAsync();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToLimitBreachDebugButton()
|
||||
{
|
||||
var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach");
|
||||
|
||||
button.StateChanges()
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
if (_enforcementService.IsLimitActive)
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed while active, resetting breach");
|
||||
_enforcementService.ResetLimitBreach();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed, triggering fake breach");
|
||||
_enforcementService.TriggerLimitBreach();
|
||||
}
|
||||
});
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
if (_enforcementService.IsLimitActive)
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed while active, resetting breach");
|
||||
_enforcementService.ResetLimitBreach();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Limit breach debug button pressed, triggering fake breach");
|
||||
_enforcementService.TriggerLimitBreach();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleRediscoveryAsync()
|
||||
@@ -193,18 +205,22 @@ public sealed class PowerMonitorInit
|
||||
if (added.Count > 0)
|
||||
{
|
||||
await _entityService.CreateDeviceEntitiesAsync(added);
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
|
||||
}
|
||||
}
|
||||
|
||||
if (removed.Count > 0) await RemoreDevicePriceEntities(removed);
|
||||
if (removed.Count > 0)
|
||||
{
|
||||
await RemoreDevicePriceEntities(removed);
|
||||
}
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)",
|
||||
newSensors.Count, added.Count, removed.Count);
|
||||
newSensors.Count, added.Count, removed.Count);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -229,11 +245,13 @@ public sealed class PowerMonitorInit
|
||||
try
|
||||
{
|
||||
var totalPower = ReadMainMeterPower();
|
||||
|
||||
if (totalPower is null)
|
||||
{
|
||||
_mainMeterConsecutiveFailures++;
|
||||
|
||||
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures,
|
||||
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -251,8 +269,9 @@ public sealed class PowerMonitorInit
|
||||
var now = _timeProvider.GetLocalNow();
|
||||
|
||||
var elapsedSeconds = _lastPollTimestamp.HasValue
|
||||
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
|
||||
: _options.PollIntervalSeconds;
|
||||
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
|
||||
: _options.PollIntervalSeconds;
|
||||
|
||||
_lastPollTimestamp = now;
|
||||
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
|
||||
@@ -261,18 +280,16 @@ public sealed class PowerMonitorInit
|
||||
|
||||
_anomalyStartTime = isAnomaly switch
|
||||
{
|
||||
true when _anomalyStartTime is null => now,
|
||||
false => null,
|
||||
_ => _anomalyStartTime
|
||||
true when _anomalyStartTime is null => now, false => null, _ => _anomalyStartTime
|
||||
};
|
||||
|
||||
var anomalyDuration = _anomalyStartTime.HasValue
|
||||
? now - _anomalyStartTime.Value
|
||||
: TimeSpan.Zero;
|
||||
? now - _anomalyStartTime.Value
|
||||
: TimeSpan.Zero;
|
||||
|
||||
var systemStatus = _mainMeterConsecutiveFailures >= PowerMonitorConsts.MainMeterMaxConsecutiveFailures
|
||||
? "warning"
|
||||
: "ok";
|
||||
? "warning"
|
||||
: "ok";
|
||||
|
||||
var context = new PowerUpdateContext
|
||||
{
|
||||
@@ -300,9 +317,9 @@ public sealed class PowerMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
||||
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
|
||||
effectivePrice);
|
||||
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
||||
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
|
||||
effectivePrice);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -318,10 +335,14 @@ public sealed class PowerMonitorInit
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
_logger.LogDebug("NordPool price entity unavailable, using last known price");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) return price;
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0)
|
||||
{
|
||||
return price;
|
||||
}
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
@@ -340,11 +361,13 @@ public sealed class PowerMonitorInit
|
||||
case (true, false):
|
||||
_notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts);
|
||||
_highPowerNotificationActive = true;
|
||||
|
||||
break;
|
||||
|
||||
case (false, true):
|
||||
_notificationService.DismissHighPowerNotification();
|
||||
_highPowerNotificationActive = false;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -352,11 +375,15 @@ public sealed class PowerMonitorInit
|
||||
private double? ReadMainMeterPower()
|
||||
{
|
||||
var state = _haContext.GetState(_options.MainMeterEntityId);
|
||||
if (state?.State is null or "unavailable" or "unknown") return null;
|
||||
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
|
||||
? value
|
||||
: null;
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
private (IReadOnlyDictionary<string, double> readings, List<string> degraded) ReadDeviceSensors()
|
||||
@@ -367,19 +394,21 @@ public sealed class PowerMonitorInit
|
||||
foreach (var sensor in _discoveryService.CurrentDeviceSensors)
|
||||
{
|
||||
var state = _haContext.GetState(sensor.EntityId);
|
||||
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
readings[sensor.EntityId] = 0;
|
||||
degraded.Add(sensor.EntityId);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
|
||||
{
|
||||
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit,
|
||||
StringComparison.OrdinalIgnoreCase)
|
||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||
: value;
|
||||
StringComparison.OrdinalIgnoreCase)
|
||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||
: value;
|
||||
|
||||
readings[sensor.EntityId] = powerWatts;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
using PowerMonitorManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public static class PowerMonitorServiceRegistration
|
||||
@@ -9,13 +13,13 @@ public static class PowerMonitorServiceRegistration
|
||||
public static IServiceCollection AddPowerMonitor(this IServiceCollection services)
|
||||
{
|
||||
services
|
||||
.AddNetDaemonApp<PowerMonitorInit>()
|
||||
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
|
||||
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
|
||||
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
|
||||
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
|
||||
.AddTransient<IPowerNotificationService, PowerNotificationService>()
|
||||
.AddTransient<IPowerLimitEnforcementService, PowerLimitEnforcementService>();
|
||||
.AddNetDaemonApp<PowerMonitorInit>()
|
||||
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
|
||||
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
|
||||
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
|
||||
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
|
||||
.AddTransient<IPowerNotificationService, PowerNotificationService>()
|
||||
.AddTransient<IPowerLimitEnforcementService, PowerLimitEnforcementService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NetDaemon.HassModel;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerNotificationService(
|
||||
@@ -18,28 +22,28 @@ public sealed class PowerNotificationService(
|
||||
var message = BuildHighPowerMessage(currentKw, thresholdKw);
|
||||
|
||||
haContext.CallService(
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = PowerMonitorConsts.HighPowerNotificationTitle,
|
||||
message,
|
||||
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
||||
});
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
{
|
||||
title = PowerMonitorConsts.HighPowerNotificationTitle,
|
||||
message,
|
||||
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
||||
});
|
||||
|
||||
logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)",
|
||||
currentKw, thresholdKw);
|
||||
currentKw, thresholdKw);
|
||||
}
|
||||
|
||||
public void DismissHighPowerNotification()
|
||||
{
|
||||
haContext.CallService(
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new
|
||||
{
|
||||
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
||||
});
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new
|
||||
{
|
||||
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
||||
});
|
||||
|
||||
logger.LogDebug("Dismissed high power usage notification");
|
||||
}
|
||||
@@ -47,9 +51,9 @@ public sealed class PowerNotificationService(
|
||||
private static string BuildHighPowerMessage(double currentKw, double thresholdKw)
|
||||
{
|
||||
return string.Format(
|
||||
CultureInfo.InvariantCulture,
|
||||
"Total home power usage is **{0:F2} kW**, which exceeds the threshold of **{1:F1} kW**.\n\nConsider turning off high-power appliances to reduce consumption.",
|
||||
currentKw,
|
||||
thresholdKw);
|
||||
CultureInfo.InvariantCulture,
|
||||
"Total home power usage is **{0:F2} kW**, which exceeds the threshold of **{1:F1} kW**.\n\nConsider turning off high-power appliances to reduce consumption.",
|
||||
currentKw,
|
||||
thresholdKw);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -9,6 +11,8 @@ using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
@@ -38,25 +42,25 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
var allEntities = _haContext.GetAllEntities();
|
||||
|
||||
var powerSensors = allEntities
|
||||
.Where(IsPowerSensor)
|
||||
.Where(e => !IsMainMeter(e.EntityId))
|
||||
.Where(e => !IsExcluded(e.EntityId))
|
||||
.Select(e => new PowerSensorInfo
|
||||
{
|
||||
EntityId = e.EntityId,
|
||||
FriendlyName = GetFriendlyName(e),
|
||||
DeviceName = ExtractDeviceName(e.EntityId),
|
||||
UnitOfMeasurement = GetUnitOfMeasurement(e)
|
||||
})
|
||||
.ToList();
|
||||
.Where(IsPowerSensor)
|
||||
.Where(e => !IsMainMeter(e.EntityId))
|
||||
.Where(e => !IsExcluded(e.EntityId))
|
||||
.Select(e => new PowerSensorInfo
|
||||
{
|
||||
EntityId = e.EntityId,
|
||||
FriendlyName = GetFriendlyName(e),
|
||||
DeviceName = ExtractDeviceName(e.EntityId),
|
||||
UnitOfMeasurement = GetUnitOfMeasurement(e)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
_currentDeviceSensors = powerSensors;
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
||||
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
||||
}
|
||||
|
||||
return powerSensors;
|
||||
@@ -64,10 +68,17 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
|
||||
internal static bool IsPowerSensor(Entity entity)
|
||||
{
|
||||
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var attributes = entity.EntityState?.AttributesJson;
|
||||
if (attributes is null) return false;
|
||||
|
||||
if (attributes is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var deviceClass = GetJsonStringProperty(attributes.Value, "device_class");
|
||||
var unit = GetJsonStringProperty(attributes.Value, "unit_of_measurement");
|
||||
@@ -90,38 +101,44 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
internal static string ExtractDeviceName(string entityId)
|
||||
{
|
||||
var withoutDomain = entityId.Contains('.')
|
||||
? entityId[(entityId.IndexOf('.') + 1)..]
|
||||
: entityId;
|
||||
? entityId[(entityId.IndexOf('.') + 1)..]
|
||||
: entityId;
|
||||
|
||||
return withoutDomain.EndsWith("_power", StringComparison.OrdinalIgnoreCase)
|
||||
? withoutDomain[..^"_power".Length]
|
||||
: withoutDomain;
|
||||
? withoutDomain[..^"_power".Length]
|
||||
: withoutDomain;
|
||||
}
|
||||
|
||||
private static string GetFriendlyName(Entity entity)
|
||||
{
|
||||
var name = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name");
|
||||
|
||||
return name ?? entity.EntityId;
|
||||
}
|
||||
|
||||
private static string GetUnitOfMeasurement(Entity entity)
|
||||
{
|
||||
var unit = GetJsonStringProperty(entity.EntityState?.AttributesJson, "unit_of_measurement");
|
||||
|
||||
return unit ?? PowerMonitorConsts.WattUnit;
|
||||
}
|
||||
|
||||
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||
{
|
||||
if (element is null) return null;
|
||||
if (element is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return element.Value.TryGetProperty(propertyName, out var value)
|
||||
? value.GetString()
|
||||
: null;
|
||||
? value.GetString()
|
||||
: null;
|
||||
}
|
||||
|
||||
internal static Regex GlobToRegex(string globPattern)
|
||||
{
|
||||
var regexPattern = "^" + Regex.Escape(globPattern).Replace("\\*", ".*") + "$";
|
||||
|
||||
return new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using HomeAssistant.Models;
|
||||
using NetDaemon.Extensions.MqttEntityManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Models;
|
||||
|
||||
public class PowerMonitorEntity : EntityCreateModel
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
@@ -8,6 +10,8 @@ using ShowerMonitor.Models.Enums;
|
||||
using ShowerMonitorManager;
|
||||
using ShowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace ShowerMonitor.Manager.Tests;
|
||||
|
||||
public class ExhaustFanControlServiceTests
|
||||
@@ -15,19 +19,19 @@ public class ExhaustFanControlServiceTests
|
||||
private const string FanEntityId = "switch.exhaust_fan";
|
||||
|
||||
private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions();
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider();
|
||||
|
||||
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 on", ShowerState.Active, "on", false },
|
||||
{ "active while fan reports uppercase on", ShowerState.Active, "ON", false },
|
||||
{ "active while fan is unavailable", ShowerState.Active, "unavailable", true },
|
||||
{ "active while fan state is unknown", ShowerState.Active, "unknown", true },
|
||||
{ "active while fan state is empty", ShowerState.Active, "", true },
|
||||
{ "active while fan state is empty", ShowerState.Active, string.Empty, true },
|
||||
{ "active while fan state is missing", ShowerState.Active, null, true },
|
||||
{ "suspected while fan is off", ShowerState.Suspected, "off", true },
|
||||
{ "suspected while fan is on", ShowerState.Suspected, "on", false },
|
||||
@@ -36,7 +40,7 @@ public class ExhaustFanControlServiceTests
|
||||
{ "completed does not turn the fan on", ShowerState.Completed, "off", false }
|
||||
};
|
||||
|
||||
public static TheoryData<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 },
|
||||
{ "one second before run-after duration", 10, 599, false },
|
||||
@@ -47,7 +51,7 @@ public class ExhaustFanControlServiceTests
|
||||
{ "long run-after keeps fan running", 30, 300, false }
|
||||
};
|
||||
|
||||
public static TheoryData<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 reports uppercase on", true, "ON", true },
|
||||
@@ -83,8 +87,10 @@ public class ExhaustFanControlServiceTests
|
||||
bool expectTurnOff)
|
||||
{
|
||||
SetupFanState("off");
|
||||
|
||||
var service = CreateService(ShowerMonitorTestData.CreateOptions(
|
||||
fanRunAfterShowerMinutes: runAfterMinutes));
|
||||
fanRunAfterShowerMinutes: runAfterMinutes));
|
||||
|
||||
var showerEnd = Now.AddMinutes(5);
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
@@ -252,8 +258,8 @@ public class ExhaustFanControlServiceTests
|
||||
private void SetupFanState(string? state)
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(x => x.GetState(_defaultOptions.ExhaustFanEntityId))
|
||||
.Returns(ShowerMonitorTestData.FanState(state));
|
||||
.Setup(x => x.GetState(_defaultOptions.ExhaustFanEntityId))
|
||||
.Returns(ShowerMonitorTestData.FanState(state));
|
||||
}
|
||||
|
||||
private void VerifySwitchCall(
|
||||
@@ -263,18 +269,15 @@ public class ExhaustFanControlServiceTests
|
||||
string? because = null)
|
||||
{
|
||||
var targets = _haContextMock.Invocations
|
||||
.Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService)
|
||||
&& (string?)invocation.Arguments[0] == "switch"
|
||||
&& (string?)invocation.Arguments[1] == service)
|
||||
.Select(invocation => (ServiceTarget?)invocation.Arguments[2])
|
||||
.ToList();
|
||||
.Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService) && (string?)invocation.Arguments[0] == "switch" && (string?)invocation.Arguments[1] == service)
|
||||
.Select(invocation => (ServiceTarget?)invocation.Arguments[2])
|
||||
.ToList();
|
||||
|
||||
targets.Should().HaveCount(expectedCount, because);
|
||||
targets.Should().OnlyContain(
|
||||
target => target != null
|
||||
&& target.EntityIds != null
|
||||
&& target.EntityIds.Count == 1
|
||||
&& target.EntityIds.Single() == expectedEntityId,
|
||||
because);
|
||||
|
||||
targets.Should()
|
||||
.OnlyContain(
|
||||
target => target != null && target.EntityIds != null && target.EntityIds.Count == 1 && target.EntityIds.Single() == expectedEntityId,
|
||||
because);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user