Compare commits

...

2 Commits

Author SHA1 Message Date
gitea_admin 635e9625ea Merge pull request 'Apply code formatting cleanup across the monitor projects' (#1) from fix-style into main
Reviewed-on: #1
2026-12-01 10:40:57 +00:00
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00
115 changed files with 3115 additions and 1959 deletions
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using System.Text.Json; using System.Text.Json;
using BatteryMonitor.Models; using BatteryMonitor.Models;
@@ -5,6 +7,8 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace BatteryMonitor.Manager.Tests; namespace BatteryMonitor.Manager.Tests;
/// <summary> /// <summary>
@@ -20,7 +24,7 @@ internal static class BatteryMonitorTestData
/// (threshold, state, expected) rows straddling the strict <c>level &lt; threshold</c> /// (threshold, state, expected) rows straddling the strict <c>level &lt; threshold</c>
/// boundary, including zero/negative thresholds and int min/max thresholds. /// boundary, including zero/negative thresholds and int min/max thresholds.
/// </summary> /// </summary>
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new() public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new TheoryData<int, string, bool>
{ {
{ 5, "4", true }, { 5, "4", true },
{ 5, "5", false }, { 5, "5", false },
@@ -59,7 +63,7 @@ internal static class BatteryMonitorTestData
"unknown", "unknown",
"UNAVAILABLE", "UNAVAILABLE",
"UNKNOWN", "UNKNOWN",
"", string.Empty,
" ", " ",
"\t", "\t",
"not_a_number", "not_a_number",
@@ -85,7 +89,9 @@ internal static class BatteryMonitorTestData
} }
/// <summary>A sensor with an arbitrary (or missing) device class.</summary> /// <summary>A sensor with an arbitrary (or missing) device class.</summary>
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, public static EntitySpec Sensor(string entityId,
string? deviceClass,
string? state,
string? friendlyName = DefaultFriendlyName) string? friendlyName = DefaultFriendlyName)
{ {
return new EntitySpec return new EntitySpec
@@ -101,9 +107,15 @@ internal static class BatteryMonitorTestData
{ {
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal); var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass; if (spec.DeviceClass is not null)
{
attributes["device_class"] = spec.DeviceClass;
}
if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName; if (spec.FriendlyName is not null)
{
attributes["friendly_name"] = spec.FriendlyName;
}
return new EntityState return new EntityState
{ {
@@ -122,7 +134,10 @@ internal static class BatteryMonitorTestData
foreach (var spec in entities) foreach (var spec in entities)
{ {
if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec)); if (spec.HasState)
{
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
}
entityList.Add(new Entity(haContextMock.Object, spec.EntityId)); entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
} }
@@ -202,7 +217,7 @@ internal static class BatteryMonitorTestData
data.Add("sensor.boiler_temp_battery", false); data.Add("sensor.boiler_temp_battery", false);
data.Add("sensor.aquarium_leak_sensor_battery", false); data.Add("sensor.aquarium_leak_sensor_battery", false);
data.Add("sensor.temperature", false); data.Add("sensor.temperature", false);
data.Add("", false); data.Add(string.Empty, false);
data.Add(" ", false); data.Add(" ", false);
return data; return data;
@@ -1,3 +1,5 @@
#region
using System.Text.Json; using System.Text.Json;
using BatteryMonitor.Models; using BatteryMonitor.Models;
using BatteryMonitorManager; using BatteryMonitorManager;
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests; namespace BatteryMonitor.Manager.Tests;
public class BatteryNotificationServiceTests public class BatteryNotificationServiceTests
{ {
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new(); private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new Mock<ILogger<BatteryNotificationService>>();
private BatteryNotificationService CreateSut() private BatteryNotificationService CreateSut()
{ {
@@ -65,6 +69,7 @@ public class BatteryNotificationServiceTests
It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<ServiceTarget?>(), It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Never); It.IsAny<object?>()), Times.Never);
_loggerMock.Invocations.Should().BeEmpty(); _loggerMock.Invocations.Should().BeEmpty();
} }
@@ -72,6 +77,7 @@ public class BatteryNotificationServiceTests
public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary() public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary()
{ {
object? payload = null; object? payload = null;
_haContextMock _haContextMock
.Setup(h => h.CallService( .Setup(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain, BatteryMonitorConsts.PersistentNotificationDomain,
@@ -81,6 +87,7 @@ public class BatteryNotificationServiceTests
.Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data); .Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data);
var sut = CreateSut(); var sut = CreateSut();
sut.NotifyLowBattery(CreateSensorInfos( sut.NotifyLowBattery(CreateSensorInfos(
("sensor.a", "Device A", 4), ("sensor.a", "Device A", 4),
("sensor.b", "Device B", 1))); ("sensor.b", "Device B", 1)));
@@ -101,6 +108,7 @@ public class BatteryNotificationServiceTests
public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount() public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount()
{ {
_loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true); _loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true);
var devices = CreateSensorInfos( var devices = CreateSensorInfos(
("sensor.a", "Device A", 2), ("sensor.a", "Device A", 2),
("sensor.b", "Device B", 3)); ("sensor.b", "Device B", 3));
@@ -110,7 +118,9 @@ public class BatteryNotificationServiceTests
var logInvocation = _loggerMock.Invocations var logInvocation = _loggerMock.Invocations
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log)) .Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
.Should().ContainSingle().Subject; .Should()
.ContainSingle()
.Subject;
logInvocation.Arguments[0].Should().Be(LogLevel.Information); logInvocation.Arguments[0].Should().Be(LogLevel.Information);
logInvocation.Arguments[2].Should().NotBeNull(); logInvocation.Arguments[2].Should().NotBeNull();
@@ -139,7 +149,10 @@ public class BatteryNotificationServiceTests
{ {
var sut = CreateSut(); var sut = CreateSut();
for (var i = 0; i < calls; i++) sut.DismissNotification(); for (var i = 0; i < calls; i++)
{
sut.DismissNotification();
}
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls)); VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never()); VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
@@ -219,7 +232,8 @@ public class BatteryNotificationServiceTests
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")] [InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
[InlineData("", 5, "- ****: 5%")] [InlineData("", 5, "- ****: 5%")]
[InlineData(" ", 4, "- ** **: 4%")] [InlineData(" ", 4, "- ** **: 4%")]
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel, public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName,
double batteryLevel,
string expectedLine) string expectedLine)
{ {
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel)); var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using BatteryMonitor.Models; using BatteryMonitor.Models;
using BatteryMonitorManager; using BatteryMonitorManager;
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests; namespace BatteryMonitor.Manager.Tests;
public class BatterySensorDiscoveryServiceTests public class BatterySensorDiscoveryServiceTests
{ {
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new(); private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
private BatterySensorDiscoveryService CreateSut() private BatterySensorDiscoveryService CreateSut()
{ {
@@ -137,7 +141,8 @@ public class BatterySensorDiscoveryServiceTests
[Theory] [Theory]
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))] [MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state, public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
string state,
bool expectedIncluded) bool expectedIncluded)
{ {
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery")); SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
@@ -147,7 +152,10 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(expectedIncluded ? 1 : 0); result.Should().HaveCount(expectedIncluded ? 1 : 0);
if (!expectedIncluded) return; if (!expectedIncluded)
{
return;
}
result[0].EntityId.Should().Be("sensor.boundary_battery"); result[0].EntityId.Should().Be("sensor.boundary_battery");
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture)); result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
@@ -250,7 +258,9 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(7); result.Should().HaveCount(7);
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i)); result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
result.Select(s => s.FriendlyName).Should()
result.Select(s => s.FriendlyName)
.Should()
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal)); .OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
} }
@@ -1,3 +1,5 @@
#region
using System.Reactive.Concurrency; using System.Reactive.Concurrency;
using BatteryMonitor.Models; using BatteryMonitor.Models;
using BatteryMonitorManager.Interface; using BatteryMonitorManager.Interface;
@@ -7,6 +9,8 @@ using Microsoft.Extensions.Options;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler; using NetDaemon.Extensions.Scheduler;
#endregion
namespace BatteryMonitorManager; namespace BatteryMonitorManager;
[NetDaemonApp] [NetDaemonApp]
@@ -64,6 +68,7 @@ public sealed class BatteryMonitorInit
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error initializing BatteryMonitor"); _logger.LogError(ex, "Error initializing BatteryMonitor");
throw; throw;
} }
} }
@@ -1,9 +1,13 @@
#region
using BatteryMonitorManager.Interface; using BatteryMonitorManager.Interface;
using BatteryMonitorManager.Models; using BatteryMonitorManager.Models;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
#endregion
namespace BatteryMonitorManager; namespace BatteryMonitorManager;
public static class BatteryMonitorServiceRegistration public static class BatteryMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class BatteryMonitorServiceRegistration
{ {
var options = configuration var options = configuration
.GetSection(BatteryMonitorOptions.SectionName) .GetSection(BatteryMonitorOptions.SectionName)
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions(); .Get<BatteryMonitorOptions>() ??
new BatteryMonitorOptions();
if (!options.Enabled) return services; if (!options.Enabled)
{
return services;
}
services services
.AddNetDaemonApp<BatteryMonitorInit>() .AddNetDaemonApp<BatteryMonitorInit>()
@@ -1,9 +1,13 @@
#region
using System.Text; using System.Text;
using BatteryMonitor.Models; using BatteryMonitor.Models;
using BatteryMonitorManager.Interface; using BatteryMonitorManager.Interface;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NetDaemon.HassModel; using NetDaemon.HassModel;
#endregion
namespace BatteryMonitorManager; namespace BatteryMonitorManager;
public sealed class BatteryNotificationService( public sealed class BatteryNotificationService(
@@ -12,7 +16,10 @@ public sealed class BatteryNotificationService(
{ {
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices) public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
{ {
if (lowBatteryDevices.Count == 0) return; if (lowBatteryDevices.Count == 0)
{
return;
}
var message = BuildNotificationMessage(lowBatteryDevices); var message = BuildNotificationMessage(lowBatteryDevices);
@@ -54,7 +61,9 @@ public sealed class BatteryNotificationService(
sb.AppendLine(); sb.AppendLine();
foreach (var device in devices.OrderBy(d => d.BatteryLevel)) foreach (var device in devices.OrderBy(d => d.BatteryLevel))
{
sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%"); sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%");
}
return sb.ToString().TrimEnd(); return sb.ToString().TrimEnd();
} }
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using System.Text.Json; using System.Text.Json;
using BatteryMonitor.Models; using BatteryMonitor.Models;
@@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace BatteryMonitorManager; namespace BatteryMonitorManager;
public sealed class BatterySensorDiscoveryService( public sealed class BatterySensorDiscoveryService(
@@ -79,10 +83,12 @@ public sealed class BatterySensorDiscoveryService(
return null; return null;
} }
if (batteryLevel >= thresholdPercent) return null; if (batteryLevel >= thresholdPercent)
{
return null;
}
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId;
?? entity.EntityId;
return new BatterySensorInfo return new BatterySensorInfo
{ {
@@ -94,7 +100,10 @@ public sealed class BatterySensorDiscoveryService(
private static string? GetJsonStringProperty(JsonElement? element, string propertyName) private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
{ {
if (element is null) return null; if (element is null)
{
return null;
}
return element.Value.TryGetProperty(propertyName, out var value) return element.Value.TryGetProperty(propertyName, out var value)
? value.GetString() ? value.GetString()
@@ -1,5 +1,9 @@
#region
using BatteryMonitor.Models; using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Interface; namespace BatteryMonitorManager.Interface;
public interface IBatteryNotificationService public interface IBatteryNotificationService
@@ -1,5 +1,9 @@
#region
using BatteryMonitor.Models; using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Interface; namespace BatteryMonitorManager.Interface;
public interface IBatterySensorDiscoveryService public interface IBatterySensorDiscoveryService
@@ -1,5 +1,9 @@
#region
using BatteryMonitor.Models; using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Models; namespace BatteryMonitorManager.Models;
public sealed class BatteryMonitorOptions public sealed class BatteryMonitorOptions
@@ -1,14 +1,18 @@
#region
using BoilerMonitor.Models.Enums; using BoilerMonitor.Models.Enums;
using BoilerMonitorManager; using BoilerMonitorManager;
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Moq; using Moq;
#endregion
namespace BoilerMonitor.Manager.Tests; namespace BoilerMonitor.Manager.Tests;
public class BoilerControlServiceTests public class BoilerControlServiceTests
{ {
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new(); private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
private BoilerControlService CreateSut() private BoilerControlService CreateSut()
{ {
@@ -34,7 +38,8 @@ public class BoilerControlServiceTests
bool budgetExhausted, bool budgetExhausted,
bool budgetOverride) bool budgetOverride)
{ {
var result = CreateSut().DetermineAction( var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride); isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
result.Should().Be(BoilerAction.NoChange); result.Should().Be(BoilerAction.NoChange);
@@ -57,7 +62,8 @@ public class BoilerControlServiceTests
[InlineData("0")] [InlineData("0")]
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState) public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
{ {
var result = CreateSut().DetermineAction( var result = CreateSut()
.DetermineAction(
true, false, switchState, true, false, switchState,
false, false); false, false);
@@ -75,7 +81,8 @@ public class BoilerControlServiceTests
string? switchState, string? switchState,
BoilerAction expectedAction) BoilerAction expectedAction)
{ {
var result = CreateSut().DetermineAction( var result = CreateSut()
.DetermineAction(
true, false, switchState, true, false, switchState,
true, true); true, true);
@@ -93,7 +100,8 @@ public class BoilerControlServiceTests
[InlineData("oN")] [InlineData("oN")]
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState) public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
{ {
var result = CreateSut().DetermineAction( var result = CreateSut()
.DetermineAction(
false, false, switchState, false, false, switchState,
false, false); false, false);
@@ -109,7 +117,8 @@ public class BoilerControlServiceTests
bool budgetExhausted, bool budgetExhausted,
bool budgetOverride) bool budgetOverride)
{ {
var result = CreateSut().DetermineAction( var result = CreateSut()
.DetermineAction(
true, waterReady, "on", true, waterReady, "on",
budgetExhausted, budgetOverride); budgetExhausted, budgetOverride);
@@ -124,7 +133,7 @@ public class BoilerControlServiceTests
/// Complete truth table for a boiler that is currently ON: it may only stay on when /// Complete truth table for a boiler that is currently ON: it may only stay on when
/// it is cheap, water is not ready and the budget is available (or overridden). /// it is cheap, water is not ready and the budget is available (or overridden).
/// </summary> /// </summary>
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new() public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
{ {
{ false, false, false, false, BoilerAction.TurnOff }, { false, false, false, false, BoilerAction.TurnOff },
{ false, false, false, true, BoilerAction.TurnOff }, { false, false, false, true, BoilerAction.TurnOff },
@@ -153,7 +162,8 @@ public class BoilerControlServiceTests
bool budgetOverride, bool budgetOverride,
BoilerAction expectedAction) BoilerAction expectedAction)
{ {
var result = CreateSut().DetermineAction( var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride); isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction); result.Should().Be(expectedAction);
@@ -163,7 +173,7 @@ public class BoilerControlServiceTests
/// Complete truth table for a boiler that is currently OFF: it may only turn on when /// Complete truth table for a boiler that is currently OFF: it may only turn on when
/// it is cheap, water is not ready and the budget is available (or overridden). /// it is cheap, water is not ready and the budget is available (or overridden).
/// </summary> /// </summary>
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new() public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
{ {
{ false, false, false, false, BoilerAction.NoChange }, { false, false, false, false, BoilerAction.NoChange },
{ false, false, false, true, BoilerAction.NoChange }, { false, false, false, true, BoilerAction.NoChange },
@@ -192,7 +202,8 @@ public class BoilerControlServiceTests
bool budgetOverride, bool budgetOverride,
BoilerAction expectedAction) BoilerAction expectedAction)
{ {
var result = CreateSut().DetermineAction( var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride); isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction); result.Should().Be(expectedAction);
@@ -1,5 +1,9 @@
#region
using FluentAssertions; using FluentAssertions;
#endregion
namespace BoilerMonitor.Manager.Tests; namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorConfigTests public class BoilerMonitorConfigTests
@@ -7,7 +11,7 @@ public class BoilerMonitorConfigTests
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId; private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId; private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new() public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new TheoryData<string, string?, string?, int?, double?, bool>
{ {
{ "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true }, { "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true },
{ "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true }, { "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true },
@@ -18,11 +22,11 @@ public class BoilerMonitorConfigTests
{ "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true }, { "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true },
{ "power entity id null", null, SwitchEntityId, 30, 5.0, false }, { "power entity id null", null, SwitchEntityId, 30, 5.0, false },
{ "power entity id empty", "", SwitchEntityId, 30, 5.0, false }, { "power entity id empty", string.Empty, SwitchEntityId, 30, 5.0, false },
{ "power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false }, { "power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false },
{ "power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false }, { "power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false },
{ "switch entity id null", PowerEntityId, null, 30, 5.0, false }, { "switch entity id null", PowerEntityId, null, 30, 5.0, false },
{ "switch entity id empty", PowerEntityId, "", 30, 5.0, false }, { "switch entity id empty", PowerEntityId, string.Empty, 30, 5.0, false },
{ "switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false }, { "switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false },
{ "both entity ids null", null, null, 30, 5.0, false }, { "both entity ids null", null, null, 30, 5.0, false },
@@ -1,3 +1,5 @@
#region
using System.Text.Json; using System.Text.Json;
using BoilerMonitorManager; using BoilerMonitorManager;
using FluentAssertions; using FluentAssertions;
@@ -8,6 +10,8 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts; using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitor.Manager.Tests; namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorEntityServiceTests public class BoilerMonitorEntityServiceTests
@@ -31,18 +35,21 @@ public class BoilerMonitorEntityServiceTests
AutoManagementEntityId AutoManagementEntityId
]; ];
private readonly Mock<IEntityManager> _entityManagerMock = new(); private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new(); private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
public BoilerMonitorEntityServiceTests() public BoilerMonitorEntityServiceTests()
{ {
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>())) _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())) _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
} }
@@ -71,6 +78,7 @@ public class BoilerMonitorEntityServiceTests
if (expectedRunTime is null) if (expectedRunTime is null)
{ {
result.Should().BeNull(); result.Should().BeNull();
return; return;
} }
@@ -93,6 +101,7 @@ public class BoilerMonitorEntityServiceTests
if (expectedSessionCount is null) if (expectedSessionCount is null)
{ {
result.Should().BeNull(); result.Should().BeNull();
return; return;
} }
@@ -151,6 +160,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp() public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp()
{ {
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30); var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30);
_haContextMock.SetupEntityState( _haContextMock.SetupEntityState(
WaterReadyEntityId, WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O"))); BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
@@ -164,6 +174,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp() public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
{ {
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero); var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
_haContextMock.SetupEntityState( _haContextMock.SetupEntityState(
WaterReadyEntityId, WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z")); BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
@@ -260,6 +271,7 @@ public class BoilerMonitorEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
Times.Exactly(5)); Times.Exactly(5));
} }
@@ -276,7 +288,8 @@ public class BoilerMonitorEntityServiceTests
double budgetPercentage, double budgetPercentage,
string expectedState) string expectedState)
{ {
await CreateSut().UpdateEntitiesAsync( await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage)); BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
_entityManagerMock.Verify( _entityManagerMock.Verify(
@@ -291,7 +304,8 @@ public class BoilerMonitorEntityServiceTests
[InlineData(3600, "3600")] [InlineData(3600, "3600")]
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState) public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState)
{ {
await CreateSut().UpdateEntitiesAsync( await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds))); BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once);
@@ -305,7 +319,8 @@ public class BoilerMonitorEntityServiceTests
[InlineData(86_400.0, "86400")] [InlineData(86_400.0, "86400")]
public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState) public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState)
{ {
await CreateSut().UpdateEntitiesAsync( await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds))); BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once);
@@ -315,12 +330,14 @@ public class BoilerMonitorEntityServiceTests
public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes() public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes()
{ {
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock _entityManagerMock
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>())) .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
.Callback<string, object>((_, attributes) => capturedAttributes = attributes) .Callback<string, object>((_, attributes) => capturedAttributes = attributes)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext( await CreateSut()
.UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(
waterReady: false, waterReady: false,
boilerSwitchState: null, boilerSwitchState: null,
boilerPowerWatts: 1234.5)); boilerPowerWatts: 1234.5));
@@ -338,12 +355,14 @@ public class BoilerMonitorEntityServiceTests
{ {
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15); var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15);
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock _entityManagerMock
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>())) .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
.Callback<string, object>((_, attributes) => capturedAttributes = attributes) .Callback<string, object>((_, attributes) => capturedAttributes = attributes)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
await CreateSut().UpdateEntitiesAsync( await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince)); BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince));
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!); var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
@@ -358,6 +377,7 @@ public class BoilerMonitorEntityServiceTests
public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce() public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce()
{ {
var createdEntityIds = new List<string?>(); var createdEntityIds = new List<string?>();
_entityManagerMock _entityManagerMock
.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>())) .Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
.Callback<EntityCreateModel>(entity => createdEntityIds.Add(entity.EntityId)) .Callback<EntityCreateModel>(entity => createdEntityIds.Add(entity.EntityId))
@@ -366,7 +386,9 @@ public class BoilerMonitorEntityServiceTests
await CreateSut().CreateEntitiesAsync(); await CreateSut().CreateEntitiesAsync();
createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems(); createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems();
createdEntityIds.Should().Contain(
createdEntityIds.Should()
.Contain(
[ [
ConfigPowerEntityId, ConfigPowerEntityId,
ConfigSwitchEntityId, ConfigSwitchEntityId,
@@ -391,16 +413,18 @@ public class BoilerMonitorEntityServiceTests
var act = () => CreateSut().CreateEntitiesAsync(); var act = () => CreateSut().CreateEntitiesAsync();
await act.Should().NotThrowAsync(); await act.Should().NotThrowAsync();
_entityManagerMock.Invocations _entityManagerMock.Invocations
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync)) .Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
.Should().Be(15); .Should()
.Be(15);
} }
#endregion #endregion
#region ResetEntitiesAsync #region ResetEntitiesAsync
public static TheoryData<string, string> ResetEntityStates => new() public static TheoryData<string, string> ResetEntityStates => new TheoryData<string, string>
{ {
{ StatusEntityId, StatusAwaitingConfiguration }, { StatusEntityId, StatusAwaitingConfiguration },
{ WaterReadyEntityId, "unknown" }, { WaterReadyEntityId, "unknown" },
@@ -422,6 +446,7 @@ public class BoilerMonitorEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(10)); _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(10));
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
Times.Exactly(5)); Times.Exactly(5));
} }
@@ -486,7 +511,9 @@ public class BoilerMonitorEntityServiceTests
await CreateSut().CleanupEntitiesAsync(); await CreateSut().CleanupEntitiesAsync();
foreach (var entityId in CleanableEntityIds) foreach (var entityId in CleanableEntityIds)
{
_entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once);
}
_entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never); _entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never);
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(CleanableEntityIds.Length)); _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(CleanableEntityIds.Length));
@@ -536,6 +563,7 @@ public class BoilerMonitorEntityServiceTests
{ {
var canceledToken = new CancellationToken(true); var canceledToken = new CancellationToken(true);
var sut = CreateSut(); var sut = CreateSut();
Func<Task> act = operation switch Func<Task> act = operation switch
{ {
CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken), CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken),
@@ -1,6 +1,10 @@
#region
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
using FluentAssertions; using FluentAssertions;
#endregion
namespace BoilerMonitor.Manager.Tests; namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorOptionsTests public class BoilerMonitorOptionsTests
@@ -1,3 +1,5 @@
#region
using System.Text.Json; using System.Text.Json;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
using Microsoft.Extensions.Time.Testing; using Microsoft.Extensions.Time.Testing;
@@ -6,6 +8,8 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts; using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitor.Manager.Tests; namespace BoilerMonitor.Manager.Tests;
/// <summary> /// <summary>
@@ -19,7 +23,7 @@ internal static class BoilerMonitorTestData
public const string SwitchEntityId = "switch.sonoff_1002230e32"; public const string SwitchEntityId = "switch.sonoff_1002230e32";
/// <summary>Fixed "now" (UTC) used by every time based test.</summary> /// <summary>Fixed "now" (UTC) used by every time based test.</summary>
public static readonly DateTimeOffset BaseTime = new(2026, 3, 31, 12, 0, 0, TimeSpan.Zero); public static readonly DateTimeOffset BaseTime = new DateTimeOffset(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null)
{ {
@@ -147,7 +151,7 @@ internal static class BoilerMonitorTestData
data.Add("1e9", TimeSpan.FromSeconds(1e9)); data.Add("1e9", TimeSpan.FromSeconds(1e9));
data.Add(null, null); data.Add(null, null);
data.Add("", null); data.Add(string.Empty, null);
data.Add(" ", null); data.Add(" ", null);
data.Add("\t", null); data.Add("\t", null);
data.Add("unavailable", null); data.Add("unavailable", null);
@@ -159,6 +163,7 @@ internal static class BoilerMonitorTestData
data.Add("1e308", null); data.Add("1e308", null);
data.Add("-1", null); data.Add("-1", null);
data.Add("-0.001", null); data.Add("-0.001", null);
return data; return data;
} }
@@ -175,7 +180,7 @@ internal static class BoilerMonitorTestData
data.Add("2147483647", int.MaxValue); data.Add("2147483647", int.MaxValue);
data.Add(null, null); data.Add(null, null);
data.Add("", null); data.Add(string.Empty, null);
data.Add(" ", null); data.Add(" ", null);
data.Add("\t", null); data.Add("\t", null);
data.Add("unavailable", null); data.Add("unavailable", null);
@@ -185,6 +190,7 @@ internal static class BoilerMonitorTestData
data.Add("-1", null); data.Add("-1", null);
data.Add("2147483648", null); data.Add("2147483648", null);
data.Add("1e3", null); data.Add("1e3", null);
return data; return data;
} }
@@ -204,6 +210,7 @@ internal static class BoilerMonitorTestData
data.Add("actively heating", 2_150.0, false); data.Add("actively heating", 2_150.0, false);
data.Add("maximum", double.MaxValue, false); data.Add("maximum", double.MaxValue, false);
data.Add("not-a-number", double.NaN, true); data.Add("not-a-number", double.NaN, true);
return data; return data;
} }
@@ -222,6 +229,7 @@ internal static class BoilerMonitorTestData
data.Add(TimeSpan.FromHours(25)); data.Add(TimeSpan.FromHours(25));
data.Add(TimeSpan.FromHours(48)); data.Add(TimeSpan.FromHours(48));
data.Add(TimeSpan.FromHours(168)); data.Add(TimeSpan.FromHours(168));
return data; return data;
} }
@@ -251,6 +259,7 @@ internal static class BoilerMonitorTestData
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)), new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
true true
); );
data.Add( data.Add(
"DST spring-forward, previous UTC day", "DST spring-forward, previous UTC day",
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
@@ -273,6 +282,7 @@ internal static class BoilerMonitorTestData
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero), new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
false false
); );
return data; return data;
} }
@@ -1,3 +1,5 @@
#region
using BoilerMonitor.Models; using BoilerMonitor.Models;
using BoilerMonitorManager; using BoilerMonitorManager;
using FluentAssertions; using FluentAssertions;
@@ -5,6 +7,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing; using Microsoft.Extensions.Time.Testing;
using Moq; using Moq;
#endregion
namespace BoilerMonitor.Manager.Tests; namespace BoilerMonitor.Manager.Tests;
public class WaterReadyServiceTests public class WaterReadyServiceTests
@@ -13,7 +17,7 @@ public class WaterReadyServiceTests
private const double HighPowerWatts = 2150.0; private const double HighPowerWatts = 2150.0;
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired; private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new(); private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new Mock<ILogger<WaterReadyService>>();
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider(); private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
private WaterReadyService CreateSut() private WaterReadyService CreateSut()
@@ -25,6 +29,7 @@ public class WaterReadyServiceTests
{ {
var sut = CreateSut(); var sut = CreateSut();
sut.RecordHeatingObserved(); sut.RecordHeatingObserved();
return sut; return sut;
} }
@@ -36,7 +41,11 @@ public class WaterReadyServiceTests
double heatingThresholdWatts = Threshold) double heatingThresholdWatts = Threshold)
{ {
var result = false; var result = false;
for (var i = 0; i < count; i++) result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
for (var i = 0; i < count; i++)
{
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
}
return result; return result;
} }
@@ -119,7 +128,9 @@ public class WaterReadyServiceTests
sut.ResetCooldown(); sut.ResetCooldown();
FeedReadings(sut, RequiredReadings).Should().BeTrue( FeedReadings(sut, RequiredReadings)
.Should()
.BeTrue(
"ResetCooldown clears the cooldown and counter, not the heating observation"); "ResetCooldown clears the cooldown and counter, not the heating observation");
} }
@@ -261,7 +272,8 @@ public class WaterReadyServiceTests
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts); var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts);
result.Should().Be( result.Should()
.Be(
expectedBelowThreshold, expectedBelowThreshold,
$"{scenario}: readings below {Threshold}W are counted as 'not heating'"); $"{scenario}: readings below {Threshold}W are counted as 'not heating'");
} }
@@ -320,8 +332,12 @@ public class WaterReadyServiceTests
_timeProvider.Advance(elapsed); _timeProvider.Advance(elapsed);
sut.IsInCooldown.Should().BeTrue(); sut.IsInCooldown.Should().BeTrue();
sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue(
sut.IsWaterReady("off", 0.0, Threshold)
.Should()
.BeTrue(
"cooldown only clears via explicit ResetCooldown, not by elapsed time"); "cooldown only clears via explicit ResetCooldown, not by elapsed time");
sut.WaterReadySince.Should().Be(triggeredAt); sut.WaterReadySince.Should().Be(triggeredAt);
} }
+10 -1
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using BoilerMonitor.Models; using BoilerMonitor.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -5,6 +7,8 @@ using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts; using static BoilerMonitor.Models.BoilerMonitorConsts;
using static NordPool.Models.NordPoolConsts; using static NordPool.Models.NordPoolConsts;
#endregion
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
@@ -14,15 +18,20 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
public BoilerConfig ReadConfig() public BoilerConfig ReadConfig()
{ {
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State; var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
? dh ? dh
: DefaultDailyHours; : DefaultDailyHours;
var intervalCount = (int)(dailyHours * IntervalsPerHour); var intervalCount = (int)(dailyHours * IntervalsPerHour);
if (intervalCount <= 0) intervalCount = IntervalsPerHour; if (intervalCount <= 0)
{
intervalCount = IntervalsPerHour;
}
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State; var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
var priceCap = var priceCap =
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
? pc ? pc
@@ -1,7 +1,11 @@
#region
using BoilerMonitor.Models.Enums; using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface; using BoilerMonitorManager.Interface;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
#endregion
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
@@ -58,7 +62,10 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted) private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
{ {
if (waterReady) return "water is already ready"; if (waterReady)
{
return "water is already ready";
}
return effectiveBudgetExhausted return effectiveBudgetExhausted
? "daily budget is exhausted" ? "daily budget is exhausted"
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using System.Text.Json; using System.Text.Json;
using BoilerMonitor.Models; using BoilerMonitor.Models;
@@ -9,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts; using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
public sealed class BoilerMonitorEntityService( public sealed class BoilerMonitorEntityService(
@@ -77,7 +81,8 @@ public sealed class BoilerMonitorEntityService(
ResetSessionCountAsync(), ResetSessionCountAsync(),
ResetBudgetOverrideAsync(), ResetBudgetOverrideAsync(),
ResetAutoManagementAsync() ResetAutoManagementAsync()
).ConfigureAwait(false); )
.ConfigureAwait(false);
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults"); logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
} }
@@ -118,6 +123,7 @@ public sealed class BoilerMonitorEntityService(
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Error cleaning up BoilerMonitor entities"); logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
throw; throw;
} }
} }
@@ -131,7 +137,8 @@ public sealed class BoilerMonitorEntityService(
await Task.WhenAll( await Task.WhenAll(
ResetStatusAsync(), ResetStatusAsync(),
ResetWaterReadyAsync() ResetWaterReadyAsync()
).ConfigureAwait(false); )
.ConfigureAwait(false);
} }
public PersistedBoilerState? ReadPersistedState() public PersistedBoilerState? ReadPersistedState()
@@ -177,6 +184,7 @@ public sealed class BoilerMonitorEntityService(
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities"); logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
return null; return null;
} }
} }
@@ -191,9 +199,16 @@ public sealed class BoilerMonitorEntityService(
try try
{ {
var entity = haContext.GetState(WaterReadyEntityId); var entity = haContext.GetState(WaterReadyEntityId);
if (entity?.Attributes is not IDictionary<string, object> attributes) return null;
if (!attributes.TryGetValue("cooldown_since", out var value)) return null; if (entity?.Attributes is not IDictionary<string, object> attributes)
{
return null;
}
if (!attributes.TryGetValue("cooldown_since", out var value))
{
return null;
}
var stringValue = value switch var stringValue = value switch
{ {
@@ -237,10 +252,7 @@ public sealed class BoilerMonitorEntityService(
private static bool TryParseEntitySeconds(string? state, out double seconds) private static bool TryParseEntitySeconds(string? state, out double seconds)
{ {
seconds = 0; seconds = 0;
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
&& state is not ("unavailable" or "unknown")
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
&& seconds >= 0;
return tryParseEntitySeconds; return tryParseEntitySeconds;
} }
@@ -248,10 +260,7 @@ public sealed class BoilerMonitorEntityService(
private static bool TryParseEntityInt(string? state, out int value) private static bool TryParseEntityInt(string? state, out int value)
{ {
value = 0; value = 0;
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
&& state is not ("unavailable" or "unknown")
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
&& value >= 0;
return tryParseEntityInt; return tryParseEntityInt;
} }
@@ -362,6 +371,7 @@ public sealed class BoilerMonitorEntityService(
private async Task ResetWaterReadyAsync() private async Task ResetWaterReadyAsync()
{ {
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false); await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(WaterReadyEntityId, new await SetEntityAttributesSafe(WaterReadyEntityId, new
{ {
boiler_switch_state = "unknown", boiler_switch_state = "unknown",
@@ -369,7 +379,8 @@ public sealed class BoilerMonitorEntityService(
power_threshold_watts = DefaultHeatingPowerThresholdWatts, power_threshold_watts = DefaultHeatingPowerThresholdWatts,
friendly_name = "Boiler water ready", friendly_name = "Boiler water ready",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetSkipPriceCapAsync() private async Task ResetSkipPriceCapAsync()
@@ -380,35 +391,41 @@ public sealed class BoilerMonitorEntityService(
private async Task ResetTodayRuntimeAsync() private async Task ResetTodayRuntimeAsync()
{ {
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false); await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayRuntimeEntityId, new await SetEntityAttributesSafe(TodayRuntimeEntityId, new
{ {
formatted = "0h 0m", formatted = "0h 0m",
friendly_name = "Today runtime", friendly_name = "Today runtime",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetRemainingTimeAsync() private async Task ResetRemainingTimeAsync()
{ {
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false); await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(RemainingTimeEntityId, new await SetEntityAttributesSafe(RemainingTimeEntityId, new
{ {
formatted = "0h 0m", formatted = "0h 0m",
budget_hours = 0.0, budget_hours = 0.0,
friendly_name = "Remaining budget time", friendly_name = "Remaining budget time",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetBudgetPercentageAsync() private async Task ResetBudgetPercentageAsync()
{ {
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false); await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(BudgetPercentageEntityId, new await SetEntityAttributesSafe(BudgetPercentageEntityId, new
{ {
unit_of_measurement = "%", unit_of_measurement = "%",
friendly_name = "Budget usage", friendly_name = "Budget usage",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetBudgetExhaustedAsync() private async Task ResetBudgetExhaustedAsync()
@@ -419,11 +436,13 @@ public sealed class BoilerMonitorEntityService(
private async Task ResetSessionCountAsync() private async Task ResetSessionCountAsync()
{ {
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false); await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(SessionCountEntityId, new await SetEntityAttributesSafe(SessionCountEntityId, new
{ {
friendly_name = "Heating sessions today", friendly_name = "Heating sessions today",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetBudgetOverrideAsync() private async Task ResetBudgetOverrideAsync()
@@ -439,6 +458,7 @@ public sealed class BoilerMonitorEntityService(
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp) private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
{ {
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false); await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
await SetEntityAttributesSafe(WaterReadyEntityId, new await SetEntityAttributesSafe(WaterReadyEntityId, new
{ {
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown", boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
@@ -446,47 +466,60 @@ public sealed class BoilerMonitorEntityService(
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture), cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
friendly_name = "Boiler water ready", friendly_name = "Boiler water ready",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp) private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
{ {
await SetEntityStateSafe(TodayRuntimeEntityId, await SetEntityStateSafe(TodayRuntimeEntityId,
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(TodayRuntimeEntityId, new await SetEntityAttributesSafe(TodayRuntimeEntityId, new
{ {
formatted, formatted,
friendly_name = "Today runtime", friendly_name = "Today runtime",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
string formatted,
double budgetHours,
string timestamp) string timestamp)
{ {
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds); var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)) await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false); .ConfigureAwait(false);
await SetEntityAttributesSafe(RemainingTimeEntityId, new await SetEntityAttributesSafe(RemainingTimeEntityId, new
{ {
formatted, formatted,
budget_hours = budgetHours, budget_hours = budgetHours,
friendly_name = "Remaining budget time", friendly_name = "Remaining budget time",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp) private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
{ {
var clampedPercentage = Math.Clamp(percentage, 0, 100); var clampedPercentage = Math.Clamp(percentage, 0, 100);
await SetEntityStateSafe(BudgetPercentageEntityId, await SetEntityStateSafe(BudgetPercentageEntityId,
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(BudgetPercentageEntityId, new await SetEntityAttributesSafe(BudgetPercentageEntityId, new
{ {
unit_of_measurement = "%", unit_of_measurement = "%",
friendly_name = "Budget usage", friendly_name = "Budget usage",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateBudgetExhaustedAsync(bool exhausted) private async Task UpdateBudgetExhaustedAsync(bool exhausted)
@@ -498,11 +531,13 @@ public sealed class BoilerMonitorEntityService(
{ {
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)) await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false); .ConfigureAwait(false);
await SetEntityAttributesSafe(SessionCountEntityId, new await SetEntityAttributesSafe(SessionCountEntityId, new
{ {
friendly_name = "Heating sessions today", friendly_name = "Heating sessions today",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task SetEntityStateSafe(string entityId, string state) private async Task SetEntityStateSafe(string entityId, string state)
@@ -510,6 +545,7 @@ public sealed class BoilerMonitorEntityService(
try try
{ {
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false); await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug)) if (logger.IsEnabled(LogLevel.Debug))
{ {
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state); logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
@@ -526,6 +562,7 @@ public sealed class BoilerMonitorEntityService(
try try
{ {
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false); await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug)) if (logger.IsEnabled(LogLevel.Debug))
{ {
logger.LogDebug("Successfully set attributes for {EntityId}", entityId); logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
+74 -18
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using System.Reactive.Concurrency; using System.Reactive.Concurrency;
using System.Text.Json; using System.Text.Json;
@@ -13,6 +15,8 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts; using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
[NetDaemonApp] [NetDaemonApp]
@@ -83,7 +87,10 @@ public sealed class BoilerMonitorInit
_options = options.Value; _options = options.Value;
_timeProvider = timeProvider; _timeProvider = timeProvider;
if (startBackgroundScheduling) _ = InitializeAndScheduleAsync(); if (startBackgroundScheduling)
{
_ = InitializeAndScheduleAsync();
}
} }
private async Task InitializeAndScheduleAsync() private async Task InitializeAndScheduleAsync()
@@ -130,9 +137,13 @@ public sealed class BoilerMonitorInit
{ {
_tracker.RestoreFromSnapshot(); _tracker.RestoreFromSnapshot();
if (persistedCooldown.HasValue) _waterReadyService.RestoreCooldownState(persistedCooldown.Value); if (persistedCooldown.HasValue)
{
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
}
await _entityService.ResetTransientEntitiesAsync(); await _entityService.ResetTransientEntitiesAsync();
if (_logger.IsEnabled(LogLevel.Information)) if (_logger.IsEnabled(LogLevel.Information))
{ {
_logger.LogInformation( _logger.LogInformation(
@@ -156,6 +167,7 @@ public sealed class BoilerMonitorInit
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error initializing BoilerMonitor"); _logger.LogError(ex, "Error initializing BoilerMonitor");
throw; throw;
} }
} }
@@ -204,13 +216,18 @@ public sealed class BoilerMonitorInit
try try
{ {
var switchState = _haContext.GetState(SkipPriceCapEntityId); var switchState = _haContext.GetState(SkipPriceCapEntityId);
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return;
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
return;
}
_haContext.CallService("notify", "mobile_app_marius_phone", null, new _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.", message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
title = "Boiler reminder" title = "Boiler reminder"
}); });
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
} }
catch (Exception ex) catch (Exception ex)
@@ -223,10 +240,14 @@ public sealed class BoilerMonitorInit
private void SubscribeToSkipPriceCapChanges() private void SubscribeToSkipPriceCapChanges()
{ {
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId); var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
skipPriceCapSwitch.StateChanges() skipPriceCapSwitch.StateChanges()
.Subscribe(e => .Subscribe(e =>
{ {
if (e.Old?.State == e.New?.State) return; if (e.Old?.State == e.New?.State)
{
return;
}
_logger.LogInformation("Skip price cap switch changed, triggering poll"); _logger.LogInformation("Skip price cap switch changed, triggering poll");
_ = PollAndUpdateAsync(); _ = PollAndUpdateAsync();
@@ -236,10 +257,14 @@ public sealed class BoilerMonitorInit
private void SubscribeToAutoManagementChanges() private void SubscribeToAutoManagementChanges()
{ {
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId); var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
autoManagementSwitch.StateChanges() autoManagementSwitch.StateChanges()
.Subscribe(e => .Subscribe(e =>
{ {
if (e.Old?.State == e.New?.State) return; if (e.Old?.State == e.New?.State)
{
return;
}
_logger.LogInformation("Automatic boiler control switch changed, triggering poll"); _logger.LogInformation("Automatic boiler control switch changed, triggering poll");
_ = PollAndUpdateAsync(); _ = PollAndUpdateAsync();
@@ -249,12 +274,19 @@ public sealed class BoilerMonitorInit
private void SubscribeToShowerState() private void SubscribeToShowerState()
{ {
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId); var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
showerStateSensor.StateChanges() showerStateSensor.StateChanges()
.Subscribe(e => .Subscribe(e =>
{ {
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) return; if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (!_waterReadyService.IsInCooldown) return; if (!_waterReadyService.IsInCooldown)
{
return;
}
_logger.LogInformation("Shower detected as active, resetting water ready cooldown"); _logger.LogInformation("Shower detected as active, resetting water ready cooldown");
_waterReadyService.ResetCooldown(); _waterReadyService.ResetCooldown();
@@ -264,6 +296,7 @@ public sealed class BoilerMonitorInit
private void SubscribeToCleanupButton() private void SubscribeToCleanupButton()
{ {
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
cleanupButton.StateChanges() cleanupButton.StateChanges()
.Subscribe(_ => .Subscribe(_ =>
{ {
@@ -359,6 +392,7 @@ public sealed class BoilerMonitorInit
if (_cleanedUp) if (_cleanedUp)
{ {
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll"); _logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
return; return;
} }
@@ -369,6 +403,7 @@ public sealed class BoilerMonitorInit
if (!config.IsFullyConfigured) if (!config.IsFullyConfigured)
{ {
await _entityService.SetStatusAsync(StatusAwaitingConfiguration); await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
_logger.LogWarning( _logger.LogWarning(
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration", "BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
config.BoilerPowerEntityId, config.BoilerSwitchEntityId, config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
@@ -379,11 +414,16 @@ public sealed class BoilerMonitorInit
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!); var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State; var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
var isHeating = boilerPowerWatts.HasValue && var isHeating = boilerPowerWatts.HasValue &&
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value; boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
_tracker.RecordPollResult(); _tracker.RecordPollResult();
if (isHeating) _waterReadyService.RecordHeatingObserved(); if (isHeating)
{
_waterReadyService.RecordHeatingObserved();
}
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
@@ -406,6 +446,7 @@ public sealed class BoilerMonitorInit
message = "Hot water is ready.", message = "Hot water is ready.",
title = "Boiler" title = "Boiler"
}); });
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow(); _lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
_logger.LogInformation("Water ready notification sent"); _logger.LogInformation("Water ready notification sent");
} }
@@ -416,7 +457,10 @@ public sealed class BoilerMonitorInit
var budgetTimeSpan = TimeSpan.FromHours(dailyHours); var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime; var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
if (remainingTime < TimeSpan.Zero) remainingTime = TimeSpan.Zero; if (remainingTime < TimeSpan.Zero)
{
remainingTime = TimeSpan.Zero;
}
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0 ? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
@@ -434,6 +478,7 @@ public sealed class BoilerMonitorInit
budgetOverride); budgetOverride);
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State; var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
var autoManagementEnabled = var autoManagementEnabled =
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase); !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
@@ -485,12 +530,17 @@ public sealed class BoilerMonitorInit
case BoilerAction.TurnOn: case BoilerAction.TurnOn:
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId)); _haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
_waterReadyService.NotifyTurnedOn(); _waterReadyService.NotifyTurnedOn();
break; break;
case BoilerAction.TurnOff: case BoilerAction.TurnOff:
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId)); _haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
break; break;
case BoilerAction.NoChange: case BoilerAction.NoChange:
break; break;
default: default:
throw new ArgumentOutOfRangeException(nameof(action), action, null); throw new ArgumentOutOfRangeException(nameof(action), action, null);
} }
@@ -504,9 +554,7 @@ public sealed class BoilerMonitorInit
int? pollInterval = null; int? pollInterval = null;
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State; var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
if (!string.IsNullOrWhiteSpace(pollIntervalState) if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
&& pollIntervalValue > 0)
{ {
pollInterval = (int)pollIntervalValue; pollInterval = (int)pollIntervalValue;
} }
@@ -514,9 +562,7 @@ public sealed class BoilerMonitorInit
double? heatingThreshold = null; double? heatingThreshold = null;
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State; var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
if (!string.IsNullOrWhiteSpace(thresholdState) if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
&& thresholdValue > 0)
{ {
heatingThreshold = thresholdValue; heatingThreshold = thresholdValue;
} }
@@ -534,14 +580,20 @@ public sealed class BoilerMonitorInit
{ {
var state = _haContext.GetState(entityId); var state = _haContext.GetState(entityId);
if (state?.State is null or "unavailable" or "unknown") return null; if (state?.State is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
} }
private static bool ReadAttributeBool(EntityState? entityState, string attributeName) private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
{ {
if (entityState?.Attributes is not IDictionary<string, object> attributes) return false; if (entityState?.Attributes is not IDictionary<string, object> attributes)
{
return false;
}
try try
{ {
@@ -569,9 +621,13 @@ public sealed class BoilerMonitorInit
private bool IsWithinNotificationCooldown() private bool IsWithinNotificationCooldown()
{ {
if (_lastWaterReadyNotificationSentAt is null) return false; if (_lastWaterReadyNotificationSentAt is null)
{
return false;
}
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value; var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
return elapsed < WaterReadyNotificationCooldown; return elapsed < WaterReadyNotificationCooldown;
} }
} }
@@ -1,9 +1,13 @@
#region
using BoilerMonitorManager.Interface; using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
#endregion
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
public static class BoilerMonitorServiceRegistration public static class BoilerMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class BoilerMonitorServiceRegistration
{ {
var options = configuration var options = configuration
.GetSection(BoilerMonitorOptions.SectionName) .GetSection(BoilerMonitorOptions.SectionName)
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions(); .Get<BoilerMonitorOptions>() ??
new BoilerMonitorOptions();
if (!options.Enabled) return services; if (!options.Enabled)
{
return services;
}
services services
.AddNetDaemonApp<BoilerMonitorInit>() .AddNetDaemonApp<BoilerMonitorInit>()
@@ -1,6 +1,10 @@
#region
using BoilerMonitorManager.Interface; using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
public class BoilerRunTimeTracker : IBoilerRunTimeTracker public class BoilerRunTimeTracker : IBoilerRunTimeTracker
@@ -1,5 +1,9 @@
#region
using BoilerMonitor.Models.Enums; using BoilerMonitor.Models.Enums;
#endregion
namespace BoilerMonitorManager.Interface; namespace BoilerMonitorManager.Interface;
public interface IBoilerControlService public interface IBoilerControlService
@@ -1,5 +1,9 @@
#region
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager.Interface; namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorEntityService public interface IBoilerMonitorEntityService
@@ -1,5 +1,9 @@
#region
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager.Interface; namespace BoilerMonitorManager.Interface;
public interface IBoilerRunTimeTracker public interface IBoilerRunTimeTracker
@@ -7,8 +7,7 @@ public record BoilerMonitorConfig
public int? PollIntervalSeconds { get; init; } public int? PollIntervalSeconds { get; init; }
public double? HeatingPowerThresholdWatts { get; init; } public double? HeatingPowerThresholdWatts { get; init; }
public bool IsFullyConfigured => public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
!string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) && !string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
PollIntervalSeconds is > 0 && PollIntervalSeconds is > 0 &&
HeatingPowerThresholdWatts is > 0; HeatingPowerThresholdWatts is > 0;
+20 -4
View File
@@ -1,13 +1,17 @@
#region
using BoilerMonitor.Models; using BoilerMonitor.Models;
using BoilerMonitorManager.Interface; using BoilerMonitorManager.Interface;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
#endregion
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
{ {
private const string SwitchOnState = "on"; private const string SwitchOnState = "on";
private readonly Lock _lock = new(); private readonly Lock _lock = new Lock();
private int _consecutiveBelowThresholdCount; private int _consecutiveBelowThresholdCount;
private bool _hasObservedHeating; private bool _hasObservedHeating;
private DateTimeOffset? _waterReadySince; private DateTimeOffset? _waterReadySince;
@@ -50,9 +54,15 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
} }
} }
if (switchState is null || powerWatts is null) return false; if (switchState is null || powerWatts is null)
{
return false;
}
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
return false;
}
lock (_lock) lock (_lock)
{ {
@@ -70,6 +80,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (powerWatts.Value >= heatingThresholdWatts) if (powerWatts.Value >= heatingThresholdWatts)
{ {
_consecutiveBelowThresholdCount = 0; _consecutiveBelowThresholdCount = 0;
return false; return false;
} }
@@ -117,7 +128,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{ {
lock (_lock) lock (_lock)
{ {
if (_hasObservedHeating) return; if (_hasObservedHeating)
{
return;
}
_hasObservedHeating = true; _hasObservedHeating = true;
} }
@@ -141,6 +155,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
lock (_lock) lock (_lock)
{ {
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero); var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
if (waterReadySince < todayMidnightUtc) if (waterReadySince < todayMidnightUtc)
{ {
if (logger.IsEnabled(LogLevel.Information)) if (logger.IsEnabled(LogLevel.Information))
@@ -153,6 +168,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
} }
_waterReadySince = waterReadySince; _waterReadySince = waterReadySince;
if (logger.IsEnabled(LogLevel.Information)) if (logger.IsEnabled(LogLevel.Information))
{ {
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince); logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
@@ -1,6 +1,10 @@
#region
using HomeAssistant.Models; using HomeAssistant.Models;
using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace BoilerMonitor.Models; namespace BoilerMonitor.Models;
public class BoilerMonitorEntity : EntityCreateModel public class BoilerMonitorEntity : EntityCreateModel
+8 -1
View File
@@ -1,10 +1,14 @@
using HomeAssistant.Entities.Interfaces; #region
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models; using HomeAssistant.Models;
using HomeAssistantGenerated; using HomeAssistantGenerated;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel; using NetDaemon.HassModel;
#endregion
namespace HomeAssistant.Entities; namespace HomeAssistant.Entities;
public class EntityManager( public class EntityManager(
@@ -53,12 +57,14 @@ public class EntityManager(
var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix); var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix);
foreach (var suffix in CleanupTopicSuffixes) foreach (var suffix in CleanupTopicSuffixes)
{
haContext.CallService("mqtt", "publish", null, new MqttPublishParameters haContext.CallService("mqtt", "publish", null, new MqttPublishParameters
{ {
Topic = $"{rootTopic}/{suffix}", Topic = $"{rootTopic}/{suffix}",
Payload = string.Empty, Payload = string.Empty,
Retain = true Retain = true
}); });
}
// IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket. // IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket.
return Task.CompletedTask; return Task.CompletedTask;
@@ -67,6 +73,7 @@ public class EntityManager(
private static string BuildRootTopic(string entityId, string discoveryPrefix) private static string BuildRootTopic(string entityId, string discoveryPrefix)
{ {
var separatorIndex = entityId.IndexOf('.'); var separatorIndex = entityId.IndexOf('.');
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1) if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
{ {
throw new ArgumentException( throw new ArgumentException(
@@ -1,4 +1,8 @@
using HomeAssistant.Models; #region
using HomeAssistant.Models;
#endregion
namespace HomeAssistant.Entities.Interfaces; namespace HomeAssistant.Entities.Interfaces;
+6 -2
View File
@@ -1,10 +1,14 @@
using NetDaemon.Extensions.MqttEntityManager; #region
using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace HomeAssistant.Models; namespace HomeAssistant.Models;
public class EntityCreateModel public class EntityCreateModel
{ {
public string? EntityId { get; protected init; } public string? EntityId { get; protected init; }
public EntityCreationOptions? Options { get; init; } = new(); public EntityCreationOptions? Options { get; init; } = new EntityCreationOptions();
public object? AdditionalConfig { get; init; } public object? AdditionalConfig { get; init; }
} }
@@ -1,8 +1,12 @@
#region
using System; using System;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Serilog; using Serilog;
#endregion
namespace HomeAssistantServer; namespace HomeAssistantServer;
public static class CustomLoggingProvider public static class CustomLoggingProvider
+17 -4
View File
@@ -1,3 +1,5 @@
#region
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json; using System.Text.Json;
@@ -13,6 +15,8 @@ using NordPoolManager.Interface;
using PowerMonitorManager.Interface; using PowerMonitorManager.Interface;
using ShowerMonitorManager.Interface; using ShowerMonitorManager.Interface;
#endregion
namespace HomeAssistantServer; namespace HomeAssistantServer;
[NetDaemonApp] [NetDaemonApp]
@@ -66,7 +70,8 @@ public sealed class MqttRecreateApp
model = "AppDaemon", model = "AppDaemon",
manufacturer = "HomeAssistant App Daemon" manufacturer = "HomeAssistant App Daemon"
} }
}).ConfigureAwait(false); })
.ConfigureAwait(false);
if (_logger.IsEnabled(LogLevel.Information)) if (_logger.IsEnabled(LogLevel.Information))
{ {
@@ -74,6 +79,7 @@ public sealed class MqttRecreateApp
} }
var button = new Entity(_haContext, RecreateButtonEntityId); var button = new Entity(_haContext, RecreateButtonEntityId);
button.StateChanges() button.StateChanges()
.Subscribe(_ => .Subscribe(_ =>
{ {
@@ -107,9 +113,11 @@ public sealed class MqttRecreateApp
private async Task RecreateNordPoolAsync() private async Task RecreateNordPoolAsync()
{ {
var entityService = _serviceProvider.GetService<INordPoolEntityService>(); var entityService = _serviceProvider.GetService<INordPoolEntityService>();
if (entityService is null) if (entityService is null)
{ {
_logger.LogDebug("NordPool entity service not registered (disabled), skipping"); _logger.LogDebug("NordPool entity service not registered (disabled), skipping");
return; return;
} }
@@ -132,9 +140,11 @@ public sealed class MqttRecreateApp
private async Task RecreateBoilerMonitorAsync() private async Task RecreateBoilerMonitorAsync()
{ {
var entityService = _serviceProvider.GetService<IBoilerMonitorEntityService>(); var entityService = _serviceProvider.GetService<IBoilerMonitorEntityService>();
if (entityService is null) if (entityService is null)
{ {
_logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping"); _logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping");
return; return;
} }
@@ -155,9 +165,11 @@ public sealed class MqttRecreateApp
private async Task RecreateShowerMonitorAsync() private async Task RecreateShowerMonitorAsync()
{ {
var entityService = _serviceProvider.GetService<IShowerMonitorEntityService>(); var entityService = _serviceProvider.GetService<IShowerMonitorEntityService>();
if (entityService is null) if (entityService is null)
{ {
_logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping"); _logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping");
return; return;
} }
@@ -177,9 +189,11 @@ public sealed class MqttRecreateApp
private async Task RecreatePowerMonitorAsync() private async Task RecreatePowerMonitorAsync()
{ {
var entityService = _serviceProvider.GetService<IPowerMonitorEntityService>(); var entityService = _serviceProvider.GetService<IPowerMonitorEntityService>();
if (entityService is null) if (entityService is null)
{ {
_logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping"); _logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping");
return; return;
} }
@@ -202,14 +216,13 @@ public sealed class MqttRecreateApp
try try
{ {
var state = _haContext.GetState(NordPoolPriceEntityId); var state = _haContext.GetState(NordPoolPriceEntityId);
if (state?.Attributes is IDictionary<string, object> attributes && if (state?.Attributes is IDictionary<string, object> attributes &&
attributes.TryGetValue("unit_of_measurement", out var value)) attributes.TryGetValue("unit_of_measurement", out var value))
{ {
return value switch return value switch
{ {
string s => s, string s => s, JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), _ => null
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
_ => null
}; };
} }
} }
+5
View File
@@ -1,3 +1,5 @@
#region
using System; using System;
using System.Reflection; using System.Reflection;
using BatteryMonitorManager; using BatteryMonitorManager;
@@ -28,6 +30,8 @@ using PowerMonitorManager.Models;
using ShowerMonitorManager; using ShowerMonitorManager;
using ShowerMonitorManager.Models; using ShowerMonitorManager.Models;
#endregion
try try
{ {
var app = Host.CreateDefaultBuilder(args) var app = Host.CreateDefaultBuilder(args)
@@ -47,6 +51,7 @@ try
{ {
config.LicenseKey = config.LicenseKey =
"eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g"; "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g";
config.AddProfile<NordPoolMappingProfile>(); config.AddProfile<NordPoolMappingProfile>();
config.AddProfile<GlobalMappingProfile>(); config.AddProfile<GlobalMappingProfile>();
}) })
@@ -1,3 +1,5 @@
#region
using FluentAssertions; using FluentAssertions;
using LeakMonitor.Models; using LeakMonitor.Models;
using LeakMonitorManager; using LeakMonitorManager;
@@ -9,14 +11,16 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitor.Manager.Tests; namespace LeakMonitor.Manager.Tests;
public class LeakMonitorInitTests public class LeakMonitorInitTests
{ {
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new(); private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new Mock<ILogger<LeakMonitorInit>>();
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new(); private readonly Mock<ILeakNotificationService> _notificationServiceMock = new Mock<ILeakNotificationService>();
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new(); private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new LeakMonitorTestData.TrackingObservable<StateChange>();
public LeakMonitorInitTests() public LeakMonitorInitTests()
{ {
@@ -56,6 +60,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState) public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState)
{ {
var sut = CreateSut(); var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange( var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object, _haContextMock.Object,
sensorEntityId, sensorEntityId,
@@ -73,6 +78,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState) public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState)
{ {
var sut = CreateSut(); var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange( var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object, _haContextMock.Object,
sensorEntityId, sensorEntityId,
@@ -90,6 +96,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState) public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState)
{ {
var sut = CreateSut(); var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange( var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object, _haContextMock.Object,
LeakMonitorTestData.AquariumSensorId, LeakMonitorTestData.AquariumSensorId,
@@ -107,6 +114,7 @@ public class LeakMonitorInitTests
// Deduplication is the notification service's job (cooldown); the init handler // Deduplication is the notification service's job (cooldown); the init handler
// forwards each "on" event it receives. // forwards each "on" event it receives.
var sut = CreateSut(); var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange( var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object, _haContextMock.Object,
LeakMonitorTestData.AquariumSensorId, LeakMonitorTestData.AquariumSensorId,
@@ -119,6 +127,7 @@ public class LeakMonitorInitTests
_notificationServiceMock.Verify( _notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Exactly(2)); Times.Exactly(2));
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never()); _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never());
} }
@@ -127,6 +136,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId) public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId)
{ {
var sut = CreateSut(); var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange( var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object, _haContextMock.Object,
sensorEntityId, sensorEntityId,
@@ -160,6 +170,7 @@ public class LeakMonitorInitTests
CreateSut(); CreateSut();
_stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length); _stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length);
_haContextMock.Verify( _haContextMock.Verify(
h => h.StateAllChanges(), h => h.StateAllChanges(),
Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
@@ -199,6 +210,7 @@ public class LeakMonitorInitTests
_notificationServiceMock.Verify( _notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId), n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId),
Times.Once()); Times.Once());
_notificationServiceMock.Verify( _notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Never()); Times.Never());
@@ -219,6 +231,7 @@ public class LeakMonitorInitTests
newState)); newState));
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
_notificationServiceMock.Verify( _notificationServiceMock.Verify(
n => n.SendLeakAlert(It.Is<string>(id => id != sensorEntityId)), n => n.SendLeakAlert(It.Is<string>(id => id != sensorEntityId)),
Times.Never()); Times.Never());
@@ -294,11 +307,14 @@ public class LeakMonitorInitTests
_haContextMock.Object, _haContextMock.Object,
LeakMonitorTestData.AquariumSensorId, LeakMonitorTestData.AquariumSensorId,
LeakMonitorTestData.DetectionSequence)) LeakMonitorTestData.DetectionSequence))
{
_stateChanges.Publish(change); _stateChanges.Publish(change);
}
_notificationServiceMock.Verify( _notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Exactly(2)); Times.Exactly(2));
_notificationServiceMock.Verify( _notificationServiceMock.Verify(
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Exactly(2)); Times.Exactly(2));
@@ -1,3 +1,5 @@
#region
using System.Text.Json; using System.Text.Json;
using LeakMonitor.Models; using LeakMonitor.Models;
using LeakMonitorManager.Models; using LeakMonitorManager.Models;
@@ -5,6 +7,8 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitor.Manager.Tests; namespace LeakMonitor.Manager.Tests;
/// <summary> /// <summary>
@@ -20,12 +24,12 @@ internal static class LeakMonitorTestData
public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId]; public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId];
private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset DefaultStart = new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
/// <summary> /// <summary>
/// Every casing of the "water detected" state, across both configured sensors. /// Every casing of the "water detected" state, across both configured sensors.
/// </summary> /// </summary>
public static TheoryData<string, string?> WaterDetectedCases { get; } = new() public static TheoryData<string, string?> WaterDetectedCases { get; } = new TheoryData<string, string?>
{ {
{ AquariumSensorId, LeakMonitorConsts.WaterDetectedState }, { AquariumSensorId, LeakMonitorConsts.WaterDetectedState },
{ AquariumSensorId, "ON" }, { AquariumSensorId, "ON" },
@@ -37,7 +41,7 @@ internal static class LeakMonitorTestData
/// <summary> /// <summary>
/// Every casing of the "water cleared" state, across both configured sensors. /// Every casing of the "water cleared" state, across both configured sensors.
/// </summary> /// </summary>
public static TheoryData<string, string?> WaterClearedCases { get; } = new() public static TheoryData<string, string?> WaterClearedCases { get; } = new TheoryData<string, string?>
{ {
{ AquariumSensorId, LeakMonitorConsts.WaterClearedState }, { AquariumSensorId, LeakMonitorConsts.WaterClearedState },
{ AquariumSensorId, "OFF" }, { AquariumSensorId, "OFF" },
@@ -83,7 +87,7 @@ internal static class LeakMonitorTestData
/// (sensor id, expected notification id) rows for the id sanitising rules: /// (sensor id, expected notification id) rows for the id sanitising rules:
/// dots become underscores, other characters and blanks are preserved. /// dots become underscores, other characters and blanks are preserved.
/// </summary> /// </summary>
public static TheoryData<string, string> NotificationIdCases { get; } = new() public static TheoryData<string, string> NotificationIdCases { get; } = new TheoryData<string, string>
{ {
{ AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" }, { AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" },
{ BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" }, { BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" },
@@ -100,7 +104,7 @@ internal static class LeakMonitorTestData
/// rows straddling the strict <c>elapsed &lt; cooldown</c> boundary, plus zero, negative /// rows straddling the strict <c>elapsed &lt; cooldown</c> boundary, plus zero, negative
/// and int-max cooldowns. /// and int-max cooldowns.
/// </summary> /// </summary>
public static TheoryData<int, int, int> CooldownBoundaryCases { get; } = new() public static TheoryData<int, int, int> CooldownBoundaryCases { get; } = new TheoryData<int, int, int>
{ {
{ 5, 0, 1 }, { 5, 0, 1 },
{ 5, 299, 1 }, { 5, 299, 1 },
@@ -258,7 +262,10 @@ internal static class LeakMonitorTestData
public void Publish(T value) public void Publish(T value)
{ {
foreach (var observer in _observers.ToArray()) observer.OnNext(value); foreach (var observer in _observers.ToArray())
{
observer.OnNext(value);
}
} }
private sealed class Subscription(List<IObserver<T>> observers, IObserver<T> observer) : IDisposable private sealed class Subscription(List<IObserver<T>> observers, IObserver<T> observer) : IDisposable
@@ -1,3 +1,5 @@
#region
using FluentAssertions; using FluentAssertions;
using LeakMonitor.Models; using LeakMonitor.Models;
using LeakMonitorManager; using LeakMonitorManager;
@@ -8,13 +10,15 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitor.Manager.Tests; namespace LeakMonitor.Manager.Tests;
public class LeakNotificationServiceTests public class LeakNotificationServiceTests
{ {
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new(); private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new Mock<ILogger<LeakNotificationService>>();
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new(); private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new LeakMonitorTestData.ManualTimeProvider();
private LeakNotificationService CreateSut(LeakMonitorOptions? options = null) private LeakNotificationService CreateSut(LeakMonitorOptions? options = null)
{ {
@@ -60,7 +64,7 @@ public class LeakNotificationServiceTests
#region SendLeakAlert #region SendLeakAlert
public static TheoryData<string, string> SendAlertServiceCalls { get; } = new() public static TheoryData<string, string> SendAlertServiceCalls { get; } = new TheoryData<string, string>
{ {
{ LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService }, { LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService },
{ LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService } { LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService }
@@ -110,7 +114,10 @@ public class LeakNotificationServiceTests
var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data); var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data);
persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle); persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle);
persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage); persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage);
persistentPayload.GetProperty("notification_id").GetString().Should()
persistentPayload.GetProperty("notification_id")
.GetString()
.Should()
.Be(LeakNotificationService.BuildNotificationId(sensorId)); .Be(LeakNotificationService.BuildNotificationId(sensorId));
} }
@@ -156,7 +163,10 @@ public class LeakNotificationServiceTests
var sut = CreateSut(); var sut = CreateSut();
const string sensorId = LeakMonitorTestData.AquariumSensorId; const string sensorId = LeakMonitorTestData.AquariumSensorId;
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId); for (var i = 0; i < repeats; i++)
{
sut.SendLeakAlert(sensorId);
}
VerifyMobilePush(Times.Once()); VerifyMobilePush(Times.Once());
VerifyPersistentCreate(Times.Once()); VerifyPersistentCreate(Times.Once());
@@ -169,7 +179,10 @@ public class LeakNotificationServiceTests
var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0)); var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0));
const string sensorId = LeakMonitorTestData.AquariumSensorId; const string sensorId = LeakMonitorTestData.AquariumSensorId;
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId); for (var i = 0; i < repeats; i++)
{
sut.SendLeakAlert(sensorId);
}
VerifyMobilePush(Times.Exactly(repeats)); VerifyMobilePush(Times.Exactly(repeats));
VerifyPersistentCreate(Times.Exactly(repeats)); VerifyPersistentCreate(Times.Exactly(repeats));
@@ -214,7 +227,10 @@ public class LeakNotificationServiceTests
{ {
var sut = CreateSut(); var sut = CreateSut();
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds) sut.SendLeakAlert(sensorId); foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds)
{
sut.SendLeakAlert(sensorId);
}
VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
@@ -286,6 +302,7 @@ public class LeakNotificationServiceTests
dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain); dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain);
dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService); dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService);
dismissCall.Target.Should().BeNull(); dismissCall.Target.Should().BeNull();
LeakMonitorTestData.SerializePayload(dismissCall.Data) LeakMonitorTestData.SerializePayload(dismissCall.Data)
.GetProperty("notification_id") .GetProperty("notification_id")
.GetString() .GetString()
+8 -1
View File
@@ -1,3 +1,5 @@
#region
using LeakMonitor.Models; using LeakMonitor.Models;
using LeakMonitorManager.Interface; using LeakMonitorManager.Interface;
using LeakMonitorManager.Models; using LeakMonitorManager.Models;
@@ -7,6 +9,8 @@ using NetDaemon.AppModel;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitorManager; namespace LeakMonitorManager;
[NetDaemonApp] [NetDaemonApp]
@@ -42,7 +46,10 @@ public sealed class LeakMonitorInit
return Task.CompletedTask; return Task.CompletedTask;
} }
foreach (var sensorEntityId in _options.SensorEntityIds) SubscribeToLeakSensor(sensorEntityId); foreach (var sensorEntityId in _options.SensorEntityIds)
{
SubscribeToLeakSensor(sensorEntityId);
}
if (_logger.IsEnabled(LogLevel.Information)) if (_logger.IsEnabled(LogLevel.Information))
{ {
@@ -1,9 +1,13 @@
#region
using LeakMonitorManager.Interface; using LeakMonitorManager.Interface;
using LeakMonitorManager.Models; using LeakMonitorManager.Models;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
#endregion
namespace LeakMonitorManager; namespace LeakMonitorManager;
public static class LeakMonitorServiceRegistration public static class LeakMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class LeakMonitorServiceRegistration
{ {
var options = configuration var options = configuration
.GetSection(LeakMonitorOptions.SectionName) .GetSection(LeakMonitorOptions.SectionName)
.Get<LeakMonitorOptions>() ?? new LeakMonitorOptions(); .Get<LeakMonitorOptions>() ??
new LeakMonitorOptions();
if (!options.Enabled) return; if (!options.Enabled)
{
return;
}
services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>(); services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
} }
+11 -2
View File
@@ -1,3 +1,5 @@
#region
using System.Collections.Concurrent; using System.Collections.Concurrent;
using LeakMonitor.Models; using LeakMonitor.Models;
using LeakMonitorManager.Interface; using LeakMonitorManager.Interface;
@@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using NetDaemon.HassModel; using NetDaemon.HassModel;
#endregion
namespace LeakMonitorManager; namespace LeakMonitorManager;
public sealed class LeakNotificationService( public sealed class LeakNotificationService(
@@ -14,7 +18,7 @@ public sealed class LeakNotificationService(
IOptions<LeakMonitorOptions> options, IOptions<LeakMonitorOptions> options,
TimeProvider timeProvider) : ILeakNotificationService TimeProvider timeProvider) : ILeakNotificationService
{ {
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new(); private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new ConcurrentDictionary<string, DateTimeOffset>();
private readonly LeakMonitorOptions _options = options.Value; private readonly LeakMonitorOptions _options = options.Value;
public void SendLeakAlert(string sensorEntityId) public void SendLeakAlert(string sensorEntityId)
@@ -95,15 +99,20 @@ public sealed class LeakNotificationService(
private bool IsWithinCooldown(string sensorEntityId) private bool IsWithinCooldown(string sensorEntityId)
{ {
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime)) return false; if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime))
{
return false;
}
var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes); var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes);
return timeProvider.GetUtcNow() - lastTime < cooldown; return timeProvider.GetUtcNow() - lastTime < cooldown;
} }
internal static string BuildNotificationId(string sensorEntityId) internal static string BuildNotificationId(string sensorEntityId)
{ {
var sanitized = sensorEntityId.Replace('.', '_'); var sanitized = sensorEntityId.Replace('.', '_');
return $"{LeakMonitorConsts.NotificationIdPrefix}{sanitized}"; return $"{LeakMonitorConsts.NotificationIdPrefix}{sanitized}";
} }
} }
@@ -1,5 +1,9 @@
#region
using LeakMonitor.Models; using LeakMonitor.Models;
#endregion
namespace LeakMonitorManager.Models; namespace LeakMonitorManager.Models;
public sealed class LeakMonitorOptions public sealed class LeakMonitorOptions
@@ -1,3 +1,5 @@
#region
using LightMonitor.Models; using LightMonitor.Models;
using LightMonitorManager; using LightMonitorManager;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitor.Manager.Tests; namespace LightMonitor.Manager.Tests;
public class LightControlServiceTests public class LightControlServiceTests
@@ -15,7 +19,7 @@ public class LightControlServiceTests
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private LightControlService CreateService(LightMonitorOptions? options = null) private LightControlService CreateService(LightMonitorOptions? options = null)
{ {
@@ -1,3 +1,5 @@
#region
using System.Reactive.Subjects; using System.Reactive.Subjects;
using FluentAssertions; using FluentAssertions;
using LightMonitor.Models; using LightMonitor.Models;
@@ -9,6 +11,8 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitor.Manager.Tests; namespace LightMonitor.Manager.Tests;
public class LightMonitorInitTests public class LightMonitorInitTests
@@ -18,10 +22,10 @@ public class LightMonitorInitTests
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILightControlService> _lightControlServiceMock = new(); private readonly Mock<ILightControlService> _lightControlServiceMock = new Mock<ILightControlService>();
private readonly Mock<IPresenceService> _presenceServiceMock = new(); private readonly Mock<IPresenceService> _presenceServiceMock = new Mock<IPresenceService>();
private readonly Subject<StateChange> _stateChangesSubject = new(); private readonly Subject<StateChange> _stateChangesSubject = new Subject<StateChange>();
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null) private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
{ {
@@ -182,6 +186,7 @@ public class LightMonitorInitTests
_presenceServiceMock.SetupSequence(x => x.IsAnyoneHome()) _presenceServiceMock.SetupSequence(x => x.IsAnyoneHome())
.Throws(new InvalidOperationException("presence failed")) .Throws(new InvalidOperationException("presence failed"))
.Returns(true); .Returns(true);
CreateSut(); CreateSut();
var act = () => EmitStateChange( var act = () => EmitStateChange(
@@ -202,6 +207,7 @@ public class LightMonitorInitTests
_lightControlServiceMock.SetupSequence(x => x.TurnOnLight()) _lightControlServiceMock.SetupSequence(x => x.TurnOnLight())
.Throws(new InvalidOperationException("light failed")) .Throws(new InvalidOperationException("light failed"))
.Pass(); .Pass();
CreateSut(); CreateSut();
var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState); var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
@@ -1,6 +1,10 @@
#region
using LightMonitor.Models; using LightMonitor.Models;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitor.Manager.Tests; namespace LightMonitor.Manager.Tests;
/// <summary> /// <summary>
@@ -37,7 +41,7 @@ internal static class LightMonitorTestData
/// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and /// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and
/// missing states must never turn the light on. /// missing states must never turn the light on.
/// </summary> /// </summary>
public static TheoryData<string?, bool> SunStateTurnOnCases { get; } = new() public static TheoryData<string?, bool> SunStateTurnOnCases { get; } = new TheoryData<string?, bool>
{ {
{ LightMonitorConsts.SunBelowHorizon, true }, { LightMonitorConsts.SunBelowHorizon, true },
{ LightMonitorConsts.SunBelowHorizon.ToUpperInvariant(), true }, { LightMonitorConsts.SunBelowHorizon.ToUpperInvariant(), true },
@@ -55,7 +59,7 @@ internal static class LightMonitorTestData
/// Light states evaluated while the sun is below the horizon. Only "on" (any casing) /// Light states evaluated while the sun is below the horizon. Only "on" (any casing)
/// suppresses the turn on call; everything else, including missing state, turns it on. /// suppresses the turn on call; everything else, including missing state, turns it on.
/// </summary> /// </summary>
public static TheoryData<string?, bool> LightStateTurnOnCases { get; } = new() public static TheoryData<string?, bool> LightStateTurnOnCases { get; } = new TheoryData<string?, bool>
{ {
{ LightMonitorConsts.LightOnState, false }, { LightMonitorConsts.LightOnState, false },
{ LightMonitorConsts.LightOnState.ToUpperInvariant(), false }, { LightMonitorConsts.LightOnState.ToUpperInvariant(), false },
@@ -73,7 +77,7 @@ internal static class LightMonitorTestData
/// Person states checked against the "arrived home" transition. /// Person states checked against the "arrived home" transition.
/// Only "home" in any casing counts. /// Only "home" in any casing counts.
/// </summary> /// </summary>
public static TheoryData<string?, bool> PersonNewStateCases { get; } = new() public static TheoryData<string?, bool> PersonNewStateCases { get; } = new TheoryData<string?, bool>
{ {
{ LightMonitorConsts.PersonHomeState, true }, { LightMonitorConsts.PersonHomeState, true },
{ "HOME", true }, { "HOME", true },
@@ -92,7 +96,7 @@ internal static class LightMonitorTestData
/// Old person states for a transition to "home". Recovery from unavailable, unknown or /// Old person states for a transition to "home". Recovery from unavailable, unknown or
/// missing state must be ignored; every other old state is a real arrival. /// missing state must be ignored; every other old state is a real arrival.
/// </summary> /// </summary>
public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new() public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new TheoryData<string?, bool>
{ {
{ "not_home", true }, { "not_home", true },
{ "work", true }, { "work", true },
@@ -106,7 +110,7 @@ internal static class LightMonitorTestData
/// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown /// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown
/// or missing state must be ignored. /// or missing state must be ignored.
/// </summary> /// </summary>
public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new() public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new TheoryData<string?, bool>
{ {
{ LightMonitorConsts.SunAboveHorizon, true }, { LightMonitorConsts.SunAboveHorizon, true },
{ string.Empty, true }, { string.Empty, true },
@@ -171,9 +175,15 @@ internal static class LightMonitorTestData
var matrix = new TheoryData<string?[]>(); var matrix = new TheoryData<string?[]>();
foreach (var first in PresenceStates) foreach (var first in PresenceStates)
{
foreach (var second in PresenceStates) foreach (var second in PresenceStates)
{
foreach (var third in PresenceStates) foreach (var third in PresenceStates)
{
matrix.Add([first, second, third]); matrix.Add([first, second, third]);
}
}
}
return matrix; return matrix;
} }
@@ -1,3 +1,5 @@
#region
using FluentAssertions; using FluentAssertions;
using LightMonitor.Models; using LightMonitor.Models;
using LightMonitorManager; using LightMonitorManager;
@@ -6,12 +8,14 @@ using Microsoft.Extensions.Options;
using Moq; using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
#endregion
namespace LightMonitor.Manager.Tests; namespace LightMonitor.Manager.Tests;
public class PresenceServiceTests public class PresenceServiceTests
{ {
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private PresenceService CreateService(LightMonitorOptions? options = null) private PresenceService CreateService(LightMonitorOptions? options = null)
{ {
@@ -95,8 +99,10 @@ public class PresenceServiceTests
CreateService().IsAnyoneHome().Should().BeFalse(); CreateService().IsAnyoneHome().Should().BeFalse();
foreach (var personEntityId in LightMonitorTestData.PersonEntityIds) foreach (var personEntityId in LightMonitorTestData.PersonEntityIds)
{
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once); _haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
} }
}
[Fact] [Fact]
public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured() public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured()
@@ -120,6 +126,8 @@ public class PresenceServiceTests
service.IsAnyoneHome().Should().BeFalse(); service.IsAnyoneHome().Should().BeFalse();
foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds) foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds)
{
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once); _haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
} }
}
} }
@@ -1,3 +1,5 @@
#region
using LightMonitor.Models; using LightMonitor.Models;
using LightMonitorManager.Interface; using LightMonitorManager.Interface;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -5,6 +7,8 @@ using Microsoft.Extensions.Options;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitorManager; namespace LightMonitorManager;
public sealed class LightControlService( public sealed class LightControlService(
+10 -1
View File
@@ -1,3 +1,5 @@
#region
using LightMonitor.Models; using LightMonitor.Models;
using LightMonitorManager.Interface; using LightMonitorManager.Interface;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using NetDaemon.AppModel;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitorManager; namespace LightMonitorManager;
[NetDaemonApp] [NetDaemonApp]
@@ -57,6 +61,7 @@ public sealed class LightMonitorInit
private void SubscribeToSunStateChanges() private void SubscribeToSunStateChanges()
{ {
var sunEntity = new Entity(_haContext, _options.SunEntityId); var sunEntity = new Entity(_haContext, _options.SunEntityId);
sunEntity.StateChanges() sunEntity.StateChanges()
.Subscribe(e => .Subscribe(e =>
{ {
@@ -80,7 +85,10 @@ public sealed class LightMonitorInit
_logger.LogInformation("Sun went below horizon, checking if anyone is home"); _logger.LogInformation("Sun went below horizon, checking if anyone is home");
if (_presenceService.IsAnyoneHome()) _lightControlService.TurnOnLight(); if (_presenceService.IsAnyoneHome())
{
_lightControlService.TurnOnLight();
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -94,6 +102,7 @@ public sealed class LightMonitorInit
foreach (var personEntityId in _options.PersonEntityIds) foreach (var personEntityId in _options.PersonEntityIds)
{ {
var personEntity = new Entity(_haContext, personEntityId); var personEntity = new Entity(_haContext, personEntityId);
personEntity.StateChanges() personEntity.StateChanges()
.Subscribe(e => .Subscribe(e =>
{ {
@@ -1,9 +1,13 @@
#region
using LightMonitor.Models; using LightMonitor.Models;
using LightMonitorManager.Interface; using LightMonitorManager.Interface;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
#endregion
namespace LightMonitorManager; namespace LightMonitorManager;
public static class LightMonitorServiceRegistration public static class LightMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class LightMonitorServiceRegistration
{ {
var options = configuration var options = configuration
.GetSection(LightMonitorOptions.SectionName) .GetSection(LightMonitorOptions.SectionName)
.Get<LightMonitorOptions>() ?? new LightMonitorOptions(); .Get<LightMonitorOptions>() ??
new LightMonitorOptions();
if (!options.Enabled) return services; if (!options.Enabled)
{
return services;
}
services.AddNetDaemonApp<LightMonitorInit>() services.AddNetDaemonApp<LightMonitorInit>()
.AddScoped<IPresenceService, PresenceService>() .AddScoped<IPresenceService, PresenceService>()
+8 -1
View File
@@ -1,9 +1,13 @@
#region
using LightMonitor.Models; using LightMonitor.Models;
using LightMonitorManager.Interface; using LightMonitorManager.Interface;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using NetDaemon.HassModel; using NetDaemon.HassModel;
#endregion
namespace LightMonitorManager; namespace LightMonitorManager;
public sealed class PresenceService( public sealed class PresenceService(
@@ -30,7 +34,10 @@ public sealed class PresenceService(
continue; continue;
} }
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Person {EntityId} is home", personEntityId); if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Person {EntityId} is home", personEntityId);
}
return true; return true;
} }
@@ -1,5 +1,9 @@
#region
using static LightMonitor.Models.LightMonitorConsts; using static LightMonitor.Models.LightMonitorConsts;
#endregion
namespace LightMonitor.Models; namespace LightMonitor.Models;
public sealed class LightMonitorOptions public sealed class LightMonitorOptions
+5 -1
View File
@@ -1,6 +1,10 @@
using System.Globalization; #region
using System.Globalization;
using AutoMapper; using AutoMapper;
#endregion
namespace Mappings.Converters; namespace Mappings.Converters;
public class DateTimeTypeConverter : ITypeConverter<string, DateTime> public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
+5 -1
View File
@@ -1,6 +1,10 @@
using AutoMapper; #region
using AutoMapper;
using Mappings.Converters; using Mappings.Converters;
#endregion
namespace Mappings; namespace Mappings;
public class GlobalMappingProfile : Profile public class GlobalMappingProfile : Profile
+6 -1
View File
@@ -1,7 +1,11 @@
using AutoMapper; #region
using AutoMapper;
using NordPool.Models; using NordPool.Models;
using NordPool.Models.Dtos; using NordPool.Models.Dtos;
#endregion
namespace Mappings; namespace Mappings;
public class NordPoolMappingProfile : Profile public class NordPoolMappingProfile : Profile
@@ -10,6 +14,7 @@ public class NordPoolMappingProfile : Profile
{ {
CreateMap<NordPoolDayPriceDto, NordPoolDayPrice>() CreateMap<NordPoolDayPriceDto, NordPoolDayPrice>()
.ForMember(destination => destination.Price, options => options.MapFrom(source => source.Price)); .ForMember(destination => destination.Price, options => options.MapFrom(source => source.Price));
CreateMap<NordPoolPriceResultDto, NordPoolPrice>(); CreateMap<NordPoolPriceResultDto, NordPoolPrice>();
} }
} }
@@ -1,9 +1,13 @@
#region
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Moq; using Moq;
using NordPool.Models; using NordPool.Models;
using NordPoolManager; using NordPoolManager;
#endregion
namespace NordPool.Manager.Tests; namespace NordPool.Manager.Tests;
public class CheapestIntervalsFinderTests public class CheapestIntervalsFinderTests
@@ -13,7 +17,7 @@ public class CheapestIntervalsFinderTests
private static readonly DateTime DayStart = NordPoolTestData.DayStart; private static readonly DateTime DayStart = NordPoolTestData.DayStart;
private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1); private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1);
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new(); private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new Mock<ILogger<CheapestIntervalsFinder>>();
private CheapestIntervalsFinder CreateSut() private CheapestIntervalsFinder CreateSut()
{ {
@@ -55,7 +59,7 @@ public class CheapestIntervalsFinderTests
#region FindCheapestIntervals #region FindCheapestIntervals
public static TheoryData<string, double[], int, double, double, int> FilteringCases => new() public static TheoryData<string, double[], int, double, double, int> FilteringCases => new TheoryData<string, double[], int, double, double, int>
{ {
{ "deadline includes interval ending exactly at it", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_800.0, 2 }, { "deadline includes interval ending exactly at it", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_800.0, 2 },
{ "deadline excludes interval ending one second late", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_799.0, 1 }, { "deadline excludes interval ending one second late", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_799.0, 1 },
@@ -236,12 +240,13 @@ public class CheapestIntervalsFinderTests
{ {
// Arrange — duplicate payload entries are not deduplicated // Arrange — duplicate payload entries are not deduplicated
var sut = CreateSut(); var sut = CreateSut();
var prices = new NordPoolPrice var prices = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }, new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 },
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 } new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }
} }
}; };
@@ -258,15 +263,16 @@ public class CheapestIntervalsFinderTests
{ {
// Arrange // Arrange
var sut = CreateSut(); var sut = CreateSut();
var prices = new NordPoolPrice var prices = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 }, new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 },
new() { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null }, new NordPoolDayPrice { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null },
new() { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 }, new NordPoolDayPrice { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 },
new() { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 }, new NordPoolDayPrice { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 },
new() { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 } new NordPoolDayPrice { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 }
} }
}; };
@@ -315,6 +321,7 @@ public class CheapestIntervalsFinderTests
{ {
// Arrange - xUnit cannot serialize CheapestIntervalResult rows, so the matrix is exercised in one test // Arrange - xUnit cannot serialize CheapestIntervalResult rows, so the matrix is exercised in one test
var sut = CreateSut(); var sut = CreateSut();
(string Scenario, int NowSeconds, CheapestIntervalResult[] Intervals, bool Expected)[] cases = (string Scenario, int NowSeconds, CheapestIntervalResult[] Intervals, bool Expected)[] cases =
[ [
("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true), ("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
@@ -1,21 +1,25 @@
#region
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using FluentAssertions; using FluentAssertions;
using NordPool.Models; using NordPool.Models;
using static NordPool.Models.NordPoolConsts; using static NordPool.Models.NordPoolConsts;
#endregion
namespace NordPool.Manager.Tests; namespace NordPool.Manager.Tests;
public class CompactNordPoolDayPriceTests public class CompactNordPoolDayPriceTests
{ {
private const int IntervalDurationSeconds = MinutesPerInterval * 60; private const int IntervalDurationSeconds = MinutesPerInterval * 60;
private static readonly DateTime TestStart = new(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc); private static readonly DateTime TestStart = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval); private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval);
private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds(); private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds();
private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds(); private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds();
public static TheoryData<string, string> InvalidJsonPayloads => new() public static TheoryData<string, string> InvalidJsonPayloads => new TheoryData<string, string>
{ {
{ "empty array", "[]" }, { "empty array", "[]" },
{ "too few elements", "[1,2]" }, { "too few elements", "[1,2]" },
@@ -157,8 +161,8 @@ public class CompactNordPoolDayPriceTests
{ {
var prices = new List<CompactNordPoolDayPrice> var prices = new List<CompactNordPoolDayPrice>
{ {
new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 }, new CompactNordPoolDayPrice { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 } new CompactNordPoolDayPrice { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
}; };
var json = JsonSerializer.Serialize(prices); var json = JsonSerializer.Serialize(prices);
@@ -198,8 +202,8 @@ public class CompactNordPoolDayPriceTests
{ {
var prices = new List<NordPoolDayPrice> var prices = new List<NordPoolDayPrice>
{ {
new() { Start = TestStart, End = TestEnd, Price = 12.50 }, new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.50 },
new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 } new NordPoolDayPrice { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
}; };
var result = prices.ToCompact(); var result = prices.ToCompact();
@@ -240,7 +244,10 @@ public class CompactNordPoolDayPriceTests
result.Should().HaveCount(96); result.Should().HaveCount(96);
result.Should().BeInAscendingOrder(p => p.Start); result.Should().BeInAscendingOrder(p => p.Start);
result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds()); result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds());
result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
result[95]
.Start.Should()
.Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
.ToUnixTimeSeconds()); .ToUnixTimeSeconds());
} }
@@ -262,7 +269,7 @@ public class CompactNordPoolDayPriceTests
{ {
var prices = new List<NordPoolDayPrice> var prices = new List<NordPoolDayPrice>
{ {
new() { Start = null, End = null, Price = null } new NordPoolDayPrice { Start = null, End = null, Price = null }
}; };
var result = prices.ToCompact(); var result = prices.ToCompact();
@@ -280,6 +287,7 @@ public class CompactNordPoolDayPriceTests
var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22); var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22);
var compactPrices = prices.ToCompact(); var compactPrices = prices.ToCompact();
var attributePayload = new var attributePayload = new
{ {
prices = compactPrices, prices = compactPrices,
@@ -287,10 +295,12 @@ public class CompactNordPoolDayPriceTests
friendly_name = "NordPool today and tomorrow prices", friendly_name = "NordPool today and tomorrow prices",
last_updated = DateTime.UtcNow.ToString("O") last_updated = DateTime.UtcNow.ToString("O")
}; };
var json = JsonSerializer.Serialize(attributePayload); var json = JsonSerializer.Serialize(attributePayload);
var byteCount = Encoding.UTF8.GetByteCount(json); var byteCount = Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes, byteCount.Should()
.BeLessThan(haAttributeByteLimitBytes,
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit"); $"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
} }
} }
@@ -1,3 +1,5 @@
#region
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using FluentAssertions; using FluentAssertions;
@@ -8,6 +10,8 @@ using NordPool.Models;
using NordPoolManager; using NordPoolManager;
using NordPoolManager.Models; using NordPoolManager.Models;
#endregion
namespace NordPool.Manager.Tests; namespace NordPool.Manager.Tests;
public class NordPoolEntityServiceTests public class NordPoolEntityServiceTests
@@ -113,10 +117,12 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
var callCount = 0; var callCount = 0;
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>())) _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(() => .Returns(() =>
{ {
callCount++; callCount++;
return callCount == 2 return callCount == 2
? throw new InvalidOperationException("Entity creation failed") ? throw new InvalidOperationException("Entity creation failed")
: Task.CompletedTask; : Task.CompletedTask;
@@ -222,6 +228,7 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
var attributes = new { unit_of_measurement = "EUR/kWh" }; var attributes = new { unit_of_measurement = "EUR/kWh" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -237,6 +244,7 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
var attributes = new { unit_of_measurement = "EUR/kWh" }; var attributes = new { unit_of_measurement = "EUR/kWh" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.ThrowsAsync(new InvalidOperationException("Attributes update failed")); .ThrowsAsync(new InvalidOperationException("Attributes update failed"));
@@ -257,6 +265,7 @@ public class NordPoolEntityServiceTests
// Arrange // Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -265,11 +274,13 @@ public class NordPoolEntityServiceTests
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", string.Empty), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"), _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("button.nordpool_fetch_prices", "unknown"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("button.nordpool_fetch_prices", "unknown"), Times.Once);
} }
@@ -280,6 +291,7 @@ public class NordPoolEntityServiceTests
// Arrange // Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -289,16 +301,22 @@ public class NordPoolEntityServiceTests
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once); Times.Once);
_entityManagerMock.Verify( _entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once); em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify( _entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once); em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()),
Times.Once); Times.Once);
} }
@@ -309,9 +327,11 @@ public class NordPoolEntityServiceTests
// Arrange // Arrange
_entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed")); .ThrowsAsync(new InvalidOperationException("State update failed"));
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>())) em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -328,6 +348,7 @@ public class NordPoolEntityServiceTests
// Arrange - 7 entities get state and attributes // Arrange - 7 entities get state and attributes
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -336,6 +357,7 @@ public class NordPoolEntityServiceTests
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(7)); _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(7));
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
Times.Exactly(7)); Times.Exactly(7));
} }
@@ -356,13 +378,15 @@ public class NordPoolEntityServiceTests
DayQuartersIndex = 5, DayQuartersIndex = 5,
LastApiUpdateDate = DateTime.UtcNow, LastApiUpdateDate = DateTime.UtcNow,
UsingCachedData = false, UsingCachedData = false,
TodayNordPoolPrice = todayPrice ?? new NordPoolPrice TodayNordPoolPrice = todayPrice ??
new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
}, },
TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice TomorrowNordPoolPrice = tomorrowPrice ??
new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
}, },
CheapestIntervals = [], CheapestIntervals = [],
ConfiguredHours = 2.0, ConfiguredHours = 2.0,
@@ -383,6 +407,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -392,12 +417,15 @@ public class NordPoolEntityServiceTests
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()), _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once);
_entityManagerMock.Verify( _entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices",
It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once); It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()), _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()),
Times.Once); Times.Once);
} }
@@ -410,6 +438,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -419,10 +448,13 @@ public class NordPoolEntityServiceTests
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once); Times.Once);
_entityManagerMock.Verify( _entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once); em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
} }
@@ -437,6 +469,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -446,13 +479,13 @@ public class NordPoolEntityServiceTests
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
_entityManagerMock.Verify( _entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s => em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s =>
s.Length > 0 && s != "0" && s.Contains('-'))), s.Length > 0 && s != "0" && s.Contains('-'))),
Times.Once); Times.Once);
} }
[Fact] [Fact]
public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices() public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices()
{ {
@@ -519,12 +552,15 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>())) em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs) .Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>())) It.IsAny<object>()))
@@ -566,10 +602,12 @@ public class NordPoolEntityServiceTests
} }
] ]
}; };
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] }); var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -592,27 +630,34 @@ public class NordPoolEntityServiceTests
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice var todayPrices = Enumerable.Range(0, intervalsPerDay)
.Select(i => new NordPoolDayPrice
{ {
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 4.93 + i * 0.22 Price = 4.93 + i * 0.22
}).ToList(); })
.ToList();
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice var tomorrowPrices = Enumerable.Range(0, intervalsPerDay)
.Select(i => new NordPoolDayPrice
{ {
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 5.50 + i * 0.22 Price = 5.50 + i * 0.22
}).ToList(); })
.ToList();
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>())) em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs) .Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>())) It.IsAny<object>()))
@@ -629,7 +674,9 @@ public class NordPoolEntityServiceTests
capturedAttributes.Should().NotBeNull(); capturedAttributes.Should().NotBeNull();
var json = JsonSerializer.Serialize(capturedAttributes); var json = JsonSerializer.Serialize(capturedAttributes);
var byteCount = Encoding.UTF8.GetByteCount(json); var byteCount = Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
byteCount.Should()
.BeLessThan(haAttributeByteLimitBytes,
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit"); $"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
} }
@@ -647,6 +694,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -662,11 +710,14 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs) .Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>())) em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
@@ -700,11 +751,14 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs) .Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
It.IsAny<object>())) It.IsAny<object>()))
@@ -717,6 +771,7 @@ public class NordPoolEntityServiceTests
Price = 4.93, Price = 4.93,
Rank = 1 Rank = 1
}; };
var second = new CheapestIntervalResult var second = new CheapestIntervalResult
{ {
Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc), Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc),
@@ -746,8 +801,10 @@ public class NordPoolEntityServiceTests
capturedAttributes.Should().NotBeNull(); capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!; var attributes = capturedAttributes!;
var type = attributes.GetType(); var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should() ((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should()
.HaveCount(2); .HaveCount(2);
type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30); type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30);
type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true); type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true);
type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O")); type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O"));
@@ -763,11 +820,14 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs) .Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
It.IsAny<object>())) It.IsAny<object>()))
@@ -794,18 +854,22 @@ public class NordPoolEntityServiceTests
{ {
// Arrange // Arrange
object? capturedAttributes = null; object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>())) em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs) .Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => _entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>())) It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var todayPrice = new NordPoolPrice var todayPrice = new NordPoolPrice
{ {
Prices = Prices =
@@ -815,6 +879,7 @@ public class NordPoolEntityServiceTests
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 } new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
] ]
}; };
var tomorrowPrice = new NordPoolPrice var tomorrowPrice = new NordPoolPrice
{ {
Prices = Prices =
@@ -823,6 +888,7 @@ public class NordPoolEntityServiceTests
{ Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 } { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
] ]
}; };
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice); var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
// Act // Act
@@ -844,23 +910,30 @@ public class NordPoolEntityServiceTests
// Arrange // Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
var todayPrices = Enumerable.Range(0, 100)
.Select(i => new NordPoolDayPrice
{ {
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0 Price = 10.0
}).ToList(); })
var tomorrowPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice .ToList();
var tomorrowPrices = Enumerable.Range(0, 100)
.Select(i => new NordPoolDayPrice
{ {
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0 Price = 10.0
}).ToList(); })
.ToList();
var context = CreateDefaultContext( var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = todayPrices }, todayPrice: new NordPoolPrice { Prices = todayPrices },
@@ -895,6 +968,7 @@ public class NordPoolEntityServiceTests
data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled)); data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled));
data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled)); data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled));
data.Add("cleanup entities", sut => sut.CleanupEntitiesAsync(cancelled)); data.Add("cleanup entities", sut => sut.CleanupEntitiesAsync(cancelled));
return data; return data;
} }
+17 -1
View File
@@ -1,3 +1,5 @@
#region
using System.Reactive.Concurrency; using System.Reactive.Concurrency;
using BoilerMonitor.Models; using BoilerMonitor.Models;
using FluentAssertions; using FluentAssertions;
@@ -11,6 +13,8 @@ using NordPoolManager;
using NordPoolManager.Interface; using NordPoolManager.Interface;
using NordPoolManager.Models; using NordPoolManager.Models;
#endregion
namespace NordPool.Manager.Tests; namespace NordPool.Manager.Tests;
public class NordPoolInitTests public class NordPoolInitTests
@@ -41,12 +45,16 @@ public class NordPoolInitTests
_priceServiceMock _priceServiceMock
.Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>())) .Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>())) _entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny<string>())).Returns(Task.CompletedTask); _entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny<string>())).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask); _entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>())) _entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0); _priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0);
_priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny<DateOnly>())).Returns(false); _priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny<DateOnly>())).Returns(false);
_priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0); _priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0);
@@ -54,11 +62,14 @@ public class NordPoolInitTests
_priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null); _priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null);
_priceServiceMock.SetupGet(p => p.CurrentPrice).Returns(0.0); _priceServiceMock.SetupGet(p => p.CurrentPrice).Returns(0.0);
_priceServiceMock.SetupGet(p => p.LastUpdatedDate).Returns((DateTime?)null); _priceServiceMock.SetupGet(p => p.LastUpdatedDate).Returns((DateTime?)null);
_cheapestIntervalsFinderMock _cheapestIntervalsFinderMock
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(), .Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
It.IsAny<DateTime>())) It.IsAny<DateTime>()))
.Returns(false); .Returns(false);
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration())
.Returns(new BoilerConfig
{ {
IntervalCount = 4, IntervalCount = 4,
PriceCap = double.MaxValue, PriceCap = double.MaxValue,
@@ -109,9 +120,12 @@ public class NordPoolInitTests
_entityServiceMock.Verify( _entityServiceMock.Verify(
es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()), es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()),
cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never()); cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never());
_entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()), _entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce); Times.AtLeastOnce);
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce); _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce);
_entityServiceMock.Verify( _entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce); Times.AtLeastOnce);
@@ -121,6 +135,7 @@ public class NordPoolInitTests
public async Task InitializeAsync_WhenCreatingEntitiesFails_ShouldRethrow() public async Task InitializeAsync_WhenCreatingEntitiesFails_ShouldRethrow()
{ {
var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false }); var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false });
_entityServiceMock _entityServiceMock
.Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())) .Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("create failed")); .ThrowsAsync(new InvalidOperationException("create failed"));
@@ -129,6 +144,7 @@ public class NordPoolInitTests
await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("create failed"); await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("create failed");
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never); _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never);
_entityServiceMock.Verify( _entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never); es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never);
} }
@@ -1,4 +1,6 @@
using System.Globalization; #region
using System.Globalization;
using System.Text.Json; using System.Text.Json;
using AutoMapper; using AutoMapper;
using FluentAssertions; using FluentAssertions;
@@ -8,6 +10,8 @@ using NordPool.Models;
using NordPool.Models.Dtos; using NordPool.Models.Dtos;
using NordPoolManager; using NordPoolManager;
#endregion
namespace NordPool.Manager.Tests; namespace NordPool.Manager.Tests;
public class NordPoolPriceServiceTests public class NordPoolPriceServiceTests
@@ -110,13 +114,16 @@ public class NordPoolPriceServiceTests
{ {
// Arrange & Act — iterate over a full UTC day; CET conversion produces 96 unique quarter indices // Arrange & Act — iterate over a full UTC day; CET conversion produces 96 unique quarter indices
var indices = new HashSet<int>(); var indices = new HashSet<int>();
for (var hour = 0; hour < 24; hour++) for (var hour = 0; hour < 24; hour++)
{
for (var minute = 0; minute < 60; minute += 15) for (var minute = 0; minute < 60; minute += 15)
{ {
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
var index = NordPoolPriceService.GetTimeQuarterIndex(date); var index = NordPoolPriceService.GetTimeQuarterIndex(date);
indices.Add(index); indices.Add(index);
} }
}
// Assert // Assert
indices.Should().HaveCount(96); indices.Should().HaveCount(96);
@@ -127,8 +134,12 @@ public class NordPoolPriceServiceTests
[Theory] [Theory]
[InlineData(2026, 1, 15, 8, 0, 36)] // CET winter (UTC+1): UTC 08:00 = CET 09:00 -> index 36 [InlineData(2026, 1, 15, 8, 0, 36)] // CET winter (UTC+1): UTC 08:00 = CET 09:00 -> index 36
[InlineData(2026, 7, 15, 8, 0, 40)] // CEST summer (UTC+2): UTC 08:00 = CEST 10:00 -> index 40 [InlineData(2026, 7, 15, 8, 0, 40)] // CEST summer (UTC+2): UTC 08:00 = CEST 10:00 -> index 40
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, int month, int day, int hour, public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year,
int minute, int expectedIndex) int month,
int day,
int hour,
int minute,
int expectedIndex)
{ {
// Arrange // Arrange
var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc); var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc);
@@ -245,7 +256,7 @@ public class NordPoolPriceServiceTests
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() new NordPoolDayPrice
{ {
Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture), Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture),
End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0 End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0
@@ -322,9 +333,9 @@ public class NordPoolPriceServiceTests
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 }, new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
} }
}; };
@@ -347,9 +358,9 @@ public class NordPoolPriceServiceTests
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }, new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }, new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 } new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
} }
}; };
@@ -388,7 +399,7 @@ public class NordPoolPriceServiceTests
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() { Start = startTime, End = endTime, Price = 81.0 } new NordPoolDayPrice { Start = startTime, End = endTime, Price = 81.0 }
} }
}; };
@@ -424,8 +435,8 @@ public class NordPoolPriceServiceTests
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null }, new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null } new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }
} }
}; };
@@ -445,7 +456,7 @@ public class NordPoolPriceServiceTests
{ {
Prices = new List<NordPoolDayPrice> Prices = new List<NordPoolDayPrice>
{ {
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 } new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }
} }
}; };
@@ -469,12 +480,14 @@ public class NordPoolPriceServiceTests
var prices = new List<NordPoolDayPrice>(); var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++) for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice prices.Add(new NordPoolDayPrice
{ {
Start = now.AddMinutes(i * 15), Start = now.AddMinutes(i * 15),
End = now.AddMinutes((i + 1) * 15), End = now.AddMinutes((i + 1) * 15),
Price = 5.0 + i * 0.22 Price = 5.0 + i * 0.22
}); });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
@@ -532,8 +545,11 @@ public class NordPoolPriceServiceTests
var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = new List<NordPoolDayPrice>(); var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++) for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 }); prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = expectedIndex; _sut.DayQuartersIndex = expectedIndex;
@@ -552,8 +568,11 @@ public class NordPoolPriceServiceTests
{ {
// Arrange // Arrange
var prices = new List<NordPoolDayPrice>(); var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++) for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = null }); prices.Add(new NordPoolDayPrice { Price = null });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91; _sut.CurrentPrice = 17.91;
@@ -572,8 +591,11 @@ public class NordPoolPriceServiceTests
{ {
// Arrange // Arrange
var prices = new List<NordPoolDayPrice>(); var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++) for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 }); prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = -1; _sut.DayQuartersIndex = -1;
@@ -595,6 +617,7 @@ public class NordPoolPriceServiceTests
{ {
// Arrange — negative and zero spot prices are valid NordPool scenarios // Arrange — negative and zero spot prices are valid NordPool scenarios
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = NordPoolTestData.CreateIntervals( var prices = NordPoolTestData.CreateIntervals(
NordPoolConsts.MaxDailyIntervals, NordPoolConsts.MaxDailyIntervals,
i => i == index ? expectedPrice : 10.0); i => i == index ? expectedPrice : 10.0);
@@ -616,6 +639,7 @@ public class NordPoolPriceServiceTests
{ {
// Arrange — fewer prices than the current quarter index (e.g. partial day payload) // Arrange — fewer prices than the current quarter index (e.g. partial day payload)
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, index) var prices = Enumerable.Range(0, index)
.Select(i => new NordPoolDayPrice { Price = 10.0 + i }) .Select(i => new NordPoolDayPrice { Price = 10.0 + i })
.ToList(); .ToList();
@@ -637,6 +661,7 @@ public class NordPoolPriceServiceTests
{ {
// Arrange // Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(_ => new NordPoolDayPrice { Price = 99.0 }) .Select(_ => new NordPoolDayPrice { Price = 99.0 })
.ToList(); .ToList();
@@ -658,6 +683,7 @@ public class NordPoolPriceServiceTests
{ {
// Arrange // Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 }) .Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 })
.ToList(); .ToList();
@@ -687,6 +713,7 @@ public class NordPoolPriceServiceTests
Task<NordPoolPrice> Fetch(DateOnly date) Task<NordPoolPrice> Fetch(DateOnly date)
{ {
requestedDates.Add(date); requestedDates.Add(date);
return Task.FromResult(CreatePrices(1.5)); return Task.FromResult(CreatePrices(1.5));
} }
@@ -720,6 +747,7 @@ public class NordPoolPriceServiceTests
await _sut.FetchPricesAsync(_ => await _sut.FetchPricesAsync(_ =>
{ {
delegateCalled = true; delegateCalled = true;
return Task.FromResult(CreatePrices(3.0)); return Task.FromResult(CreatePrices(3.0));
}); });
@@ -786,10 +814,12 @@ public class NordPoolPriceServiceTests
// Arrange — tomorrow's prices are not published before 13:00, so cached data is acceptable until then // Arrange — tomorrow's prices are not published before 13:00, so cached data is acceptable until then
var today = DateOnly.FromDateTime(DateTime.Now); var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today; _sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice _sut.TodayNordPoolPrice = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
}; };
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null }; _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null };
// Act // Act
@@ -805,10 +835,12 @@ public class NordPoolPriceServiceTests
// Arrange // Arrange
var today = DateOnly.FromDateTime(DateTime.Now); var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today; _sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice _sut.TodayNordPoolPrice = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
}; };
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() }; _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
// Act // Act
@@ -828,13 +860,14 @@ public class NordPoolPriceServiceTests
// Arrange // Arrange
var tomorrow = new NordPoolPrice var tomorrow = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
}; };
_sut.TodayNordPoolPrice = new NordPoolPrice _sut.TodayNordPoolPrice = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
}; };
_sut.TomorrowNordPoolPrice = tomorrow; _sut.TomorrowNordPoolPrice = tomorrow;
_sut.DayQuartersIndex = 48; _sut.DayQuartersIndex = 48;
var today = new DateOnly(2026, 4, 1); var today = new DateOnly(2026, 4, 1);
@@ -855,7 +888,7 @@ public class NordPoolPriceServiceTests
[Fact] [Fact]
public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice() public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice()
{ {
NordPoolPrice?[] unusablePrices = [null, new() { Prices = null }, new() { Prices = [] }]; NordPoolPrice?[] unusablePrices = [null, new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = [] }];
foreach (var tomorrow in unusablePrices) foreach (var tomorrow in unusablePrices)
{ {
@@ -900,11 +933,12 @@ public class NordPoolPriceServiceTests
// Arrange // Arrange
var previousToday = new NordPoolPrice var previousToday = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
}; };
var tomorrow = new NordPoolPrice var tomorrow = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } } Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
}; };
_sut.TodayNordPoolPrice = previousToday; _sut.TodayNordPoolPrice = previousToday;
+5 -1
View File
@@ -1,5 +1,9 @@
#region
using NordPool.Models; using NordPool.Models;
#endregion
namespace NordPool.Manager.Tests; namespace NordPool.Manager.Tests;
/// <summary> /// <summary>
@@ -8,7 +12,7 @@ namespace NordPool.Manager.Tests;
/// </summary> /// </summary>
internal static class NordPoolTestData internal static class NordPoolTestData
{ {
public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); public static readonly DateTime DayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
/// <summary> /// <summary>
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart" />. /// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart" />.
@@ -1,7 +1,11 @@
#region
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NordPool.Models; using NordPool.Models;
using NordPoolManager.Interface; using NordPoolManager.Interface;
#endregion
namespace NordPoolManager; namespace NordPoolManager;
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
@@ -1,11 +1,17 @@
#region
using NordPool.Models; using NordPool.Models;
#endregion
namespace NordPoolManager.Interface; namespace NordPoolManager.Interface;
public interface ICheapestIntervalsFinder public interface ICheapestIntervalsFinder
{ {
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices,
double priceCap, DateTime deadline); int numberOfIntervals,
double priceCap,
DateTime deadline);
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow); bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
} }
@@ -1,5 +1,9 @@
#region
using BoilerMonitor.Models; using BoilerMonitor.Models;
#endregion
namespace NordPoolManager.Interface; namespace NordPoolManager.Interface;
/// <summary> /// <summary>
@@ -1,5 +1,9 @@
#region
using NordPoolManager.Models; using NordPoolManager.Models;
#endregion
namespace NordPoolManager.Interface; namespace NordPoolManager.Interface;
public interface INordPoolEntityService public interface INordPoolEntityService
@@ -1,6 +1,10 @@
#region
using System.Text.Json; using System.Text.Json;
using NordPool.Models; using NordPool.Models;
#endregion
namespace NordPoolManager.Interface; namespace NordPoolManager.Interface;
public interface INordPoolPriceService public interface INordPoolPriceService
@@ -1,5 +1,9 @@
#region
using NordPool.Models; using NordPool.Models;
#endregion
namespace NordPoolManager.Models; namespace NordPoolManager.Models;
public record EntityUpdateContext public record EntityUpdateContext
@@ -1,6 +1,10 @@
#region
using BoilerMonitor.Models; using BoilerMonitor.Models;
using NordPoolManager.Interface; using NordPoolManager.Interface;
#endregion
namespace NordPoolManager; namespace NordPoolManager;
/// <summary> /// <summary>
+46 -15
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using HomeAssistant.Entities.Interfaces; using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using NordPool.Models;
using NordPoolManager.Interface; using NordPoolManager.Interface;
using NordPoolManager.Models; using NordPoolManager.Models;
#endregion
namespace NordPoolManager; namespace NordPoolManager;
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger) public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger)
@@ -61,7 +65,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
ResetTodayTomorrowPricesAsync(), ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync(), ResetCheapestIntervalsAsync(),
ResetFetchPricesButtonAsync() ResetFetchPricesButtonAsync()
).ConfigureAwait(false); )
.ConfigureAwait(false);
} }
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default) public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
@@ -117,6 +122,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Error cleaning up NordPool entities"); logger.LogError(ex, "Error cleaning up NordPool entities");
throw; throw;
} }
} }
@@ -124,15 +130,18 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
private async Task ResetLastUpdateTimeAsync() private async Task ResetLastUpdateTimeAsync()
{ {
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false); await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(LastUpdateTimeEntityId, new await SetEntityAttributesSafe(LastUpdateTimeEntityId, new
{ {
friendly_name = "NordPool last update time" friendly_name = "NordPool last update time"
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetCurrentPriceAsync() private async Task ResetCurrentPriceAsync()
{ {
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false); await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{ {
unit_of_measurement = (string?)null, unit_of_measurement = (string?)null,
@@ -143,68 +152,79 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
last_api_fetch = (string?)null, last_api_fetch = (string?)null,
using_cached_data = false, using_cached_data = false,
current_quarter_index = 0 current_quarter_index = 0
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetTodayPricesAsync() private async Task ResetTodayPricesAsync()
{ {
await SetEntityStateSafe(TodayPricesEntityId, "0").ConfigureAwait(false); await SetEntityStateSafe(TodayPricesEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayPricesEntityId, new await SetEntityAttributesSafe(TodayPricesEntityId, new
{ {
prices = Array.Empty<CompactNordPoolDayPrice>(), prices = Array.Empty<CompactNordPoolDayPrice>(),
friendly_name = "NordPool today prices", friendly_name = "NordPool today prices",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetTomorrowPricesAsync() private async Task ResetTomorrowPricesAsync()
{ {
await SetEntityStateSafe(TomorrowPricesEntityId, "0").ConfigureAwait(false); await SetEntityStateSafe(TomorrowPricesEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TomorrowPricesEntityId, new await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{ {
prices = Array.Empty<CompactNordPoolDayPrice>(), prices = Array.Empty<CompactNordPoolDayPrice>(),
friendly_name = "NordPool tomorrow prices", friendly_name = "NordPool tomorrow prices",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetTodayTomorrowPricesAsync() private async Task ResetTodayTomorrowPricesAsync()
{ {
await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown").ConfigureAwait(false); await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{ {
prices = Array.Empty<CompactNordPoolDayPrice>(), prices = Array.Empty<CompactNordPoolDayPrice>(),
prices_count = 0, prices_count = 0,
friendly_name = "NordPool today and tomorrow prices", friendly_name = "NordPool today and tomorrow prices",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetCheapestIntervalsAsync() private async Task ResetCheapestIntervalsAsync()
{ {
await SetEntityStateSafe(CheapestIntervalsEntityId, "0").ConfigureAwait(false); await SetEntityStateSafe(CheapestIntervalsEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
{ {
intervals = Array.Empty<CheapestIntervalResult>(), intervals = Array.Empty<CheapestIntervalResult>(),
configured_hours = 0.0, configured_hours = 0.0,
configured_interval_count = 0, configured_interval_count = 0,
configured_price_cap = 0.0, configured_price_cap = 0.0,
configured_ready_by = "", configured_ready_by = string.Empty,
total_heating_minutes = 0, total_heating_minutes = 0,
is_now_cheap = false, is_now_cheap = false,
next_cheap_interval = (string?)null, next_cheap_interval = (string?)null,
friendly_name = "NordPool cheapest boiler intervals", friendly_name = "NordPool cheapest boiler intervals",
last_updated = (string?)null last_updated = (string?)null
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task ResetFetchPricesButtonAsync() private async Task ResetFetchPricesButtonAsync()
{ {
await SetEntityStateSafe(NordPoolConsts.FetchPricesButtonEntityId, "unknown").ConfigureAwait(false); await SetEntityStateSafe(NordPoolConsts.FetchPricesButtonEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.FetchPricesButtonEntityId, new await SetEntityAttributesSafe(NordPoolConsts.FetchPricesButtonEntityId, new
{ {
friendly_name = "NordPool fetch prices" friendly_name = "NordPool fetch prices"
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateLastUpdateTimeAsync(string updateTimeState) private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
@@ -215,6 +235,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp) private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp)
{ {
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false); await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{ {
unit_of_measurement = ctx.UnitOfMeasurement, unit_of_measurement = ctx.UnitOfMeasurement,
@@ -225,47 +246,56 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture), last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture),
using_cached_data = ctx.UsingCachedData, using_cached_data = ctx.UsingCachedData,
current_quarter_index = ctx.DayQuartersIndex current_quarter_index = ctx.DayQuartersIndex
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateTodayPricesAsync(EntityUpdateContext ctx, int todayPricesCount, string timestamp) private async Task UpdateTodayPricesAsync(EntityUpdateContext ctx, int todayPricesCount, string timestamp)
{ {
await SetEntityStateSafe(TodayPricesEntityId, todayPricesCount.ToString()).ConfigureAwait(false); await SetEntityStateSafe(TodayPricesEntityId, todayPricesCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(TodayPricesEntityId, new await SetEntityAttributesSafe(TodayPricesEntityId, new
{ {
prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(), prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(),
friendly_name = "NordPool today prices", friendly_name = "NordPool today prices",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateTomorrowPricesAsync(EntityUpdateContext ctx, int tomorrowPricesCount, string timestamp) private async Task UpdateTomorrowPricesAsync(EntityUpdateContext ctx, int tomorrowPricesCount, string timestamp)
{ {
await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()).ConfigureAwait(false); await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(TomorrowPricesEntityId, new await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{ {
prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(), prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(),
friendly_name = "NordPool tomorrow prices", friendly_name = "NordPool tomorrow prices",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState, private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices,
string updateTimeState,
string timestamp) string timestamp)
{ {
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false); await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{ {
prices = mergedPrices.ToCompact(), prices = mergedPrices.ToCompact(),
prices_count = mergedPrices.Count, prices_count = mergedPrices.Count,
friendly_name = "NordPool today and tomorrow prices", friendly_name = "NordPool today and tomorrow prices",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateCheapestIntervalsAsync(EntityUpdateContext ctx, int cheapestCount, string timestamp) private async Task UpdateCheapestIntervalsAsync(EntityUpdateContext ctx, int cheapestCount, string timestamp)
{ {
await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()).ConfigureAwait(false); await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
{ {
intervals = ctx.CheapestIntervals ?? [], intervals = ctx.CheapestIntervals ?? [],
@@ -279,7 +309,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture), next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture),
friendly_name = "NordPool cheapest boiler intervals", friendly_name = "NordPool cheapest boiler intervals",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement) internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
+10 -1
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using System.Reactive.Concurrency; using System.Reactive.Concurrency;
using BoilerMonitor.Models; using BoilerMonitor.Models;
@@ -12,6 +14,8 @@ using NordPool.Models;
using NordPoolManager.Interface; using NordPoolManager.Interface;
using NordPoolManager.Models; using NordPoolManager.Models;
#endregion
namespace NordPoolManager; namespace NordPoolManager;
[NetDaemonApp] [NetDaemonApp]
@@ -67,7 +71,10 @@ public class NordPoolInit
{ {
await Task.Delay(TimeSpan.FromSeconds(3)); await Task.Delay(TimeSpan.FromSeconds(3));
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync(); if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
await _entityService.CreateEntitiesAsync(UnitOfMeasurement); await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
await _entityService.ResetEntitiesAsync(); await _entityService.ResetEntitiesAsync();
@@ -78,6 +85,7 @@ public class NordPoolInit
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error initializing NordPool prices"); _logger.LogError(ex, "Error initializing NordPool prices");
throw; throw;
} }
} }
@@ -153,6 +161,7 @@ public class NordPoolInit
private void SubscribeToFetchPricesButton() private void SubscribeToFetchPricesButton()
{ {
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId); var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
button.StateChanges() button.StateChanges()
.Subscribe(_ => .Subscribe(_ =>
{ {
+39 -8
View File
@@ -1,3 +1,5 @@
#region
using System.Text.Json; using System.Text.Json;
using AutoMapper; using AutoMapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using NordPool.Models.Dtos;
using NordPoolManager.Interface; using NordPoolManager.Interface;
using NordPoolManager.Models.Consts; using NordPoolManager.Models.Consts;
#endregion
namespace NordPoolManager; namespace NordPoolManager;
/// <summary> /// <summary>
@@ -61,7 +65,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0); logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
} }
if (DayQuartersIndex == index) return; if (DayQuartersIndex == index)
{
return;
}
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index) if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
{ {
@@ -91,13 +98,25 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
public bool ShouldFetchNewPrices(DateOnly date) public bool ShouldFetchNewPrices(DateOnly date)
{ {
if (!LastFetchedDate.HasValue) return true; if (!LastFetchedDate.HasValue)
{
return true;
}
if (LastFetchedDate.Value < date) return true; if (LastFetchedDate.Value < date)
{
return true;
}
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true; if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
{
return true;
}
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false; if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
{
return false;
}
var currentHour = DateTime.Now.Hour; var currentHour = DateTime.Now.Hour;
@@ -125,7 +144,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
internal NordPoolPrice ParseNordPoolResult(JsonElement? element) internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
{ {
if (!element.HasValue) return new NordPoolPrice(); if (!element.HasValue)
{
return new NordPoolPrice();
}
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>(); var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
@@ -141,11 +163,17 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
Prices = new List<NordPoolDayPrice>() Prices = new List<NordPoolDayPrice>()
}; };
if (todayNordPoolPrice.Prices is null) return recalculatedPrice; if (todayNordPoolPrice.Prices is null)
{
return recalculatedPrice;
}
foreach (var price in todayNordPoolPrice.Prices) foreach (var price in todayNordPoolPrice.Prices)
{ {
if (price.Price is null) continue; if (price.Price is null)
{
continue;
}
recalculatedPrice.Prices.Add(new NordPoolDayPrice recalculatedPrice.Prices.Add(new NordPoolDayPrice
{ {
@@ -179,6 +207,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate) private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
{ {
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++) for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
{
try try
{ {
return await fetchPricesForDate(date); return await fetchPricesForDate(date);
@@ -193,8 +222,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt); logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt);
break; break;
} }
}
logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date); logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date);
@@ -1,7 +1,11 @@
#region
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using NordPoolManager.Interface; using NordPoolManager.Interface;
#endregion
namespace NordPoolManager; namespace NordPoolManager;
public static class NordPoolServiceRegistration public static class NordPoolServiceRegistration
@@ -10,6 +14,7 @@ public static class NordPoolServiceRegistration
{ {
services services
.AddNetDaemonApp<NordPoolInit>() .AddNetDaemonApp<NordPoolInit>()
// Singleton is safe: NordPoolPriceService holds no IHaContext/generated // Singleton is safe: NordPoolPriceService holds no IHaContext/generated
// entity dependency. The HA price fetch call lives in NordPoolInit. // entity dependency. The HA price fetch call lives in NordPoolInit.
.AddSingleton<INordPoolPriceService, NordPoolPriceService>() .AddSingleton<INordPoolPriceService, NordPoolPriceService>()
+12 -4
View File
@@ -1,14 +1,22 @@
#region
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models; namespace NordPool.Models;
public class CheapestIntervalResult public class CheapestIntervalResult
{ {
[JsonPropertyName("start")] public DateTime Start { get; init; } [JsonPropertyName("start")]
public DateTime Start { get; init; }
[JsonPropertyName("end")] public DateTime End { get; init; } [JsonPropertyName("end")]
public DateTime End { get; init; }
[JsonPropertyName("price")] public double Price { get; init; } [JsonPropertyName("price")]
public double Price { get; init; }
[JsonPropertyName("rank")] public int Rank { get; init; } [JsonPropertyName("rank")]
public int Rank { get; init; }
} }
+10 -2
View File
@@ -1,6 +1,10 @@
#region
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models; namespace NordPool.Models;
[JsonConverter(typeof(CompactNordPoolDayPriceConverter))] [JsonConverter(typeof(CompactNordPoolDayPriceConverter))]
@@ -40,10 +44,14 @@ public readonly struct CompactNordPoolDayPrice
internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNordPoolDayPrice> internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNordPoolDayPrice>
{ {
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert, public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) JsonSerializerOptions options)
{ {
if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("Expected start of array."); if (reader.TokenType != JsonTokenType.StartArray)
{
throw new JsonException("Expected start of array.");
}
if (!reader.Read() || reader.TokenType != JsonTokenType.Number) if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
{ {
+11 -4
View File
@@ -1,12 +1,19 @@
using System.Text.Json.Serialization; #region
using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models.Dtos; namespace NordPool.Models.Dtos;
public class NordPoolDayPriceDto public class NordPoolDayPriceDto
{ {
[JsonPropertyName("start")] public string? Start { get; init; } [JsonPropertyName("start")]
public string? Start { get; init; }
[JsonPropertyName("end")] public string? End { get; init; } [JsonPropertyName("end")]
public string? End { get; init; }
[JsonPropertyName("price")] public double? Price { get; init; } [JsonPropertyName("price")]
public double? Price { get; init; }
} }
@@ -1,8 +1,13 @@
using System.Text.Json.Serialization; #region
using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models.Dtos; namespace NordPool.Models.Dtos;
public class NordPoolPriceResultDto public class NordPoolPriceResultDto
{ {
[JsonPropertyName("LT")] public List<NordPoolDayPriceDto>? Prices { get; init; } [JsonPropertyName("LT")]
public List<NordPoolDayPriceDto>? Prices { get; init; }
} }
+6 -1
View File
@@ -1,6 +1,10 @@
#region
using HomeAssistant.Models; using HomeAssistant.Models;
using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace NordPool.Models; namespace NordPool.Models;
public class NordPoolEntity : EntityCreateModel public class NordPoolEntity : EntityCreateModel
@@ -39,7 +43,8 @@ public class NordPoolEntity : EntityCreateModel
/// </summary> /// </summary>
public static object CreateAdditionalConfig(object extraProperties) public static object CreateAdditionalConfig(object extraProperties)
{ {
var extras = extraProperties.GetType().GetProperties() var extras = extraProperties.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(extraProperties)); .ToDictionary(p => p.Name, p => p.GetValue(extraProperties));
extras["device"] = DeviceBlock; extras["device"] = DeviceBlock;
@@ -1,6 +1,10 @@
#region
using FluentAssertions; using FluentAssertions;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class CostAccumulatorTests public class CostAccumulatorTests
@@ -29,7 +33,10 @@ public class CostAccumulatorTests
var tasks = Enumerable.Range(0, threadCount) var tasks = Enumerable.Range(0, threadCount)
.Select(_ => Task.Run(() => .Select(_ => Task.Run(() =>
{ {
for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1)); for (var i = 0; i < callsPerThread; i++)
{
sut.AddCost(incrementPerCall, now.AddSeconds(1));
}
})) }))
.ToArray(); .ToArray();
@@ -47,11 +54,7 @@ public class CostAccumulatorTests
{ {
return window switch return window switch
{ {
CostWindow.FifteenMinutes => snapshot.Cost15Min, CostWindow.FifteenMinutes => snapshot.Cost15Min, CostWindow.Hour => snapshot.Cost1Hour, CostWindow.Day => snapshot.CostDaily, CostWindow.Month => snapshot.CostMonthly, _ => throw new ArgumentOutOfRangeException(nameof(window))
CostWindow.Hour => snapshot.Cost1Hour,
CostWindow.Day => snapshot.CostDaily,
CostWindow.Month => snapshot.CostMonthly,
_ => throw new ArgumentOutOfRangeException(nameof(window))
}; };
} }
@@ -116,12 +119,16 @@ public class CostAccumulatorTests
// Arrange // Arrange
var now = PowerMonitorTestData.FixedNow; var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now); var sut = new CostAccumulator(now);
var increments = PowerMonitorTestData.CreatePowerSampleSeries(50) var increments = PowerMonitorTestData.CreatePowerSampleSeries(50)
.Select(watts => watts / 100_000.0) .Select(watts => watts / 100_000.0)
.ToArray(); .ToArray();
// Act // Act
foreach (var increment in increments) sut.AddCost(increment, now.AddSeconds(1)); foreach (var increment in increments)
{
sut.AddCost(increment, now.AddSeconds(1));
}
// Assert // Assert
var expected = increments.Sum(); var expected = increments.Sum();
@@ -191,7 +198,7 @@ public class CostAccumulatorTests
#region Window rollovers #region Window rollovers
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new() public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new TheoryData<string, CostWindow, DateTime, DateTime, double, double>
{ {
{ {
"15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), "15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0),
@@ -323,7 +330,7 @@ public class CostAccumulatorTests
#region Window boundary detection (static methods) #region Window boundary detection (static methods)
public static TheoryData<string, DateTime, DateTime, bool> FifteenMinuteBoundaryCases => new() public static TheoryData<string, DateTime, DateTime, bool> FifteenMinuteBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{ {
{ "same slot, first second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false }, { "same slot, first second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
{ "same slot, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false }, { "same slot, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false },
@@ -344,7 +351,7 @@ public class CostAccumulatorTests
CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
} }
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new() public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{ {
{ "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false }, { "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
{ {
@@ -366,7 +373,7 @@ public class CostAccumulatorTests
CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
} }
public static TheoryData<string, DateTime, DateTime, bool> DayBoundaryCases => new() public static TheoryData<string, DateTime, DateTime, bool> DayBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{ {
{ "same timestamp", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 0, 0, 0), false }, { "same timestamp", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 0, 0, 0), false },
{ "same day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false }, { "same day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false },
@@ -385,7 +392,7 @@ public class CostAccumulatorTests
CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
} }
public static TheoryData<string, DateTime, DateTime, bool> MonthBoundaryCases => new() public static TheoryData<string, DateTime, DateTime, bool> MonthBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{ {
{ "same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false }, { "same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false },
{ "same month, last day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 59), false }, { "same month, last day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 59), false },
@@ -1,8 +1,12 @@
#region
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class OtherPowerCalculationServiceTests public class OtherPowerCalculationServiceTests
@@ -13,12 +17,13 @@ public class OtherPowerCalculationServiceTests
{ {
SmoothingWindowSize = smoothingWindowSize SmoothingWindowSize = smoothingWindowSize
}); });
return new OtherPowerCalculationService(options); return new OtherPowerCalculationService(options);
} }
#region Basic calculation #region Basic calculation
public static TheoryData<string, double, double[], double, string> CalculationCases => new() public static TheoryData<string, double, double[], double, string> CalculationCases => new TheoryData<string, double, double[], double, string>
{ {
{ "two devices", 341.97, [8.55, 36.93], 296.49, "ok" }, { "two devices", 341.97, [8.55, 36.93], 296.49, "ok" },
{ "no devices", 341.97, [], 341.97, "ok" }, { "no devices", 341.97, [], 341.97, "ok" },
@@ -42,6 +47,7 @@ public class OtherPowerCalculationServiceTests
{ {
// Arrange // Arrange
var sut = CreateSut(1); var sut = CreateSut(1);
var devices = deviceWatts var devices = deviceWatts
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts)) .Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
.ToDictionary(entry => entry.entityId, entry => entry.watts); .ToDictionary(entry => entry.entityId, entry => entry.watts);
@@ -166,7 +172,11 @@ public class OtherPowerCalculationServiceTests
// Act // Act
PowerCalculationResult? result = null; PowerCalculationResult? result = null;
for (var i = 0; i < 200; i++) result = sut.Calculate(200.0, new Dictionary<string, double>());
for (var i = 0; i < 200; i++)
{
result = sut.Calculate(200.0, new Dictionary<string, double>());
}
// Assert // Assert
result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1); result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1);
@@ -1,7 +1,11 @@
#region
using FluentAssertions; using FluentAssertions;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class PowerCostCalculationServiceTests public class PowerCostCalculationServiceTests
@@ -12,7 +16,7 @@ public class PowerCostCalculationServiceTests
Other Other
} }
private readonly PowerCostCalculationService _sut = new(); private readonly PowerCostCalculationService _sut = new PowerCostCalculationService();
#region Snapshot defaults #region Snapshot defaults
@@ -52,7 +56,9 @@ public class PowerCostCalculationServiceTests
.Select(_ => Task.Run(() => .Select(_ => Task.Run(() =>
{ {
for (var i = 0; i < callsPerThread; i++) for (var i = 0; i < callsPerThread; i++)
{
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1)); _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
}
})) }))
.ToArray(); .ToArray();
@@ -73,14 +79,12 @@ public class PowerCostCalculationServiceTests
double pricePerKwh, double pricePerKwh,
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds)
{ {
return powerWatts / PowerMonitorConsts.WattsPerKilowatt return powerWatts / PowerMonitorConsts.WattsPerKilowatt * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
* pricePerKwh
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
} }
#region CalculateCostIncrement #region CalculateCostIncrement
public static TheoryData<string, double, double, int, double> CostIncrementCases => new() public static TheoryData<string, double, double, int, double> CostIncrementCases => new TheoryData<string, double, double, int, double>
{ {
{ "default polling interval", 341.97, 0.1791, 15, 0.0002551951125 }, { "default polling interval", 341.97, 0.1791, 15, 0.0002551951125 },
{ "one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0 }, { "one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0 },
@@ -127,9 +131,12 @@ public class PowerCostCalculationServiceTests
// Assert // Assert
costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one"); costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one");
for (var i = 0; i < samples.Count; i++) for (var i = 0; i < samples.Count; i++)
{
costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15); costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15);
} }
}
#endregion #endregion
@@ -149,6 +156,7 @@ public class PowerCostCalculationServiceTests
// Assert // Assert
var expectedTotal = var expectedTotal =
ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts,
PowerMonitorTestData.DefaultPricePerKwh); PowerMonitorTestData.DefaultPricePerKwh);
@@ -218,6 +226,7 @@ public class PowerCostCalculationServiceTests
{ {
// Arrange // Arrange
var now = PowerMonitorTestData.FixedNow; var now = PowerMonitorTestData.FixedNow;
var firstResult = PowerMonitorTestData.CreateCalculation( var firstResult = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
@@ -243,6 +252,7 @@ public class PowerCostCalculationServiceTests
// Act // Act
var singleDeviceResult = PowerMonitorTestData.CreateCalculation( var singleDeviceResult = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
_sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15)); _sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
// Assert // Assert
@@ -270,6 +280,7 @@ public class PowerCostCalculationServiceTests
{ {
// Arrange // Arrange
var now = PowerMonitorTestData.FixedNow; var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation( var result = PowerMonitorTestData.CreateCalculation(
0, 0,
0, 0,
@@ -290,6 +301,7 @@ public class PowerCostCalculationServiceTests
{ {
// Arrange - a sensor glitch must flow through the pure cost math unchanged. // Arrange - a sensor glitch must flow through the pure cost math unchanged.
var now = PowerMonitorTestData.FixedNow; var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation( var result = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0))); deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0)));
@@ -382,6 +394,7 @@ public class PowerCostCalculationServiceTests
const double pricePerKwh = 0.2; const double pricePerKwh = 0.2;
var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96); var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96);
var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries(); var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries();
var expectedPerSlot = timestamps var expectedPerSlot = timestamps
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh)) .Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh))
.ToArray(); .ToArray();
@@ -393,6 +406,7 @@ public class PowerCostCalculationServiceTests
wattSamples[slot], wattSamples[slot],
wattSamples[slot] / 2, wattSamples[slot] / 2,
new Dictionary<string, double>()); new Dictionary<string, double>());
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]); _sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
} }
@@ -416,10 +430,12 @@ public class PowerCostCalculationServiceTests
foreach (var (start, pricePerKwh) in windows) foreach (var (start, pricePerKwh) in windows)
{ {
var watts = 500.0 + start.Hour * 125.0; var watts = 500.0 + start.Hour * 125.0;
var result = PowerMonitorTestData.CreateCalculation( var result = PowerMonitorTestData.CreateCalculation(
watts, watts,
watts / 4, watts / 4,
PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2))); PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
_sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start); _sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start);
expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds)); expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds));
} }
@@ -476,8 +492,10 @@ public class PowerCostCalculationServiceTests
// Assert // Assert
_sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh); _sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh);
_sut.PriceSource.Should().Be("live"); _sut.PriceSource.Should().Be("live");
var expected = var expected =
2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12); _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
} }
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -9,6 +11,8 @@ using NetDaemon.HassModel.Entities;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class PowerLimitEnforcementServiceTests public class PowerLimitEnforcementServiceTests
@@ -16,10 +20,10 @@ public class PowerLimitEnforcementServiceTests
private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId; private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId;
private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId; private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId;
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new(); private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions(); private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow); private readonly FakeTimeProvider _timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow);
private PowerLimitEnforcementService CreateSut() private PowerLimitEnforcementService CreateSut()
{ {
@@ -131,11 +135,13 @@ public class PowerLimitEnforcementServiceTests
{ {
// Arrange // Arrange
var calls = new List<(string domain, string service, string? entityId)>(); var calls = new List<(string domain, string service, string? entityId)>();
_haContextMock _haContextMock
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), .Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(),
It.IsAny<object?>())) It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((d, s, t, _) => .Callback<string, string, ServiceTarget?, object?>((d, s, t, _) =>
calls.Add((d, s, t?.EntityIds?.FirstOrDefault()))); calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
var sut = CreateSut(); var sut = CreateSut();
// Act // Act
@@ -144,8 +150,12 @@ public class PowerLimitEnforcementServiceTests
// Assert // Assert
var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList(); var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList();
turnOffCalls.Should().HaveCount(2); turnOffCalls.Should().HaveCount(2);
turnOffCalls[0].entityId.Should().Be(BoilerSwitch,
turnOffCalls[0]
.entityId.Should()
.Be(BoilerSwitch,
"boiler switch must be turned off before auto_management (race-safe order)"); "boiler switch must be turned off before auto_management (race-safe order)");
turnOffCalls[1].entityId.Should().Be(AutoManagement); turnOffCalls[1].entityId.Should().Be(AutoManagement);
} }
@@ -156,10 +166,12 @@ public class PowerLimitEnforcementServiceTests
_options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"]; _options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"];
_options.PauseAndRestoreEntityIds = ["switch.monitor_c"]; _options.PauseAndRestoreEntityIds = ["switch.monitor_c"];
var calls = new List<string?>(); var calls = new List<string?>();
_haContextMock _haContextMock
.Setup(x => x.CallService(It.IsAny<string>(), "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>())) .Setup(x => x.CallService(It.IsAny<string>(), "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((_, _, target, _) => .Callback<string, string, ServiceTarget?, object?>((_, _, target, _) =>
calls.Add(target?.EntityIds?.FirstOrDefault())); calls.Add(target?.EntityIds?.FirstOrDefault()));
var sut = CreateSut(); var sut = CreateSut();
// Act // Act
@@ -184,6 +196,7 @@ public class PowerLimitEnforcementServiceTests
// Assert // Assert
sut.IsLimitActive.Should().BeTrue(); sut.IsLimitActive.Should().BeTrue();
VerifyNotificationCreated(1); VerifyNotificationCreated(1);
_haContextMock.Verify( _haContextMock.Verify(
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()), x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Never); Times.Never);
@@ -193,7 +206,7 @@ public class PowerLimitEnforcementServiceTests
#region Recovery #region Recovery
public static TheoryData<string, int, double, bool, int> RecoveryCases => new() public static TheoryData<string, int, double, bool, int> RecoveryCases => new TheoryData<string, int, double, bool, int>
{ {
{ "not yet due", 300, 3000.0, true, 0 }, { "not yet due", 300, 3000.0, true, 0 },
{ "one second before due", 599, 3000.0, true, 0 }, { "one second before due", 599, 3000.0, true, 0 },
@@ -379,9 +392,11 @@ public class PowerLimitEnforcementServiceTests
// Assert // Assert
sut.IsLimitActive.Should().BeTrue(); sut.IsLimitActive.Should().BeTrue();
_haContextMock.Verify( _haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()), x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Exactly(3)); Times.Exactly(3));
VerifyTurnOff(BoilerSwitch, 1); VerifyTurnOff(BoilerSwitch, 1);
VerifyTurnOff(AutoManagement, 1); VerifyTurnOff(AutoManagement, 1);
VerifyNotificationCreated(1); VerifyNotificationCreated(1);
@@ -1,3 +1,5 @@
#region
using FluentAssertions; using FluentAssertions;
using HomeAssistant.Entities.Interfaces; using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -5,6 +7,8 @@ using Moq;
using PowerMonitor.Models; using PowerMonitor.Models;
using PowerMonitorManager; using PowerMonitorManager;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class PowerMonitorEntityServiceTests public class PowerMonitorEntityServiceTests
@@ -27,18 +31,22 @@ public class PowerMonitorEntityServiceTests
"button.powermonitor_trigger_limit_breach" "button.powermonitor_trigger_limit_breach"
]; ];
private readonly Mock<IEntityManager> _entityManagerMock = new(); private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
private readonly PowerMonitorEntityService _sut; private readonly PowerMonitorEntityService _sut;
public PowerMonitorEntityServiceTests() public PowerMonitorEntityServiceTests()
{ {
var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>(); var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>())) _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask);
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object); _sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object);
} }
@@ -56,6 +64,7 @@ public class PowerMonitorEntityServiceTests
// Assert // Assert
result.Should().HaveCount(4); result.Should().HaveCount(4);
string[] expectedEntityIds = string[] expectedEntityIds =
[ [
$"sensor.powermonitor_{deviceName}_cost_15min", $"sensor.powermonitor_{deviceName}_cost_15min",
@@ -63,6 +72,7 @@ public class PowerMonitorEntityServiceTests
$"sensor.powermonitor_{deviceName}_cost_daily", $"sensor.powermonitor_{deviceName}_cost_daily",
$"sensor.powermonitor_{deviceName}_cost_monthly" $"sensor.powermonitor_{deviceName}_cost_monthly"
]; ];
result.Should().BeEquivalentTo(expectedEntityIds); result.Should().BeEquivalentTo(expectedEntityIds);
} }
@@ -152,7 +162,7 @@ public class PowerMonitorEntityServiceTests
#region GetPowerDeviceEntitiesNames #region GetPowerDeviceEntitiesNames
public static TheoryData<string, string, string, string> DeviceEntityCases => new() public static TheoryData<string, string, string, string> DeviceEntityCases => new TheoryData<string, string, string, string>
{ {
{ "sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32" }, { "sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32" },
{ "simple device", "sensor.tv_power", "TV Power", "tv" }, { "simple device", "sensor.tv_power", "TV Power", "tv" },
@@ -176,6 +186,7 @@ public class PowerMonitorEntityServiceTests
// Assert // Assert
result.Should().HaveCount(4, $"scenario: {scenario}"); result.Should().HaveCount(4, $"scenario: {scenario}");
string[] expectedEntityIds = string[] expectedEntityIds =
[ [
$"sensor.powermonitor_{expectedDeviceName}_cost_15min", $"sensor.powermonitor_{expectedDeviceName}_cost_15min",
@@ -183,8 +194,10 @@ public class PowerMonitorEntityServiceTests
$"sensor.powermonitor_{expectedDeviceName}_cost_daily", $"sensor.powermonitor_{expectedDeviceName}_cost_daily",
$"sensor.powermonitor_{expectedDeviceName}_cost_monthly" $"sensor.powermonitor_{expectedDeviceName}_cost_monthly"
]; ];
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}"); result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}");
result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}"); result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}");
string[] expectedNames = string[] expectedNames =
[ [
$"{friendlyName} cost (15 min)", $"{friendlyName} cost (15 min)",
@@ -192,6 +205,7 @@ public class PowerMonitorEntityServiceTests
$"{friendlyName} cost (daily)", $"{friendlyName} cost (daily)",
$"{friendlyName} cost (monthly)" $"{friendlyName} cost (monthly)"
]; ];
result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"scenario: {scenario}"); result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"scenario: {scenario}");
} }
@@ -405,10 +419,12 @@ public class PowerMonitorEntityServiceTests
// Assert // Assert
foreach (var window in new[] { "15min", "1h", "daily", "monthly" }) foreach (var window in new[] { "15min", "1h", "daily", "monthly" })
{
_entityManagerMock.Verify( _entityManagerMock.Verify(
em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny<string>()), em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny<string>()),
Times.Once); Times.Once);
} }
}
[Theory] [Theory]
[InlineData(false, "off")] [InlineData(false, "off")]
@@ -455,8 +471,10 @@ public class PowerMonitorEntityServiceTests
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "342.0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "342.0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "128.5"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "128.5"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"), _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"),
Times.Once); Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once);
} }
@@ -467,6 +485,7 @@ public class PowerMonitorEntityServiceTests
_entityManagerMock _entityManagerMock
.Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>())) .Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Failed")); .ThrowsAsync(new InvalidOperationException("Failed"));
var context = PowerMonitorTestData.CreateUpdateContext(); var context = PowerMonitorTestData.CreateUpdateContext();
// Act // Act
@@ -475,6 +494,7 @@ public class PowerMonitorEntityServiceTests
// Assert // Assert
await act.Should().NotThrowAsync(); await act.Should().NotThrowAsync();
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()), _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()),
Times.Once); Times.Once);
} }
@@ -1,7 +1,11 @@
#region
using FluentAssertions; using FluentAssertions;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class PowerMonitorOptionsTests public class PowerMonitorOptionsTests
@@ -1,9 +1,13 @@
#region
using System.Text.Json; using System.Text.Json;
using PowerMonitor.Models; using PowerMonitor.Models;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
/// <summary> /// <summary>
@@ -21,11 +25,11 @@ internal static class PowerMonitorTestData
public const string AutoManagementEntityId = "switch.boilermonitor_auto_management"; public const string AutoManagementEntityId = "switch.boilermonitor_auto_management";
public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power"; public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power";
public static readonly DateTime FixedNow = new(2026, 3, 17, 10, 0, 0); public static readonly DateTime FixedNow = new DateTime(2026, 3, 17, 10, 0, 0);
public static readonly DateTime FixedDayStart = new(2026, 3, 17, 0, 0, 0); public static readonly DateTime FixedDayStart = new DateTime(2026, 3, 17, 0, 0, 0);
public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero); public static readonly DateTimeOffset FixedUtcNow = new DateTimeOffset(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
/// <summary> /// <summary>
/// Two-device reading set used by the cost calculation tests. /// Two-device reading set used by the cost calculation tests.
@@ -107,6 +111,7 @@ internal static class PowerMonitorTestData
string priceSource = "live") string priceSource = "live")
{ {
var readings = deviceReadings ?? CreateDeviceReadings(); var readings = deviceReadings ?? CreateDeviceReadings();
var deviceCosts = readings var deviceCosts = readings
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot( .Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
0.0005 * (index + 1), 0.0005 * (index + 1),
@@ -143,6 +148,7 @@ internal static class PowerMonitorTestData
}; };
configure?.Invoke(options); configure?.Invoke(options);
return options; return options;
} }
@@ -182,11 +188,20 @@ internal static class PowerMonitorTestData
{ {
var attributes = new Dictionary<string, object?>(); var attributes = new Dictionary<string, object?>();
if (deviceClass is not null) attributes["device_class"] = deviceClass; if (deviceClass is not null)
{
attributes["device_class"] = deviceClass;
}
if (unitOfMeasurement is not null) attributes["unit_of_measurement"] = unitOfMeasurement; if (unitOfMeasurement is not null)
{
attributes["unit_of_measurement"] = unitOfMeasurement;
}
if (friendlyName is not null) attributes["friendly_name"] = friendlyName; if (friendlyName is not null)
{
attributes["friendly_name"] = friendlyName;
}
return JsonSerializer.SerializeToElement(attributes); return JsonSerializer.SerializeToElement(attributes);
} }
@@ -1,3 +1,5 @@
#region
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -6,12 +8,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using PowerMonitorManager; using PowerMonitorManager;
#endregion
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class PowerSensorDiscoveryServiceTests public class PowerSensorDiscoveryServiceTests
{ {
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new(); private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new Mock<ILogger<PowerSensorDiscoveryService>>();
private PowerSensorDiscoveryService CreateSut( private PowerSensorDiscoveryService CreateSut(
string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId, string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId,
@@ -22,6 +26,7 @@ public class PowerSensorDiscoveryServiceTests
option.MainMeterEntityId = mainMeterEntityId; option.MainMeterEntityId = mainMeterEntityId;
option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"]; option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"];
})); }));
return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object); return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object);
} }
@@ -33,6 +38,7 @@ public class PowerSensorDiscoveryServiceTests
}; };
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); _haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
return new Entity(_haContextMock.Object, entityId); return new Entity(_haContextMock.Object, entityId);
} }
@@ -243,9 +249,10 @@ public class PowerSensorDiscoveryServiceTests
{ {
// Arrange - HA can report entities whose state has not been published yet. // Arrange - HA can report entities whose state has not been published yet.
var tv = SetupEntity("sensor.tv_power", "power", "W", "TV Power"); var tv = SetupEntity("sensor.tv_power", "power", "W", "TV Power");
_haContextMock _haContextMock
.Setup(h => h.GetAllEntities()) .Setup(h => h.GetAllEntities())
.Returns(new List<Entity> { new(_haContextMock.Object, "sensor.ghost_power"), tv }); .Returns(new List<Entity> { new Entity(_haContextMock.Object, "sensor.ghost_power"), tv });
var sut = CreateSut(); var sut = CreateSut();
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface; namespace PowerMonitorManager.Interface;
public interface IOtherPowerCalculationService public interface IOtherPowerCalculationService
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface; namespace PowerMonitorManager.Interface;
public interface IPowerCostCalculationService public interface IPowerCostCalculationService
@@ -1,6 +1,10 @@
#region
using PowerMonitor.Models; using PowerMonitor.Models;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface; namespace PowerMonitorManager.Interface;
public interface IPowerMonitorEntityService public interface IPowerMonitorEntityService
@@ -1,5 +1,9 @@
#region
using PowerMonitor.Models; using PowerMonitor.Models;
#endregion
namespace PowerMonitorManager.Interface; namespace PowerMonitorManager.Interface;
public interface IPowerSensorDiscoveryService public interface IPowerSensorDiscoveryService
@@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models;
public sealed class CostAccumulator(DateTime now) public sealed class CostAccumulator(DateTime now)
{ {
private readonly Lock _lock = new(); private readonly Lock _lock = new Lock();
private double _cost15Min; private double _cost15Min;
private double _cost1Hour; private double _cost1Hour;
@@ -77,7 +77,10 @@ public sealed class CostAccumulator(DateTime now)
_lastDailyReset = now; _lastDailyReset = now;
} }
if (!IsNewMonthWindow(now, _lastMonthlyReset)) return; if (!IsNewMonthWindow(now, _lastMonthlyReset))
{
return;
}
_previousMonthly = _costMonthly; _previousMonthly = _costMonthly;
_costMonthly = 0; _costMonthly = 0;
@@ -88,6 +91,7 @@ public sealed class CostAccumulator(DateTime now)
{ {
var currentSlot = now.Minute / 15; var currentSlot = now.Minute / 15;
var lastSlot = lastReset.Minute / 15; var lastSlot = lastReset.Minute / 15;
return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot; return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot;
} }
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager.Models; namespace PowerMonitorManager.Models;
public sealed class PowerMonitorOptions public sealed class PowerMonitorOptions
@@ -1,13 +1,17 @@
#region
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using PowerMonitorManager.Interface; using PowerMonitorManager.Interface;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
{ {
private readonly double _alpha; private readonly double _alpha;
private readonly Lock _lock = new(); private readonly Lock _lock = new Lock();
private double? _previousSmoothed; private double? _previousSmoothed;
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options) public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
@@ -29,11 +33,13 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
} }
double smoothed; double smoothed;
lock (_lock) lock (_lock)
{ {
smoothed = _previousSmoothed.HasValue smoothed = _previousSmoothed.HasValue
? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value ? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
: rawOther; : rawOther;
_previousSmoothed = smoothed; _previousSmoothed = smoothed;
} }
@@ -1,15 +1,19 @@
#region
using System.Collections.Concurrent; using System.Collections.Concurrent;
using PowerMonitorManager.Interface; using PowerMonitorManager.Interface;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
public sealed class PowerCostCalculationService : IPowerCostCalculationService public sealed class PowerCostCalculationService : IPowerCostCalculationService
{ {
private readonly Lock _accumulatorLock = new(); private readonly Lock _accumulatorLock = new Lock();
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new(); private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new ConcurrentDictionary<string, CostAccumulator>();
private readonly Lock _priceLock = new(); private readonly Lock _priceLock = new Lock();
private double _lastKnownPrice; private double _lastKnownPrice;
private CostAccumulator? _otherAccumulator; private CostAccumulator? _otherAccumulator;
@@ -38,7 +42,9 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
} }
} }
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, public void RecordCosts(PowerCalculationResult calculation,
double nordPoolPrice,
int pollIntervalSeconds,
DateTime now) DateTime now)
{ {
lock (_priceLock) lock (_priceLock)
@@ -57,6 +63,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
var otherCost = var otherCost =
CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds); CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
GetOrCreateOtherAccumulator(now).AddCost(otherCost, now); GetOrCreateOtherAccumulator(now).AddCost(otherCost, now);
foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings) foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings)
@@ -109,6 +116,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds) internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
{ {
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt; var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
return powerKw * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); return powerKw * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
} }
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -7,6 +9,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
public sealed class PowerLimitEnforcementService( public sealed class PowerLimitEnforcementService(
@@ -25,13 +29,17 @@ public sealed class PowerLimitEnforcementService(
public void EnforceLimit(double currentPowerWatts) public void EnforceLimit(double currentPowerWatts)
{ {
if (!_options.EnforceLimitEnabled) return; if (!_options.EnforceLimitEnabled)
{
return;
}
var now = timeProvider.GetUtcNow(); var now = timeProvider.GetUtcNow();
if (!IsLimitActive) if (!IsLimitActive)
{ {
TryEnforce(currentPowerWatts, now); TryEnforce(currentPowerWatts, now);
return; return;
} }
@@ -43,6 +51,7 @@ public sealed class PowerLimitEnforcementService(
if (IsLimitActive) if (IsLimitActive)
{ {
logger.LogInformation("Debug: trigger requested but limit already active"); logger.LogInformation("Debug: trigger requested but limit already active");
return; return;
} }
@@ -55,6 +64,7 @@ public sealed class PowerLimitEnforcementService(
if (!IsLimitActive) if (!IsLimitActive)
{ {
logger.LogInformation("Debug: reset requested but limit not active"); logger.LogInformation("Debug: reset requested but limit not active");
return; return;
} }
@@ -64,9 +74,15 @@ public sealed class PowerLimitEnforcementService(
private void ExecuteEnforce(double currentPowerWatts) private void ExecuteEnforce(double currentPowerWatts)
{ {
foreach (var entityId in _options.EnforceSwitchOffEntityIds) TurnOff(entityId); foreach (var entityId in _options.EnforceSwitchOffEntityIds)
{
TurnOff(entityId);
}
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOff(entityId); foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOff(entityId);
}
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts); NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
@@ -78,7 +94,10 @@ public sealed class PowerLimitEnforcementService(
private void ExecuteRecover() private void ExecuteRecover()
{ {
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId); foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification(); DismissLimitNotification();
@@ -88,7 +107,10 @@ public sealed class PowerLimitEnforcementService(
private void TryEnforce(double currentPowerWatts, DateTimeOffset now) private void TryEnforce(double currentPowerWatts, DateTimeOffset now)
{ {
if (currentPowerWatts <= _options.PowerLimitWatts) return; if (currentPowerWatts <= _options.PowerLimitWatts)
{
return;
}
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds)) if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
{ {
@@ -112,12 +134,16 @@ public sealed class PowerLimitEnforcementService(
{ {
var elapsed = now - _enforcedAt; var elapsed = now - _enforcedAt;
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds)) return; if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds))
{
return;
}
if (currentPowerWatts >= _options.PowerLimitWatts) if (currentPowerWatts >= _options.PowerLimitWatts)
{ {
logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced", logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced",
currentPowerWatts, _options.PowerLimitWatts); currentPowerWatts, _options.PowerLimitWatts);
_enforcedAt = now; _enforcedAt = now;
return; return;
@@ -130,7 +156,10 @@ public sealed class PowerLimitEnforcementService(
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds); currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
} }
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId); foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification(); DismissLimitNotification();
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using HomeAssistant.Entities.Interfaces; using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
public sealed class PowerMonitorEntityService( public sealed class PowerMonitorEntityService(
@@ -44,6 +48,7 @@ public sealed class PowerMonitorEntityService(
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
var entities = GetSystemEntitiesList(); var entities = GetSystemEntitiesList();
var tasks = entities.Select(async entity => var tasks = entities.Select(async entity =>
{ {
try try
@@ -70,6 +75,7 @@ public sealed class PowerMonitorEntityService(
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
var entities = sensors.SelectMany(GetPowerDeviceEntitiesNames).ToList(); var entities = sensors.SelectMany(GetPowerDeviceEntitiesNames).ToList();
var tasks = entities.Select(async entity => var tasks = entities.Select(async entity =>
{ {
try try
@@ -123,12 +129,16 @@ public sealed class PowerMonitorEntityService(
foreach (var (entityId, costSnapshot) in context.DeviceCosts) foreach (var (entityId, costSnapshot) in context.DeviceCosts)
{ {
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(entityId); var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(entityId);
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min, tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min,
costSnapshot, $"{deviceName} cost (15 min)", timestamp)); costSnapshot, $"{deviceName} cost (15 min)", timestamp));
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour, tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour,
costSnapshot, $"{deviceName} cost (1h)", timestamp)); costSnapshot, $"{deviceName} cost (1h)", timestamp));
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily, tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily,
costSnapshot, $"{deviceName} cost (daily)", timestamp)); costSnapshot, $"{deviceName} cost (daily)", timestamp));
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly, tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly,
costSnapshot, $"{deviceName} cost (monthly)", timestamp)); costSnapshot, $"{deviceName} cost (monthly)", timestamp));
} }
@@ -175,6 +185,7 @@ public sealed class PowerMonitorEntityService(
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Error cleaning up PowerMonitor entities"); logger.LogError(ex, "Error cleaning up PowerMonitor entities");
throw; throw;
} }
} }
@@ -192,7 +203,10 @@ public sealed class PowerMonitorEntityService(
{ {
await entityManager.RemoveEntity(id).ConfigureAwait(false); await entityManager.RemoveEntity(id).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Entity removed: {EntityId}", id); if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Entity removed: {EntityId}", id);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -203,12 +217,11 @@ public sealed class PowerMonitorEntityService(
await Task.WhenAll(tasks).ConfigureAwait(false); await Task.WhenAll(tasks).ConfigureAwait(false);
} }
internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList() internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList()
{ {
return new List<PowerMonitorEntity> return new List<PowerMonitorEntity>
{ {
new("sensor", "powermonitor_total_power", "PowerMonitor total power") new PowerMonitorEntity("sensor", "powermonitor_total_power", "PowerMonitor total power")
{ {
AdditionalConfig = new AdditionalConfig = new
{ {
@@ -221,7 +234,7 @@ public sealed class PowerMonitorEntityService(
CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"), CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"),
CreateCostEntity("powermonitor_total_cost_daily", "PowerMonitor total cost (daily)"), CreateCostEntity("powermonitor_total_cost_daily", "PowerMonitor total cost (daily)"),
CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"), CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"),
new("sensor", "powermonitor_other_power", "PowerMonitor other power") new PowerMonitorEntity("sensor", "powermonitor_other_power", "PowerMonitor other power")
{ {
AdditionalConfig = new AdditionalConfig = new
{ {
@@ -234,13 +247,13 @@ public sealed class PowerMonitorEntityService(
CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"), CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"),
CreateCostEntity("powermonitor_other_cost_daily", "PowerMonitor other cost (daily)"), CreateCostEntity("powermonitor_other_cost_daily", "PowerMonitor other cost (daily)"),
CreateCostEntity("powermonitor_other_cost_monthly", "PowerMonitor other cost (monthly)"), CreateCostEntity("powermonitor_other_cost_monthly", "PowerMonitor other cost (monthly)"),
new("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"), new PowerMonitorEntity("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"),
new("sensor", "powermonitor_status", "PowerMonitor status"), new PowerMonitorEntity("sensor", "powermonitor_status", "PowerMonitor status"),
new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors") new PowerMonitorEntity("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
{ {
AdditionalConfig = new { icon = "mdi:refresh" } AdditionalConfig = new { icon = "mdi:refresh" }
}, },
new("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)") new PowerMonitorEntity("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
{ {
AdditionalConfig = new { icon = "mdi:flash-alert" } AdditionalConfig = new { icon = "mdi:flash-alert" }
} }
@@ -263,6 +276,7 @@ public sealed class PowerMonitorEntityService(
internal static IEnumerable<PowerMonitorEntity> GetPowerDeviceEntitiesNames(PowerSensorInfo sensor) internal static IEnumerable<PowerMonitorEntity> GetPowerDeviceEntitiesNames(PowerSensorInfo sensor)
{ {
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId); var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId);
return return
[ [
CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"), CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"),
@@ -287,6 +301,7 @@ public sealed class PowerMonitorEntityService(
{ {
var value = context.Calculation.TotalPowerWatts.ToString("F1", CultureInfo.InvariantCulture); var value = context.Calculation.TotalPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
await SetEntityStateSafe(TotalPowerEntityId, value).ConfigureAwait(false); await SetEntityStateSafe(TotalPowerEntityId, value).ConfigureAwait(false);
await SetEntityAttributesSafe(TotalPowerEntityId, new await SetEntityAttributesSafe(TotalPowerEntityId, new
{ {
unit_of_measurement = PowerMonitorConsts.WattUnit, unit_of_measurement = PowerMonitorConsts.WattUnit,
@@ -294,13 +309,15 @@ public sealed class PowerMonitorEntityService(
state_class = PowerMonitorConsts.MeasurementStateClass, state_class = PowerMonitorConsts.MeasurementStateClass,
friendly_name = "PowerMonitor total power", friendly_name = "PowerMonitor total power",
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateOtherPowerAsync(PowerUpdateContext context, string timestamp) private async Task UpdateOtherPowerAsync(PowerUpdateContext context, string timestamp)
{ {
var value = context.Calculation.SmoothedOtherPowerWatts.ToString("F1", CultureInfo.InvariantCulture); var value = context.Calculation.SmoothedOtherPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
await SetEntityStateSafe(OtherPowerEntityId, value).ConfigureAwait(false); await SetEntityStateSafe(OtherPowerEntityId, value).ConfigureAwait(false);
await SetEntityAttributesSafe(OtherPowerEntityId, new await SetEntityAttributesSafe(OtherPowerEntityId, new
{ {
unit_of_measurement = PowerMonitorConsts.WattUnit, unit_of_measurement = PowerMonitorConsts.WattUnit,
@@ -311,14 +328,19 @@ public sealed class PowerMonitorEntityService(
smoothed_power = context.Calculation.SmoothedOtherPowerWatts, smoothed_power = context.Calculation.SmoothedOtherPowerWatts,
data_quality = context.Calculation.DataQuality, data_quality = context.Calculation.DataQuality,
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateCostEntityAsync(string entityId, double costValue, CostSnapshot snapshot, private async Task UpdateCostEntityAsync(string entityId,
string friendlyName, string timestamp) double costValue,
CostSnapshot snapshot,
string friendlyName,
string timestamp)
{ {
var value = costValue.ToString("F4", CultureInfo.InvariantCulture); var value = costValue.ToString("F4", CultureInfo.InvariantCulture);
await SetEntityStateSafe(entityId, value).ConfigureAwait(false); await SetEntityStateSafe(entityId, value).ConfigureAwait(false);
await SetEntityAttributesSafe(entityId, new await SetEntityAttributesSafe(entityId, new
{ {
unit_of_measurement = PowerMonitorConsts.EurUnit, unit_of_measurement = PowerMonitorConsts.EurUnit,
@@ -327,13 +349,15 @@ public sealed class PowerMonitorEntityService(
friendly_name = friendlyName, friendly_name = friendlyName,
partial_window = snapshot.PartialWindow, partial_window = snapshot.PartialWindow,
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateAnomalyAsync(PowerUpdateContext context, string timestamp) private async Task UpdateAnomalyAsync(PowerUpdateContext context, string timestamp)
{ {
var state = context.IsAnomaly ? "on" : "off"; var state = context.IsAnomaly ? "on" : "off";
await SetEntityStateSafe(AnomalyEntityId, state).ConfigureAwait(false); await SetEntityStateSafe(AnomalyEntityId, state).ConfigureAwait(false);
await SetEntityAttributesSafe(AnomalyEntityId, new await SetEntityAttributesSafe(AnomalyEntityId, new
{ {
friendly_name = "PowerMonitor anomaly", friendly_name = "PowerMonitor anomaly",
@@ -341,12 +365,14 @@ public sealed class PowerMonitorEntityService(
threshold = context.AnomalyThresholdWatts, threshold = context.AnomalyThresholdWatts,
duration_above = context.AnomalyDuration.TotalSeconds, duration_above = context.AnomalyDuration.TotalSeconds,
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
private async Task UpdateStatusAsync(PowerUpdateContext context, string timestamp) private async Task UpdateStatusAsync(PowerUpdateContext context, string timestamp)
{ {
await SetEntityStateSafe(StatusEntityId, context.SystemStatus).ConfigureAwait(false); await SetEntityStateSafe(StatusEntityId, context.SystemStatus).ConfigureAwait(false);
await SetEntityAttributesSafe(StatusEntityId, new await SetEntityAttributesSafe(StatusEntityId, new
{ {
friendly_name = "PowerMonitor status", friendly_name = "PowerMonitor status",
@@ -356,7 +382,8 @@ public sealed class PowerMonitorEntityService(
current_price = context.CurrentNordPoolPrice, current_price = context.CurrentNordPoolPrice,
price_unit = context.PriceUnit, price_unit = context.PriceUnit,
last_updated = timestamp last_updated = timestamp
}).ConfigureAwait(false); })
.ConfigureAwait(false);
} }
internal async Task SetEntityStateSafe(string entityId, string state) internal async Task SetEntityStateSafe(string entityId, string state)
+36 -7
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization; using System.Globalization;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -10,6 +12,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
[NetDaemonApp] [NetDaemonApp]
@@ -108,6 +112,7 @@ public sealed class PowerMonitorInit
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error initializing PowerMonitor"); _logger.LogError(ex, "Error initializing PowerMonitor");
throw; throw;
} }
} }
@@ -129,14 +134,19 @@ public sealed class PowerMonitorInit
if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId)) if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId))
{ {
_logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes"); _logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes");
return; return;
} }
var meter = new Entity(_haContext, _options.MainMeterEntityId); var meter = new Entity(_haContext, _options.MainMeterEntityId);
meter.StateChanges() meter.StateChanges()
.Subscribe(e => .Subscribe(e =>
{ {
if (e.Old?.State == e.New?.State) return; if (e.Old?.State == e.New?.State)
{
return;
}
_ = PollAndUpdateAsync(); _ = PollAndUpdateAsync();
}); });
@@ -150,6 +160,7 @@ public sealed class PowerMonitorInit
private void SubscribeToRediscoverButton() private void SubscribeToRediscoverButton()
{ {
var button = new Entity(_haContext, "button.powermonitor_rediscover_sensors"); var button = new Entity(_haContext, "button.powermonitor_rediscover_sensors");
button.StateChanges() button.StateChanges()
.Subscribe(change => .Subscribe(change =>
{ {
@@ -161,6 +172,7 @@ public sealed class PowerMonitorInit
private void SubscribeToLimitBreachDebugButton() private void SubscribeToLimitBreachDebugButton()
{ {
var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach"); var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach");
button.StateChanges() button.StateChanges()
.Subscribe(_ => .Subscribe(_ =>
{ {
@@ -193,13 +205,17 @@ public sealed class PowerMonitorInit
if (added.Count > 0) if (added.Count > 0)
{ {
await _entityService.CreateDeviceEntitiesAsync(added); await _entityService.CreateDeviceEntitiesAsync(added);
if (_logger.IsEnabled(LogLevel.Information)) if (_logger.IsEnabled(LogLevel.Information))
{ {
_logger.LogInformation("Created entities for {Count} new sensors", added.Count); _logger.LogInformation("Created entities for {Count} new sensors", added.Count);
} }
} }
if (removed.Count > 0) await RemoreDevicePriceEntities(removed); if (removed.Count > 0)
{
await RemoreDevicePriceEntities(removed);
}
if (_logger.IsEnabled(LogLevel.Information)) if (_logger.IsEnabled(LogLevel.Information))
{ {
@@ -229,9 +245,11 @@ public sealed class PowerMonitorInit
try try
{ {
var totalPower = ReadMainMeterPower(); var totalPower = ReadMainMeterPower();
if (totalPower is null) if (totalPower is null)
{ {
_mainMeterConsecutiveFailures++; _mainMeterConsecutiveFailures++;
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, _logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures,
PowerMonitorConsts.MainMeterMaxConsecutiveFailures); PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
@@ -253,6 +271,7 @@ public sealed class PowerMonitorInit
var elapsedSeconds = _lastPollTimestamp.HasValue var elapsedSeconds = _lastPollTimestamp.HasValue
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10) ? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
: _options.PollIntervalSeconds; : _options.PollIntervalSeconds;
_lastPollTimestamp = now; _lastPollTimestamp = now;
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime); _costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
@@ -261,9 +280,7 @@ public sealed class PowerMonitorInit
_anomalyStartTime = isAnomaly switch _anomalyStartTime = isAnomaly switch
{ {
true when _anomalyStartTime is null => now, true when _anomalyStartTime is null => now, false => null, _ => _anomalyStartTime
false => null,
_ => _anomalyStartTime
}; };
var anomalyDuration = _anomalyStartTime.HasValue var anomalyDuration = _anomalyStartTime.HasValue
@@ -318,10 +335,14 @@ public sealed class PowerMonitorInit
if (state?.State is null or "unavailable" or "unknown") if (state?.State is null or "unavailable" or "unknown")
{ {
_logger.LogDebug("NordPool price entity unavailable, using last known price"); _logger.LogDebug("NordPool price entity unavailable, using last known price");
return 0; return 0;
} }
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) return price; if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0)
{
return price;
}
if (_logger.IsEnabled(LogLevel.Debug)) if (_logger.IsEnabled(LogLevel.Debug))
{ {
@@ -340,11 +361,13 @@ public sealed class PowerMonitorInit
case (true, false): case (true, false):
_notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts);
_highPowerNotificationActive = true; _highPowerNotificationActive = true;
break; break;
case (false, true): case (false, true):
_notificationService.DismissHighPowerNotification(); _notificationService.DismissHighPowerNotification();
_highPowerNotificationActive = false; _highPowerNotificationActive = false;
break; break;
} }
} }
@@ -352,7 +375,11 @@ public sealed class PowerMonitorInit
private double? ReadMainMeterPower() private double? ReadMainMeterPower()
{ {
var state = _haContext.GetState(_options.MainMeterEntityId); var state = _haContext.GetState(_options.MainMeterEntityId);
if (state?.State is null or "unavailable" or "unknown") return null;
if (state?.State is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
? value ? value
@@ -367,10 +394,12 @@ public sealed class PowerMonitorInit
foreach (var sensor in _discoveryService.CurrentDeviceSensors) foreach (var sensor in _discoveryService.CurrentDeviceSensors)
{ {
var state = _haContext.GetState(sensor.EntityId); var state = _haContext.GetState(sensor.EntityId);
if (state?.State is null or "unavailable" or "unknown") if (state?.State is null or "unavailable" or "unknown")
{ {
readings[sensor.EntityId] = 0; readings[sensor.EntityId] = 0;
degraded.Add(sensor.EntityId); degraded.Add(sensor.EntityId);
continue; continue;
} }
@@ -1,7 +1,11 @@
#region
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using PowerMonitorManager.Interface; using PowerMonitorManager.Interface;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
public static class PowerMonitorServiceRegistration public static class PowerMonitorServiceRegistration
@@ -1,9 +1,13 @@
#region
using System.Globalization; using System.Globalization;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using PowerMonitorManager.Interface; using PowerMonitorManager.Interface;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
public sealed class PowerNotificationService( public sealed class PowerNotificationService(
@@ -1,3 +1,5 @@
#region
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -9,6 +11,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager; namespace PowerMonitorManager;
public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
@@ -64,10 +68,17 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
internal static bool IsPowerSensor(Entity entity) internal static bool IsPowerSensor(Entity entity)
{ {
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) return false; if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase))
{
return false;
}
var attributes = entity.EntityState?.AttributesJson; var attributes = entity.EntityState?.AttributesJson;
if (attributes is null) return false;
if (attributes is null)
{
return false;
}
var deviceClass = GetJsonStringProperty(attributes.Value, "device_class"); var deviceClass = GetJsonStringProperty(attributes.Value, "device_class");
var unit = GetJsonStringProperty(attributes.Value, "unit_of_measurement"); var unit = GetJsonStringProperty(attributes.Value, "unit_of_measurement");
@@ -101,18 +112,23 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
private static string GetFriendlyName(Entity entity) private static string GetFriendlyName(Entity entity)
{ {
var name = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name"); var name = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name");
return name ?? entity.EntityId; return name ?? entity.EntityId;
} }
private static string GetUnitOfMeasurement(Entity entity) private static string GetUnitOfMeasurement(Entity entity)
{ {
var unit = GetJsonStringProperty(entity.EntityState?.AttributesJson, "unit_of_measurement"); var unit = GetJsonStringProperty(entity.EntityState?.AttributesJson, "unit_of_measurement");
return unit ?? PowerMonitorConsts.WattUnit; return unit ?? PowerMonitorConsts.WattUnit;
} }
private static string? GetJsonStringProperty(JsonElement? element, string propertyName) private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
{ {
if (element is null) return null; if (element is null)
{
return null;
}
return element.Value.TryGetProperty(propertyName, out var value) return element.Value.TryGetProperty(propertyName, out var value)
? value.GetString() ? value.GetString()
@@ -122,6 +138,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
internal static Regex GlobToRegex(string globPattern) internal static Regex GlobToRegex(string globPattern)
{ {
var regexPattern = "^" + Regex.Escape(globPattern).Replace("\\*", ".*") + "$"; var regexPattern = "^" + Regex.Escape(globPattern).Replace("\\*", ".*") + "$";
return new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); return new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
} }
} }
@@ -1,6 +1,10 @@
#region
using HomeAssistant.Models; using HomeAssistant.Models;
using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace PowerMonitor.Models; namespace PowerMonitor.Models;
public class PowerMonitorEntity : EntityCreateModel public class PowerMonitorEntity : EntityCreateModel
@@ -1,3 +1,5 @@
#region
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.Extensions.Time.Testing; using Microsoft.Extensions.Time.Testing;
@@ -8,6 +10,8 @@ using ShowerMonitor.Models.Enums;
using ShowerMonitorManager; using ShowerMonitorManager;
using ShowerMonitorManager.Models; using ShowerMonitorManager.Models;
#endregion
namespace ShowerMonitor.Manager.Tests; namespace ShowerMonitor.Manager.Tests;
public class ExhaustFanControlServiceTests public class ExhaustFanControlServiceTests
@@ -15,19 +19,19 @@ public class ExhaustFanControlServiceTests
private const string FanEntityId = "switch.exhaust_fan"; private const string FanEntityId = "switch.exhaust_fan";
private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions(); private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new(); private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider(); private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider();
private DateTimeOffset Now => _timeProvider.GetUtcNow(); private DateTimeOffset Now => _timeProvider.GetUtcNow();
public static TheoryData<string, ShowerState, string?, bool> ShowerProgressFanStateCases => new() public static TheoryData<string, ShowerState, string?, bool> ShowerProgressFanStateCases => new TheoryData<string, ShowerState, string?, bool>
{ {
{ "active while fan is off", ShowerState.Active, "off", true }, { "active while fan is off", ShowerState.Active, "off", true },
{ "active while fan is on", ShowerState.Active, "on", false }, { "active while fan is on", ShowerState.Active, "on", false },
{ "active while fan reports uppercase on", ShowerState.Active, "ON", false }, { "active while fan reports uppercase on", ShowerState.Active, "ON", false },
{ "active while fan is unavailable", ShowerState.Active, "unavailable", true }, { "active while fan is unavailable", ShowerState.Active, "unavailable", true },
{ "active while fan state is unknown", ShowerState.Active, "unknown", true }, { "active while fan state is unknown", ShowerState.Active, "unknown", true },
{ "active while fan state is empty", ShowerState.Active, "", true }, { "active while fan state is empty", ShowerState.Active, string.Empty, true },
{ "active while fan state is missing", ShowerState.Active, null, true }, { "active while fan state is missing", ShowerState.Active, null, true },
{ "suspected while fan is off", ShowerState.Suspected, "off", true }, { "suspected while fan is off", ShowerState.Suspected, "off", true },
{ "suspected while fan is on", ShowerState.Suspected, "on", false }, { "suspected while fan is on", ShowerState.Suspected, "on", false },
@@ -36,7 +40,7 @@ public class ExhaustFanControlServiceTests
{ "completed does not turn the fan on", ShowerState.Completed, "off", false } { "completed does not turn the fan on", ShowerState.Completed, "off", false }
}; };
public static TheoryData<string, int, int, bool> FanRunAfterCases => new() public static TheoryData<string, int, int, bool> FanRunAfterCases => new TheoryData<string, int, int, bool>
{ {
{ "well before run-after duration", 10, 60, false }, { "well before run-after duration", 10, 60, false },
{ "one second before run-after duration", 10, 599, false }, { "one second before run-after duration", 10, 599, false },
@@ -47,7 +51,7 @@ public class ExhaustFanControlServiceTests
{ "long run-after keeps fan running", 30, 300, false } { "long run-after keeps fan running", 30, 300, false }
}; };
public static TheoryData<string, bool, string?, bool> ResetCases => new() public static TheoryData<string, bool, string?, bool> ResetCases => new TheoryData<string, bool, string?, bool>
{ {
{ "fan on after we turned it on", true, "on", true }, { "fan on after we turned it on", true, "on", true },
{ "fan reports uppercase on", true, "ON", true }, { "fan reports uppercase on", true, "ON", true },
@@ -83,8 +87,10 @@ public class ExhaustFanControlServiceTests
bool expectTurnOff) bool expectTurnOff)
{ {
SetupFanState("off"); SetupFanState("off");
var service = CreateService(ShowerMonitorTestData.CreateOptions( var service = CreateService(ShowerMonitorTestData.CreateOptions(
fanRunAfterShowerMinutes: runAfterMinutes)); fanRunAfterShowerMinutes: runAfterMinutes));
var showerEnd = Now.AddMinutes(5); var showerEnd = Now.AddMinutes(5);
service.Evaluate(ShowerState.Active, Now); service.Evaluate(ShowerState.Active, Now);
@@ -263,18 +269,15 @@ public class ExhaustFanControlServiceTests
string? because = null) string? because = null)
{ {
var targets = _haContextMock.Invocations var targets = _haContextMock.Invocations
.Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService) .Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService) && (string?)invocation.Arguments[0] == "switch" && (string?)invocation.Arguments[1] == service)
&& (string?)invocation.Arguments[0] == "switch"
&& (string?)invocation.Arguments[1] == service)
.Select(invocation => (ServiceTarget?)invocation.Arguments[2]) .Select(invocation => (ServiceTarget?)invocation.Arguments[2])
.ToList(); .ToList();
targets.Should().HaveCount(expectedCount, because); targets.Should().HaveCount(expectedCount, because);
targets.Should().OnlyContain(
target => target != null targets.Should()
&& target.EntityIds != null .OnlyContain(
&& target.EntityIds.Count == 1 target => target != null && target.EntityIds != null && target.EntityIds.Count == 1 && target.EntityIds.Single() == expectedEntityId,
&& target.EntityIds.Single() == expectedEntityId,
because); because);
} }
} }
@@ -1,8 +1,12 @@
#region
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Time.Testing; using Microsoft.Extensions.Time.Testing;
using ShowerMonitor.Models; using ShowerMonitor.Models;
using ShowerMonitorManager; using ShowerMonitorManager;
#endregion
namespace ShowerMonitor.Manager.Tests; namespace ShowerMonitor.Manager.Tests;
public class HumidityRateCalculatorTests public class HumidityRateCalculatorTests
@@ -13,7 +17,7 @@ public class HumidityRateCalculatorTests
private DateTimeOffset Now => _timeProvider.GetUtcNow(); private DateTimeOffset Now => _timeProvider.GetUtcNow();
public static TheoryData<string, int, double[], int[], double> RateCases => new() public static TheoryData<string, int, double[], int[], double> RateCases => new TheoryData<string, int, double[], int[], double>
{ {
{ "no readings", 5, [], [], 0.0 }, { "no readings", 5, [], [], 0.0 },
{ "single reading", 5, [52.9], [0], 0.0 }, { "single reading", 5, [52.9], [0], 0.0 },
@@ -49,7 +53,9 @@ public class HumidityRateCalculatorTests
var calculator = new HumidityRateCalculator(windowSize); var calculator = new HumidityRateCalculator(windowSize);
for (var i = 0; i < humidities.Length; i++) for (var i = 0; i < humidities.Length; i++)
{
calculator.RecordReading(humidities[i], Now.AddSeconds(offsetSeconds[i])); calculator.RecordReading(humidities[i], Now.AddSeconds(offsetSeconds[i]));
}
calculator.GetRatePerMinute().Should().BeApproximately(expectedRate, 1e-6, $"scenario: {scenario}"); calculator.GetRatePerMinute().Should().BeApproximately(expectedRate, 1e-6, $"scenario: {scenario}");
} }
@@ -58,6 +64,7 @@ public class HumidityRateCalculatorTests
public void GetRatePerMinute_WithGeneratedLinearSeries_ReturnsSlopeForEveryWindowSize() public void GetRatePerMinute_WithGeneratedLinearSeries_ReturnsSlopeForEveryWindowSize()
{ {
const double ratePerMinute = 2.5; const double ratePerMinute = 2.5;
var series = ShowerMonitorTestData.CreateLinearHumiditySeries( var series = ShowerMonitorTestData.CreateLinearHumiditySeries(
45.0, 45.0,
ratePerMinute, ratePerMinute,
@@ -67,7 +74,10 @@ public class HumidityRateCalculatorTests
{ {
var calculator = new HumidityRateCalculator(windowSize); var calculator = new HumidityRateCalculator(windowSize);
foreach (var sample in series) calculator.RecordReading(sample.Humidity, Now + sample.Offset); foreach (var sample in series)
{
calculator.RecordReading(sample.Humidity, Now + sample.Offset);
}
calculator.GetRatePerMinute() calculator.GetRatePerMinute()
.Should() .Should()

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