Apply code formatting cleanup across monitor projects
- Reindent appsettings.json and the MSBuild project files - Collapse single-statement guard blocks and tidy using and member order - Normalize XML doc indentation and file endings - Reorder BatteryMonitor test-data helpers and move the exclusion tests into their own region - Carry the same formatting through the boiler config, control, entity and test files
This commit is contained in:
@@ -16,139 +16,6 @@ internal static class BatteryMonitorTestData
|
|||||||
{
|
{
|
||||||
private const string DefaultFriendlyName = "Battery Device";
|
private const string DefaultFriendlyName = "Battery Device";
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities"/>.
|
|
||||||
/// </summary>
|
|
||||||
public sealed record EntitySpec
|
|
||||||
{
|
|
||||||
public required string EntityId { get; init; }
|
|
||||||
|
|
||||||
public string? State { get; init; } = "50";
|
|
||||||
|
|
||||||
public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
|
|
||||||
|
|
||||||
public string? FriendlyName { get; init; } = DefaultFriendlyName;
|
|
||||||
|
|
||||||
/// <summary>When false the context returns no <see cref="EntityState"/> for the entity.</summary>
|
|
||||||
public bool HasState { get; init; } = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>A battery device-class sensor.</summary>
|
|
||||||
public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
|
|
||||||
{
|
|
||||||
return new EntitySpec
|
|
||||||
{
|
|
||||||
EntityId = entityId,
|
|
||||||
State = state,
|
|
||||||
FriendlyName = friendlyName
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
|
|
||||||
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, string? friendlyName = DefaultFriendlyName)
|
|
||||||
{
|
|
||||||
return new EntitySpec
|
|
||||||
{
|
|
||||||
EntityId = entityId,
|
|
||||||
DeviceClass = deviceClass,
|
|
||||||
State = state,
|
|
||||||
FriendlyName = friendlyName
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public static EntityState CreateEntityState(EntitySpec spec)
|
|
||||||
{
|
|
||||||
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
|
|
||||||
|
|
||||||
if (spec.DeviceClass is not null)
|
|
||||||
{
|
|
||||||
attributes["device_class"] = spec.DeviceClass;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (spec.FriendlyName is not null)
|
|
||||||
{
|
|
||||||
attributes["friendly_name"] = spec.FriendlyName;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new EntityState
|
|
||||||
{
|
|
||||||
State = spec.State,
|
|
||||||
AttributesJson = JsonSerializer.SerializeToElement(attributes)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Wires <see cref="IHaContext.GetState"/> and <see cref="IHaContext.GetAllEntities"/>
|
|
||||||
/// on the mock, exposing the entities in declaration order.
|
|
||||||
/// </summary>
|
|
||||||
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
|
|
||||||
{
|
|
||||||
var entityList = new List<Entity>(entities.Length);
|
|
||||||
|
|
||||||
foreach (var spec in entities)
|
|
||||||
{
|
|
||||||
if (spec.HasState)
|
|
||||||
{
|
|
||||||
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
|
|
||||||
}
|
|
||||||
|
|
||||||
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
|
|
||||||
}
|
|
||||||
|
|
||||||
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
|
|
||||||
{
|
|
||||||
return new BatterySensorInfo
|
|
||||||
{
|
|
||||||
EntityId = entityId,
|
|
||||||
FriendlyName = friendlyName ?? entityId,
|
|
||||||
BatteryLevel = batteryLevel
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
|
|
||||||
{
|
|
||||||
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
|
|
||||||
{
|
|
||||||
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Generates battery sensors with every integer level in <c>0..count-1</c>.
|
|
||||||
/// </summary>
|
|
||||||
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
|
|
||||||
{
|
|
||||||
return
|
|
||||||
[
|
|
||||||
.. Enumerable.Range(0, count)
|
|
||||||
.Select(i => Battery(
|
|
||||||
$"sensor.generated_battery_{i:D3}",
|
|
||||||
i.ToString(CultureInfo.InvariantCulture),
|
|
||||||
$"Generated Battery {i:D3}"))
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Generates notification devices with deterministic, non-monotonic levels so
|
|
||||||
/// ordering behaviour is exercised over more than a handful of rows.
|
|
||||||
/// </summary>
|
|
||||||
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
|
|
||||||
{
|
|
||||||
return
|
|
||||||
[
|
|
||||||
.. Enumerable.Range(0, count)
|
|
||||||
.Select(i => CreateSensorInfo(
|
|
||||||
$"sensor.generated_{i:D3}",
|
|
||||||
i * 37 % 101,
|
|
||||||
$"Generated Device {i:D3}"))
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// (threshold, state, expected) rows straddling the strict <c>level < threshold</c>
|
/// (threshold, state, expected) rows straddling the strict <c>level < threshold</c>
|
||||||
/// boundary, including zero/negative thresholds and int min/max thresholds.
|
/// boundary, including zero/negative thresholds and int min/max thresholds.
|
||||||
@@ -203,6 +70,118 @@ internal static class BatteryMonitorTestData
|
|||||||
null
|
null
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// <summary>Device counts used to exercise notification payload generation.</summary>
|
||||||
|
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
|
||||||
|
|
||||||
|
/// <summary>A battery device-class sensor.</summary>
|
||||||
|
public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
|
||||||
|
{
|
||||||
|
return new EntitySpec
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
State = state,
|
||||||
|
FriendlyName = friendlyName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
|
||||||
|
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state,
|
||||||
|
string? friendlyName = DefaultFriendlyName)
|
||||||
|
{
|
||||||
|
return new EntitySpec
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
DeviceClass = deviceClass,
|
||||||
|
State = state,
|
||||||
|
FriendlyName = friendlyName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateEntityState(EntitySpec spec)
|
||||||
|
{
|
||||||
|
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass;
|
||||||
|
|
||||||
|
if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName;
|
||||||
|
|
||||||
|
return new EntityState
|
||||||
|
{
|
||||||
|
State = spec.State,
|
||||||
|
AttributesJson = JsonSerializer.SerializeToElement(attributes)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wires <see cref="IHaContext.GetState" /> and <see cref="IHaContext.GetAllEntities" />
|
||||||
|
/// on the mock, exposing the entities in declaration order.
|
||||||
|
/// </summary>
|
||||||
|
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
|
||||||
|
{
|
||||||
|
var entityList = new List<Entity>(entities.Length);
|
||||||
|
|
||||||
|
foreach (var spec in entities)
|
||||||
|
{
|
||||||
|
if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
|
||||||
|
|
||||||
|
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
|
||||||
|
}
|
||||||
|
|
||||||
|
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
|
||||||
|
{
|
||||||
|
return new BatterySensorInfo
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
FriendlyName = friendlyName ?? entityId,
|
||||||
|
BatteryLevel = batteryLevel
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
|
||||||
|
{
|
||||||
|
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<BatterySensorInfo> CreateSensorInfos(
|
||||||
|
params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
|
||||||
|
{
|
||||||
|
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates battery sensors with every integer level in <c>0..count-1</c>.
|
||||||
|
/// </summary>
|
||||||
|
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count)
|
||||||
|
.Select(i => Battery(
|
||||||
|
$"sensor.generated_battery_{i:D3}",
|
||||||
|
i.ToString(CultureInfo.InvariantCulture),
|
||||||
|
$"Generated Battery {i:D3}"))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates notification devices with deterministic, non-monotonic levels so
|
||||||
|
/// ordering behaviour is exercised over more than a handful of rows.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count)
|
||||||
|
.Select(i => CreateSensorInfo(
|
||||||
|
$"sensor.generated_{i:D3}",
|
||||||
|
i * 37 % 101,
|
||||||
|
$"Generated Device {i:D3}"))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Cross-product of every excluded keyword (lower and upper case) plus
|
/// Cross-product of every excluded keyword (lower and upper case) plus
|
||||||
/// non-excluded look-alikes that must not be filtered.
|
/// non-excluded look-alikes that must not be filtered.
|
||||||
@@ -229,6 +208,20 @@ internal static class BatteryMonitorTestData
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Device counts used to exercise notification payload generation.</summary>
|
/// <summary>
|
||||||
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
|
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities" />.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record EntitySpec
|
||||||
|
{
|
||||||
|
public required string EntityId { get; init; }
|
||||||
|
|
||||||
|
public string? State { get; init; } = "50";
|
||||||
|
|
||||||
|
public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
|
||||||
|
|
||||||
|
public string? FriendlyName { get; init; } = DefaultFriendlyName;
|
||||||
|
|
||||||
|
/// <summary>When false the context returns no <see cref="EntityState" /> for the entity.</summary>
|
||||||
|
public bool HasState { get; init; } = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitor.Models;
|
|
||||||
using BatteryMonitorManager;
|
|
||||||
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
|
|
||||||
namespace BatteryMonitor.Manager.Tests;
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
@@ -139,10 +139,7 @@ public class BatteryNotificationServiceTests
|
|||||||
{
|
{
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
for (var i = 0; i < calls; i++)
|
for (var i = 0; i < calls; i++) sut.DismissNotification();
|
||||||
{
|
|
||||||
sut.DismissNotification();
|
|
||||||
}
|
|
||||||
|
|
||||||
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
|
||||||
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
||||||
@@ -222,7 +219,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, string expectedLine)
|
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel,
|
||||||
|
string expectedLine)
|
||||||
{
|
{
|
||||||
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
|
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitor.Models;
|
|
||||||
using BatteryMonitorManager;
|
|
||||||
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
|
|
||||||
namespace BatteryMonitor.Manager.Tests;
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
@@ -25,6 +25,17 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
ConfigureHaContext(_haContextMock, entities);
|
ConfigureHaContext(_haContextMock, entities);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#region IsExcludedDevice
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
|
||||||
|
{
|
||||||
|
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region Discovery
|
#region Discovery
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -77,7 +88,8 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
[InlineData("sensor.no_device_class", null)]
|
[InlineData("sensor.no_device_class", null)]
|
||||||
[InlineData("sensorx.bathroom_battery", "battery")]
|
[InlineData("sensorx.bathroom_battery", "battery")]
|
||||||
[InlineData("switch.bathroom_battery", "battery")]
|
[InlineData("switch.bathroom_battery", "battery")]
|
||||||
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId, string? deviceClass)
|
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId,
|
||||||
|
string? deviceClass)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
|
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
|
||||||
@@ -111,7 +123,8 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
|
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
new EntitySpec { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
|
new EntitySpec
|
||||||
|
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
|
||||||
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -124,7 +137,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, bool expectedIncluded)
|
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state,
|
||||||
|
bool expectedIncluded)
|
||||||
{
|
{
|
||||||
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
|
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
|
||||||
|
|
||||||
@@ -133,10 +147,7 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
|
|
||||||
result.Should().HaveCount(expectedIncluded ? 1 : 0);
|
result.Should().HaveCount(expectedIncluded ? 1 : 0);
|
||||||
|
|
||||||
if (!expectedIncluded)
|
if (!expectedIncluded) return;
|
||||||
{
|
|
||||||
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));
|
||||||
@@ -239,7 +250,8 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
|
|
||||||
result.Should().HaveCount(7);
|
result.Should().HaveCount(7);
|
||||||
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
|
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
|
||||||
result.Select(s => s.FriendlyName).Should().OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
|
result.Select(s => s.FriendlyName).Should()
|
||||||
|
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -279,15 +291,4 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region IsExcludedDevice
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
|
|
||||||
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
|
|
||||||
{
|
|
||||||
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,22 @@
|
|||||||
using System.Reactive.Concurrency;
|
using System.Reactive.Concurrency;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using BatteryMonitorManager.Interface;
|
|
||||||
using BatteryMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class BatteryMonitorInit
|
public sealed class BatteryMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<BatteryMonitorInit> _logger;
|
|
||||||
private readonly IScheduler _scheduler;
|
|
||||||
private readonly IBatterySensorDiscoveryService _discoveryService;
|
private readonly IBatterySensorDiscoveryService _discoveryService;
|
||||||
|
private readonly ILogger<BatteryMonitorInit> _logger;
|
||||||
private readonly IBatteryNotificationService _notificationService;
|
private readonly IBatteryNotificationService _notificationService;
|
||||||
private readonly BatteryMonitorOptions _options;
|
private readonly BatteryMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
|
||||||
public BatteryMonitorInit(
|
public BatteryMonitorInit(
|
||||||
ILogger<BatteryMonitorInit> logger,
|
ILogger<BatteryMonitorInit> logger,
|
||||||
@@ -55,9 +56,8 @@ public sealed class BatteryMonitorInit
|
|||||||
CheckAndNotify();
|
CheckAndNotify();
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
|
||||||
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent);
|
_options.BatteryThresholdPercent);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -68,7 +68,7 @@ public sealed class BatteryMonitorInit
|
|||||||
|
|
||||||
private void ScheduleDailyCheck()
|
private void ScheduleDailyCheck()
|
||||||
{
|
{
|
||||||
_scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () =>
|
_scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
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;
|
||||||
using BatteryMonitorManager.Interface;
|
|
||||||
using BatteryMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
@@ -14,10 +14,7 @@ public static class BatteryMonitorServiceRegistration
|
|||||||
.GetSection(BatteryMonitorOptions.SectionName)
|
.GetSection(BatteryMonitorOptions.SectionName)
|
||||||
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
|
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled) return services;
|
||||||
{
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
services
|
services
|
||||||
.AddNetDaemonApp<BatteryMonitorInit>()
|
.AddNetDaemonApp<BatteryMonitorInit>()
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using NetDaemon.HassModel;
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
using BatteryMonitorManager.Interface;
|
using BatteryMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
@@ -12,10 +12,7 @@ public sealed class BatteryNotificationService(
|
|||||||
{
|
{
|
||||||
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
||||||
{
|
{
|
||||||
if (lowBatteryDevices.Count == 0)
|
if (lowBatteryDevices.Count == 0) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var message = BuildNotificationMessage(lowBatteryDevices);
|
var message = BuildNotificationMessage(lowBatteryDevices);
|
||||||
|
|
||||||
@@ -30,12 +27,10 @@ public sealed class BatteryNotificationService(
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation(
|
logger.LogInformation(
|
||||||
"Sent low battery notification for {Count} device(s)",
|
"Sent low battery notification for {Count} device(s)",
|
||||||
lowBatteryDevices.Count);
|
lowBatteryDevices.Count);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public void DismissNotification()
|
public void DismissNotification()
|
||||||
{
|
{
|
||||||
@@ -57,9 +52,7 @@ 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,10 +1,10 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitor.Models;
|
|
||||||
using BatteryMonitorManager.Interface;
|
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
@@ -24,11 +24,9 @@ public sealed class BatterySensorDiscoveryService(
|
|||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation(
|
logger.LogInformation(
|
||||||
"Battery check: found {Count} sensors below {Threshold}%",
|
"Battery check: found {Count} sensors below {Threshold}%",
|
||||||
lowBatterySensors.Count, thresholdPercent);
|
lowBatterySensors.Count, thresholdPercent);
|
||||||
}
|
|
||||||
|
|
||||||
return lowBatterySensors!;
|
return lowBatterySensors!;
|
||||||
}
|
}
|
||||||
@@ -36,9 +34,7 @@ public sealed class BatterySensorDiscoveryService(
|
|||||||
internal static bool IsBatterySensor(Entity entity)
|
internal static bool IsBatterySensor(Entity entity)
|
||||||
{
|
{
|
||||||
if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase))
|
if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
|
||||||
return false;
|
return false;
|
||||||
}
|
|
||||||
|
|
||||||
var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class");
|
var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class");
|
||||||
|
|
||||||
@@ -60,9 +56,8 @@ public sealed class BatterySensorDiscoveryService(
|
|||||||
if (state is null or "unavailable" or "unknown")
|
if (state is null or "unavailable" or "unknown")
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
|
||||||
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null");
|
state ?? "null");
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -70,17 +65,13 @@ public sealed class BatterySensorDiscoveryService(
|
|||||||
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
|
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
|
||||||
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state);
|
state);
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (batteryLevel >= thresholdPercent)
|
if (batteryLevel >= thresholdPercent) return null;
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
|
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
|
||||||
?? entity.EntityId;
|
?? entity.EntityId;
|
||||||
@@ -95,10 +86,7 @@ public sealed class BatterySensorDiscoveryService(
|
|||||||
|
|
||||||
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||||
{
|
{
|
||||||
if (element is null)
|
if (element is null) return null;
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return element.Value.TryGetProperty(propertyName, out var value)
|
return element.Value.TryGetProperty(propertyName, out var value)
|
||||||
? value.GetString()
|
? value.GetString()
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -10,84 +10,11 @@ public class BoilerControlServiceTests
|
|||||||
{
|
{
|
||||||
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new();
|
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new();
|
||||||
|
|
||||||
private BoilerControlService CreateSut() => new(_loggerMock.Object);
|
private BoilerControlService CreateSut()
|
||||||
|
|
||||||
#region TurnOn scenarios
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("off")]
|
|
||||||
[InlineData("OFF")]
|
|
||||||
[InlineData("Off")]
|
|
||||||
[InlineData(null)]
|
|
||||||
[InlineData("")]
|
|
||||||
[InlineData(" ")]
|
|
||||||
[InlineData("off ")]
|
|
||||||
[InlineData("unavailable")]
|
|
||||||
[InlineData("unknown")]
|
|
||||||
[InlineData("0")]
|
|
||||||
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
|
||||||
{
|
{
|
||||||
var result = CreateSut().DetermineAction(
|
return new BoilerControlService(_loggerMock.Object);
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
|
||||||
budgetExhausted: false, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("off", BoilerAction.TurnOn)]
|
|
||||||
[InlineData(null, BoilerAction.TurnOn)]
|
|
||||||
[InlineData("unavailable", BoilerAction.TurnOn)]
|
|
||||||
[InlineData("on", BoilerAction.NoChange)]
|
|
||||||
[InlineData("On", BoilerAction.NoChange)]
|
|
||||||
[InlineData("ON", BoilerAction.NoChange)]
|
|
||||||
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn(
|
|
||||||
string? switchState,
|
|
||||||
BoilerAction expectedAction)
|
|
||||||
{
|
|
||||||
var result = CreateSut().DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
|
||||||
budgetExhausted: true, budgetOverride: true);
|
|
||||||
|
|
||||||
result.Should().Be(expectedAction);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region TurnOff scenarios
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("on")]
|
|
||||||
[InlineData("ON")]
|
|
||||||
[InlineData("On")]
|
|
||||||
[InlineData("oN")]
|
|
||||||
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
|
|
||||||
{
|
|
||||||
var result = CreateSut().DetermineAction(
|
|
||||||
isNowCheap: false, waterReady: false, currentSwitchState: switchState,
|
|
||||||
budgetExhausted: false, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(true, false, false)] // water ready
|
|
||||||
[InlineData(false, true, false)] // budget exhausted, no override
|
|
||||||
[InlineData(true, true, true)] // water ready wins over the budget override
|
|
||||||
public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff(
|
|
||||||
bool waterReady,
|
|
||||||
bool budgetExhausted,
|
|
||||||
bool budgetOverride)
|
|
||||||
{
|
|
||||||
var result = CreateSut().DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: waterReady, currentSwitchState: "on",
|
|
||||||
budgetExhausted: budgetExhausted, budgetOverride: budgetOverride);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region NoChange scenarios
|
#region NoChange scenarios
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -115,6 +42,82 @@ public class BoilerControlServiceTests
|
|||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
#region TurnOn scenarios
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("off")]
|
||||||
|
[InlineData("OFF")]
|
||||||
|
[InlineData("Off")]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
[InlineData("off ")]
|
||||||
|
[InlineData("unavailable")]
|
||||||
|
[InlineData("unknown")]
|
||||||
|
[InlineData("0")]
|
||||||
|
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
||||||
|
{
|
||||||
|
var result = CreateSut().DetermineAction(
|
||||||
|
true, false, switchState,
|
||||||
|
false, false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("off", BoilerAction.TurnOn)]
|
||||||
|
[InlineData(null, BoilerAction.TurnOn)]
|
||||||
|
[InlineData("unavailable", BoilerAction.TurnOn)]
|
||||||
|
[InlineData("on", BoilerAction.NoChange)]
|
||||||
|
[InlineData("On", BoilerAction.NoChange)]
|
||||||
|
[InlineData("ON", BoilerAction.NoChange)]
|
||||||
|
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn(
|
||||||
|
string? switchState,
|
||||||
|
BoilerAction expectedAction)
|
||||||
|
{
|
||||||
|
var result = CreateSut().DetermineAction(
|
||||||
|
true, false, switchState,
|
||||||
|
true, true);
|
||||||
|
|
||||||
|
result.Should().Be(expectedAction);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region TurnOff scenarios
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("on")]
|
||||||
|
[InlineData("ON")]
|
||||||
|
[InlineData("On")]
|
||||||
|
[InlineData("oN")]
|
||||||
|
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
|
||||||
|
{
|
||||||
|
var result = CreateSut().DetermineAction(
|
||||||
|
false, false, switchState,
|
||||||
|
false, false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, false, false)] // water ready
|
||||||
|
[InlineData(false, true, false)] // budget exhausted, no override
|
||||||
|
[InlineData(true, true, true)] // water ready wins over the budget override
|
||||||
|
public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff(
|
||||||
|
bool waterReady,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride)
|
||||||
|
{
|
||||||
|
var result = CreateSut().DetermineAction(
|
||||||
|
true, waterReady, "on",
|
||||||
|
budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region Comprehensive truth tables
|
#region Comprehensive truth tables
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -151,7 +154,7 @@ public class BoilerControlServiceTests
|
|||||||
BoilerAction expectedAction)
|
BoilerAction expectedAction)
|
||||||
{
|
{
|
||||||
var result = CreateSut().DetermineAction(
|
var result = CreateSut().DetermineAction(
|
||||||
isNowCheap, waterReady, currentSwitchState: "on", budgetExhausted, budgetOverride);
|
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
result.Should().Be(expectedAction);
|
result.Should().Be(expectedAction);
|
||||||
}
|
}
|
||||||
@@ -190,7 +193,7 @@ public class BoilerControlServiceTests
|
|||||||
BoilerAction expectedAction)
|
BoilerAction expectedAction)
|
||||||
{
|
{
|
||||||
var result = CreateSut().DetermineAction(
|
var result = CreateSut().DetermineAction(
|
||||||
isNowCheap, waterReady, currentSwitchState: "off", budgetExhausted, budgetOverride);
|
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
result.Should().Be(expectedAction);
|
result.Should().Be(expectedAction);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,10 +50,10 @@ public class BoilerMonitorConfigTests
|
|||||||
bool expected)
|
bool expected)
|
||||||
{
|
{
|
||||||
var config = BoilerMonitorTestData.CreateConfig(
|
var config = BoilerMonitorTestData.CreateConfig(
|
||||||
boilerPowerEntityId: powerEntityId,
|
powerEntityId,
|
||||||
boilerSwitchEntityId: switchEntityId,
|
switchEntityId,
|
||||||
pollIntervalSeconds: pollIntervalSeconds,
|
pollIntervalSeconds,
|
||||||
heatingPowerThresholdWatts: heatingPowerThresholdWatts);
|
heatingPowerThresholdWatts);
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().Be(expected, scenario);
|
config.IsFullyConfigured.Should().Be(expected, scenario);
|
||||||
}
|
}
|
||||||
@@ -62,8 +62,8 @@ public class BoilerMonitorConfigTests
|
|||||||
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
|
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
|
||||||
{
|
{
|
||||||
var config = BoilerMonitorTestData.CreateConfig(
|
var config = BoilerMonitorTestData.CreateConfig(
|
||||||
boilerPowerEntityId: " sensor.sonoff_1002230e32_power ",
|
" sensor.sonoff_1002230e32_power ",
|
||||||
boilerSwitchEntityId: "SWITCH.SONOFF_1002230E32");
|
"SWITCH.SONOFF_1002230E32");
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
|
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,10 +47,13 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
}
|
}
|
||||||
|
|
||||||
private BoilerMonitorEntityService CreateSut() => new(
|
private BoilerMonitorEntityService CreateSut()
|
||||||
|
{
|
||||||
|
return new BoilerMonitorEntityService(
|
||||||
_entityManagerMock.Object,
|
_entityManagerMock.Object,
|
||||||
_haContextMock.Object,
|
_haContextMock.Object,
|
||||||
_loggerMock.Object);
|
_loggerMock.Object);
|
||||||
|
}
|
||||||
|
|
||||||
#region ReadPersistedState
|
#region ReadPersistedState
|
||||||
|
|
||||||
@@ -61,7 +64,7 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
TimeSpan? expectedRunTime)
|
TimeSpan? expectedRunTime)
|
||||||
{
|
{
|
||||||
_haContextMock.SetupEntityStates(
|
_haContextMock.SetupEntityStates(
|
||||||
BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: runtimeState, sessionCount: "2"));
|
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||||
|
|
||||||
var result = CreateSut().ReadPersistedState();
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
@@ -83,7 +86,7 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
int? expectedSessionCount)
|
int? expectedSessionCount)
|
||||||
{
|
{
|
||||||
_haContextMock.SetupEntityStates(
|
_haContextMock.SetupEntityStates(
|
||||||
BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: "3600", sessionCount: sessionCountState));
|
BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
|
||||||
|
|
||||||
var result = CreateSut().ReadPersistedState();
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
@@ -102,7 +105,7 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
||||||
{
|
{
|
||||||
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||||
todayRuntime: "7200", sessionCount: "3", skipPriceCap: "ON", budgetOverride: "OFF"));
|
"7200", "3", "ON", "OFF"));
|
||||||
|
|
||||||
var result = CreateSut().ReadPersistedState();
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
@@ -135,7 +138,7 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
|
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
_haContextMock.SetupEntityStates(
|
_haContextMock.SetupEntityStates(
|
||||||
BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: null, sessionCount: null));
|
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||||
|
|
||||||
CreateSut().ReadPersistedState().Should().BeNull();
|
CreateSut().ReadPersistedState().Should().BeNull();
|
||||||
}
|
}
|
||||||
@@ -242,11 +245,11 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
|
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
|
||||||
{
|
{
|
||||||
var context = BoilerMonitorTestData.CreateUpdateContext(
|
var context = BoilerMonitorTestData.CreateUpdateContext(
|
||||||
todayRunTime: TimeSpan.FromSeconds(3723.9),
|
TimeSpan.FromSeconds(3723.9),
|
||||||
remainingTime: TimeSpan.FromSeconds(42.9),
|
TimeSpan.FromSeconds(42.9),
|
||||||
budgetPercentage: 150.0,
|
150.0,
|
||||||
budgetExhausted: true,
|
true,
|
||||||
sessionCount: 4,
|
4,
|
||||||
waterReady: true);
|
waterReady: true);
|
||||||
|
|
||||||
await CreateSut().UpdateEntitiesAsync(context);
|
await CreateSut().UpdateEntitiesAsync(context);
|
||||||
@@ -257,7 +260,8 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState(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>()), Times.Exactly(5));
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||||
|
Times.Exactly(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -302,7 +306,7 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
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(todayRunTime: 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);
|
||||||
}
|
}
|
||||||
@@ -380,8 +384,8 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity()
|
public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity()
|
||||||
{
|
{
|
||||||
_entityManagerMock
|
_entityManagerMock
|
||||||
.Setup(em => em.CreateEntityAsync(It.Is<EntityCreateModel>(
|
.Setup(em =>
|
||||||
entity => entity.EntityId == CleanupButtonEntityId)))
|
em.CreateEntityAsync(It.Is<EntityCreateModel>(entity => entity.EntityId == CleanupButtonEntityId)))
|
||||||
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||||
|
|
||||||
var act = () => CreateSut().CreateEntitiesAsync();
|
var act = () => CreateSut().CreateEntitiesAsync();
|
||||||
@@ -418,7 +422,8 @@ 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>()), Times.Exactly(5));
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||||
|
Times.Exactly(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -481,9 +486,7 @@ 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));
|
||||||
@@ -531,7 +534,7 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
public async Task Operation_WhenCancellationIsAlreadyRequested_ShouldThrowAndNotTouchEntityManager(
|
public async Task Operation_WhenCancellationIsAlreadyRequested_ShouldThrowAndNotTouchEntityManager(
|
||||||
CancelableOperation operation)
|
CancelableOperation operation)
|
||||||
{
|
{
|
||||||
var canceledToken = new CancellationToken(canceled: true);
|
var canceledToken = new CancellationToken(true);
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
Func<Task> act = operation switch
|
Func<Task> act = operation switch
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using FluentAssertions;
|
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
using FluentAssertions;
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ public class BoilerMonitorOptionsTests
|
|||||||
[InlineData(true)]
|
[InlineData(true)]
|
||||||
public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled)
|
public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled)
|
||||||
{
|
{
|
||||||
var options = BoilerMonitorTestData.CreateOptions(enabled: enabled);
|
var options = BoilerMonitorTestData.CreateOptions(enabled);
|
||||||
|
|
||||||
options.Enabled.Should().Be(enabled);
|
options.Enabled.Should().Be(enabled);
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,7 @@ public class BoilerMonitorOptionsTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently()
|
public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently()
|
||||||
{
|
{
|
||||||
var options = BoilerMonitorTestData.CreateOptions(enabled: false, cleanupEntitiesOnStartup: false);
|
var options = BoilerMonitorTestData.CreateOptions(false, false);
|
||||||
|
|
||||||
options.Enabled.Should().BeFalse();
|
options.Enabled.Should().BeFalse();
|
||||||
options.CleanupEntitiesOnStartup.Should().BeFalse();
|
options.CleanupEntitiesOnStartup.Should().BeFalse();
|
||||||
|
|||||||
@@ -21,30 +21,36 @@ internal static class BoilerMonitorTestData
|
|||||||
/// <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(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) =>
|
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null)
|
||||||
new(utcNow ?? BaseTime);
|
{
|
||||||
|
return new FakeTimeProvider(utcNow ?? BaseTime);
|
||||||
|
}
|
||||||
|
|
||||||
public static BoilerMonitorConfig CreateConfig(
|
public static BoilerMonitorConfig CreateConfig(
|
||||||
string? boilerPowerEntityId = PowerEntityId,
|
string? boilerPowerEntityId = PowerEntityId,
|
||||||
string? boilerSwitchEntityId = SwitchEntityId,
|
string? boilerSwitchEntityId = SwitchEntityId,
|
||||||
int? pollIntervalSeconds = DefaultPollIntervalSeconds,
|
int? pollIntervalSeconds = DefaultPollIntervalSeconds,
|
||||||
double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts) =>
|
double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts)
|
||||||
new()
|
{
|
||||||
|
return new BoilerMonitorConfig
|
||||||
{
|
{
|
||||||
BoilerPowerEntityId = boilerPowerEntityId,
|
BoilerPowerEntityId = boilerPowerEntityId,
|
||||||
BoilerSwitchEntityId = boilerSwitchEntityId,
|
BoilerSwitchEntityId = boilerSwitchEntityId,
|
||||||
PollIntervalSeconds = pollIntervalSeconds,
|
PollIntervalSeconds = pollIntervalSeconds,
|
||||||
HeatingPowerThresholdWatts = heatingPowerThresholdWatts
|
HeatingPowerThresholdWatts = heatingPowerThresholdWatts
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static BoilerMonitorOptions CreateOptions(
|
public static BoilerMonitorOptions CreateOptions(
|
||||||
bool enabled = true,
|
bool enabled = true,
|
||||||
bool cleanupEntitiesOnStartup = true) =>
|
bool cleanupEntitiesOnStartup = true)
|
||||||
new()
|
{
|
||||||
|
return new BoilerMonitorOptions
|
||||||
{
|
{
|
||||||
Enabled = enabled,
|
Enabled = enabled,
|
||||||
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup
|
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static BoilerMonitorUpdateContext CreateUpdateContext(
|
public static BoilerMonitorUpdateContext CreateUpdateContext(
|
||||||
TimeSpan? todayRunTime = null,
|
TimeSpan? todayRunTime = null,
|
||||||
@@ -56,8 +62,9 @@ internal static class BoilerMonitorTestData
|
|||||||
bool waterReady = false,
|
bool waterReady = false,
|
||||||
string? boilerSwitchState = "on",
|
string? boilerSwitchState = "on",
|
||||||
double? boilerPowerWatts = 0.0,
|
double? boilerPowerWatts = 0.0,
|
||||||
DateTimeOffset? cooldownSince = null) =>
|
DateTimeOffset? cooldownSince = null)
|
||||||
new()
|
{
|
||||||
|
return new BoilerMonitorUpdateContext
|
||||||
{
|
{
|
||||||
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
|
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
|
||||||
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
|
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
|
||||||
@@ -68,8 +75,9 @@ internal static class BoilerMonitorTestData
|
|||||||
WaterReady = waterReady,
|
WaterReady = waterReady,
|
||||||
BoilerSwitchState = boilerSwitchState,
|
BoilerSwitchState = boilerSwitchState,
|
||||||
BoilerPowerWatts = boilerPowerWatts,
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
CooldownSince = cooldownSince,
|
CooldownSince = cooldownSince
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The four entity states <c>ReadPersistedState</c> reads, with valid defaults.
|
/// The four entity states <c>ReadPersistedState</c> reads, with valid defaults.
|
||||||
@@ -79,22 +87,31 @@ internal static class BoilerMonitorTestData
|
|||||||
string? todayRuntime = "7200",
|
string? todayRuntime = "7200",
|
||||||
string? sessionCount = "3",
|
string? sessionCount = "3",
|
||||||
string? skipPriceCap = "OFF",
|
string? skipPriceCap = "OFF",
|
||||||
string? budgetOverride = "OFF") =>
|
string? budgetOverride = "OFF")
|
||||||
new()
|
{
|
||||||
|
return new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
[TodayRuntimeEntityId] = todayRuntime,
|
[TodayRuntimeEntityId] = todayRuntime,
|
||||||
[SessionCountEntityId] = sessionCount,
|
[SessionCountEntityId] = sessionCount,
|
||||||
[SkipPriceCapEntityId] = skipPriceCap,
|
[SkipPriceCapEntityId] = skipPriceCap,
|
||||||
[BudgetOverrideEntityId] = budgetOverride
|
[BudgetOverrideEntityId] = budgetOverride
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static EntityState CreateEntityState(string state) => new() { State = state };
|
public static EntityState CreateEntityState(string state)
|
||||||
|
{
|
||||||
|
return new EntityState { State = state };
|
||||||
|
}
|
||||||
|
|
||||||
public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary<string, object?> attributes) =>
|
public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary<string, object?> attributes)
|
||||||
new() { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) };
|
{
|
||||||
|
return new EntityState { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) };
|
||||||
|
}
|
||||||
|
|
||||||
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) =>
|
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince)
|
||||||
CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
|
{
|
||||||
|
return CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
|
||||||
|
}
|
||||||
|
|
||||||
extension(Mock<IHaContext> haContextMock)
|
extension(Mock<IHaContext> haContextMock)
|
||||||
{
|
{
|
||||||
@@ -107,9 +124,11 @@ internal static class BoilerMonitorTestData
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SetupEntityState(string entityId, EntityState? entityState) =>
|
public void SetupEntityState(string entityId, EntityState? entityState)
|
||||||
|
{
|
||||||
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Entity-state samples for the today-runtime sensor: valid values with the expected
|
/// Entity-state samples for the today-runtime sensor: valid values with the expected
|
||||||
@@ -141,7 +160,6 @@ internal static class BoilerMonitorTestData
|
|||||||
data.Add("-1", null);
|
data.Add("-1", null);
|
||||||
data.Add("-0.001", null);
|
data.Add("-0.001", null);
|
||||||
return data;
|
return data;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -168,7 +186,6 @@ internal static class BoilerMonitorTestData
|
|||||||
data.Add("2147483648", null);
|
data.Add("2147483648", null);
|
||||||
data.Add("1e3", null);
|
data.Add("1e3", null);
|
||||||
return data;
|
return data;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -188,7 +205,6 @@ internal static class BoilerMonitorTestData
|
|||||||
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;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -207,7 +223,6 @@ internal static class BoilerMonitorTestData
|
|||||||
data.Add(TimeSpan.FromHours(48));
|
data.Add(TimeSpan.FromHours(48));
|
||||||
data.Add(TimeSpan.FromHours(168));
|
data.Add(TimeSpan.FromHours(168));
|
||||||
return data;
|
return data;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -259,9 +274,10 @@ internal static class BoilerMonitorTestData
|
|||||||
false
|
false
|
||||||
);
|
);
|
||||||
return data;
|
return data;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DateTimeOffset TodayMidnight() =>
|
private static DateTimeOffset TodayMidnight()
|
||||||
new(BaseTime.Date, TimeSpan.Zero);
|
{
|
||||||
|
return new DateTimeOffset(BaseTime.Date, TimeSpan.Zero);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Time.Testing;
|
using Microsoft.Extensions.Time.Testing;
|
||||||
using Moq;
|
using Moq;
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -16,7 +16,10 @@ public class WaterReadyServiceTests
|
|||||||
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new();
|
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new();
|
||||||
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
|
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
|
||||||
|
|
||||||
private WaterReadyService CreateSut() => new(_loggerMock.Object, _timeProvider);
|
private WaterReadyService CreateSut()
|
||||||
|
{
|
||||||
|
return new WaterReadyService(_loggerMock.Object, _timeProvider);
|
||||||
|
}
|
||||||
|
|
||||||
private WaterReadyService CreateSutWithHeatingObserved()
|
private WaterReadyService CreateSutWithHeatingObserved()
|
||||||
{
|
{
|
||||||
@@ -33,10 +36,7 @@ public class WaterReadyServiceTests
|
|||||||
double heatingThresholdWatts = Threshold)
|
double heatingThresholdWatts = Threshold)
|
||||||
{
|
{
|
||||||
var result = false;
|
var result = false;
|
||||||
for (var i = 0; i < count; i++)
|
for (var i = 0; i < count; i++) result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
||||||
{
|
|
||||||
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -282,7 +282,8 @@ public class WaterReadyServiceTests
|
|||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts, heatingThresholdWatts: heatingThresholdWatts);
|
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts,
|
||||||
|
heatingThresholdWatts: heatingThresholdWatts);
|
||||||
|
|
||||||
result.Should().Be(expected);
|
result.Should().Be(expected);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,33 +14,34 @@ 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) ? dh : DefaultDailyHours;
|
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
|
||||||
|
? dh
|
||||||
|
: DefaultDailyHours;
|
||||||
|
|
||||||
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
||||||
|
|
||||||
if (intervalCount <= 0)
|
if (intervalCount <= 0) intervalCount = IntervalsPerHour;
|
||||||
{
|
|
||||||
intervalCount = IntervalsPerHour;
|
|
||||||
}
|
|
||||||
|
|
||||||
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
||||||
var priceCap = double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 ? pc : double.MaxValue;
|
var priceCap =
|
||||||
|
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
|
||||||
|
? pc
|
||||||
|
: double.MaxValue;
|
||||||
|
|
||||||
var deadline = DateTime.Today.AddDays(1);
|
var deadline = DateTime.Today.AddDays(1);
|
||||||
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
|
if (!string.IsNullOrEmpty(readyByState) &&
|
||||||
{
|
TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
|
||||||
deadline = DateTime.Today.Add(readyByTime);
|
deadline = DateTime.Today.Add(readyByTime);
|
||||||
}
|
|
||||||
|
|
||||||
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug(
|
||||||
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", intervalCount, priceCap, skipPriceCap, deadline);
|
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||||
}
|
intervalCount, priceCap, skipPriceCap, deadline);
|
||||||
|
|
||||||
var config = new BoilerConfig
|
var config = new BoilerConfig
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -23,9 +23,9 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
|||||||
{
|
{
|
||||||
case (true, false):
|
case (true, false):
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
logger.LogInformation(
|
||||||
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
|
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||||
}
|
currentSwitchState);
|
||||||
|
|
||||||
return BoilerAction.TurnOn;
|
return BoilerAction.TurnOn;
|
||||||
|
|
||||||
@@ -34,19 +34,17 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
|||||||
var reason = GetTurnOffReason(waterReady, effectiveBudgetExhausted);
|
var reason = GetTurnOffReason(waterReady, effectiveBudgetExhausted);
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason,
|
||||||
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
|
currentSwitchState);
|
||||||
}
|
|
||||||
|
|
||||||
return BoilerAction.TurnOff;
|
return BoilerAction.TurnOff;
|
||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug(
|
||||||
logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||||
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||||
}
|
|
||||||
|
|
||||||
return BoilerAction.NoChange;
|
return BoilerAction.NoChange;
|
||||||
}
|
}
|
||||||
@@ -54,10 +52,7 @@ 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)
|
if (waterReady) return "water is already ready";
|
||||||
{
|
|
||||||
return "water is already ready";
|
|
||||||
}
|
|
||||||
|
|
||||||
return effectiveBudgetExhausted
|
return effectiveBudgetExhausted
|
||||||
? "daily budget is exhausted"
|
? "daily budget is exhausted"
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
@@ -33,14 +34,6 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
AutoManagementEntityId
|
AutoManagementEntityId
|
||||||
];
|
];
|
||||||
|
|
||||||
private static object CreateDeviceBlock() => new
|
|
||||||
{
|
|
||||||
identifiers = new[] { DeviceIdentifier },
|
|
||||||
name = DeviceName,
|
|
||||||
model = DeviceName,
|
|
||||||
manufacturer = DeviceManufacturer
|
|
||||||
};
|
|
||||||
|
|
||||||
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -52,9 +45,7 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||||
}
|
|
||||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -149,13 +140,13 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
|
|
||||||
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount))
|
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) ||
|
||||||
|
!TryParseEntityInt(sessionCountState, out var sessionCount))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
logger.LogInformation(
|
||||||
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||||
runtimeState, sessionCountState);
|
runtimeState, sessionCountState);
|
||||||
}
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,10 +159,10 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
logger.LogInformation(
|
||||||
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||||
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
|
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||||
}
|
persisted.BudgetOverrideState);
|
||||||
|
|
||||||
return persisted;
|
return persisted;
|
||||||
}
|
}
|
||||||
@@ -187,6 +178,51 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
await UpdateStatusAsync(status).ConfigureAwait(false);
|
await UpdateStatusAsync(status).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public DateTimeOffset? ReadPersistedCooldownTimestamp()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var entity = haContext.GetState(WaterReadyEntityId);
|
||||||
|
if (entity?.Attributes is not IDictionary<string, object> attributes) return null;
|
||||||
|
|
||||||
|
if (!attributes.TryGetValue("cooldown_since", out var value)) return null;
|
||||||
|
|
||||||
|
var stringValue = value switch
|
||||||
|
{
|
||||||
|
string s => s,
|
||||||
|
JsonElement { ValueKind: JsonValueKind.String } jsonElement =>
|
||||||
|
jsonElement.GetString(),
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
|
||||||
|
if (stringValue is not null &&
|
||||||
|
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
||||||
|
DateTimeStyles.RoundtripKind, out var parsed))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error reading persisted cooldown timestamp");
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static object CreateDeviceBlock()
|
||||||
|
{
|
||||||
|
return new
|
||||||
|
{
|
||||||
|
identifiers = new[] { DeviceIdentifier },
|
||||||
|
name = DeviceName,
|
||||||
|
model = DeviceName,
|
||||||
|
manufacturer = DeviceManufacturer
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
||||||
{
|
{
|
||||||
seconds = 0;
|
seconds = 0;
|
||||||
@@ -235,7 +271,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
device
|
device
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)")
|
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
|
||||||
|
"Heating power threshold (watts)")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new
|
AdditionalConfig = new
|
||||||
{
|
{
|
||||||
@@ -265,11 +302,13 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
||||||
{
|
{
|
||||||
@@ -401,7 +440,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(TodayRuntimeEntityId, ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(TodayRuntimeEntityId,
|
||||||
|
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted,
|
formatted,
|
||||||
@@ -410,10 +450,12 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, string timestamp)
|
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours,
|
||||||
|
string timestamp)
|
||||||
{
|
{
|
||||||
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
||||||
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted,
|
formatted,
|
||||||
@@ -426,7 +468,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
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, ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(BudgetPercentageEntityId,
|
||||||
|
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = "%",
|
unit_of_measurement = "%",
|
||||||
@@ -442,7 +485,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
{
|
{
|
||||||
friendly_name = "Heating sessions today",
|
friendly_name = "Heating sessions today",
|
||||||
@@ -450,58 +494,14 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTimeOffset? ReadPersistedCooldownTimestamp()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var entity = haContext.GetState(WaterReadyEntityId);
|
|
||||||
if (entity?.Attributes is not IDictionary<string, object> attributes)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!attributes.TryGetValue("cooldown_since", out var value))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var stringValue = value switch
|
|
||||||
{
|
|
||||||
string s => s,
|
|
||||||
System.Text.Json.JsonElement { ValueKind: System.Text.Json.JsonValueKind.String } jsonElement =>
|
|
||||||
jsonElement.GetString(),
|
|
||||||
_ => null
|
|
||||||
};
|
|
||||||
|
|
||||||
if (stringValue is not null &&
|
|
||||||
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
|
||||||
DateTimeStyles.RoundtripKind, out var parsed))
|
|
||||||
{
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
|
||||||
{
|
|
||||||
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
|
|
||||||
}
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, "Error reading persisted cooldown timestamp");
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task SetEntityStateSafe(string entityId, string state)
|
private async Task SetEntityStateSafe(string entityId, string state)
|
||||||
{
|
{
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
||||||
@@ -514,10 +514,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
{
|
{
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||||
|
|||||||
@@ -18,19 +18,19 @@ namespace BoilerMonitorManager;
|
|||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class BoilerMonitorInit
|
public sealed class BoilerMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<BoilerMonitorInit> _logger;
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly IScheduler _scheduler;
|
|
||||||
private readonly IMqttEntityManager _mqttEntityManager;
|
|
||||||
private readonly IBoilerControlService _boilerControlService;
|
private readonly IBoilerControlService _boilerControlService;
|
||||||
private readonly IBoilerRunTimeTracker _tracker;
|
|
||||||
private readonly IBoilerMonitorEntityService _entityService;
|
private readonly IBoilerMonitorEntityService _entityService;
|
||||||
private readonly IWaterReadyService _waterReadyService;
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<BoilerMonitorInit> _logger;
|
||||||
|
private readonly IMqttEntityManager _mqttEntityManager;
|
||||||
private readonly BoilerMonitorOptions _options;
|
private readonly BoilerMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
|
||||||
private readonly TimeProvider _timeProvider;
|
private readonly TimeProvider _timeProvider;
|
||||||
private bool _lastWaterReady;
|
private readonly IBoilerRunTimeTracker _tracker;
|
||||||
|
private readonly IWaterReadyService _waterReadyService;
|
||||||
private volatile bool _cleanedUp;
|
private volatile bool _cleanedUp;
|
||||||
|
private bool _lastWaterReady;
|
||||||
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
|
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
|
||||||
|
|
||||||
public BoilerMonitorInit(
|
public BoilerMonitorInit(
|
||||||
@@ -55,7 +55,7 @@ public sealed class BoilerMonitorInit
|
|||||||
waterReadyService,
|
waterReadyService,
|
||||||
options,
|
options,
|
||||||
timeProvider,
|
timeProvider,
|
||||||
startBackgroundScheduling: true)
|
true)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,10 +83,7 @@ public sealed class BoilerMonitorInit
|
|||||||
_options = options.Value;
|
_options = options.Value;
|
||||||
_timeProvider = timeProvider;
|
_timeProvider = timeProvider;
|
||||||
|
|
||||||
if (startBackgroundScheduling)
|
if (startBackgroundScheduling) _ = InitializeAndScheduleAsync();
|
||||||
{
|
|
||||||
_ = InitializeAndScheduleAsync();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task InitializeAndScheduleAsync()
|
private async Task InitializeAndScheduleAsync()
|
||||||
@@ -133,18 +130,14 @@ public sealed class BoilerMonitorInit
|
|||||||
{
|
{
|
||||||
_tracker.RestoreFromSnapshot();
|
_tracker.RestoreFromSnapshot();
|
||||||
|
|
||||||
if (persistedCooldown.HasValue)
|
if (persistedCooldown.HasValue) _waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||||
{
|
|
||||||
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
|
||||||
}
|
|
||||||
|
|
||||||
await _entityService.ResetTransientEntitiesAsync();
|
await _entityService.ResetTransientEntitiesAsync();
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation(
|
||||||
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _entityService.ResetEntitiesAsync();
|
await _entityService.ResetEntitiesAsync();
|
||||||
@@ -174,11 +167,11 @@ public sealed class BoilerMonitorInit
|
|||||||
var nextPollTime = now.Add(delayUntilNext);
|
var nextPollTime = now.Add(delayUntilNext);
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
|
||||||
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
|
DefaultPollIntervalSeconds, nextPollTime);
|
||||||
}
|
|
||||||
|
|
||||||
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync());
|
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
|
||||||
|
() => _ = PollAndUpdateAsync());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ScheduleMidnightReset()
|
private void ScheduleMidnightReset()
|
||||||
@@ -207,10 +200,7 @@ public sealed class BoilerMonitorInit
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||||
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||||
{
|
{
|
||||||
@@ -232,10 +222,7 @@ public sealed class BoilerMonitorInit
|
|||||||
skipPriceCapSwitch.StateChanges()
|
skipPriceCapSwitch.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
if (e.Old?.State == e.New?.State)
|
if (e.Old?.State == e.New?.State) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
||||||
_ = PollAndUpdateAsync();
|
_ = PollAndUpdateAsync();
|
||||||
@@ -248,10 +235,7 @@ public sealed class BoilerMonitorInit
|
|||||||
autoManagementSwitch.StateChanges()
|
autoManagementSwitch.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
if (e.Old?.State == e.New?.State)
|
if (e.Old?.State == e.New?.State) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
|
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
|
||||||
_ = PollAndUpdateAsync();
|
_ = PollAndUpdateAsync();
|
||||||
@@ -264,15 +248,9 @@ public sealed class BoilerMonitorInit
|
|||||||
showerStateSensor.StateChanges()
|
showerStateSensor.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!_waterReadyService.IsInCooldown)
|
if (!_waterReadyService.IsInCooldown) return;
|
||||||
{
|
|
||||||
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();
|
||||||
@@ -312,9 +290,7 @@ public sealed class BoilerMonitorInit
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
||||||
}
|
|
||||||
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
@@ -344,9 +320,7 @@ public sealed class BoilerMonitorInit
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
||||||
}
|
|
||||||
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
@@ -385,7 +359,8 @@ public sealed class BoilerMonitorInit
|
|||||||
if (!config.IsFullyConfigured)
|
if (!config.IsFullyConfigured)
|
||||||
{
|
{
|
||||||
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
||||||
_logger.LogWarning("BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
_logger.LogWarning(
|
||||||
|
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||||
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||||
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||||
|
|
||||||
@@ -394,13 +369,11 @@ 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 && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
var isHeating = boilerPowerWatts.HasValue &&
|
||||||
|
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
||||||
_tracker.RecordPollResult();
|
_tracker.RecordPollResult();
|
||||||
|
|
||||||
if (isHeating)
|
if (isHeating) _waterReadyService.RecordHeatingObserved();
|
||||||
{
|
|
||||||
_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");
|
||||||
@@ -413,7 +386,8 @@ public sealed class BoilerMonitorInit
|
|||||||
|
|
||||||
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
||||||
|
|
||||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
|
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
|
||||||
|
config.HeatingPowerThresholdWatts!.Value);
|
||||||
|
|
||||||
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
||||||
{
|
{
|
||||||
@@ -425,16 +399,14 @@ public sealed class BoilerMonitorInit
|
|||||||
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
||||||
_logger.LogInformation("Water ready notification sent");
|
_logger.LogInformation("Water ready notification sent");
|
||||||
}
|
}
|
||||||
|
|
||||||
_lastWaterReady = waterReady;
|
_lastWaterReady = waterReady;
|
||||||
|
|
||||||
var snapshot = _tracker.GetSnapshot();
|
var snapshot = _tracker.GetSnapshot();
|
||||||
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
||||||
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
|
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
|
||||||
|
|
||||||
if (remainingTime < TimeSpan.Zero)
|
if (remainingTime < TimeSpan.Zero) 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
|
||||||
@@ -452,21 +424,16 @@ public sealed class BoilerMonitorInit
|
|||||||
budgetOverride);
|
budgetOverride);
|
||||||
|
|
||||||
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
||||||
var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
var autoManagementEnabled =
|
||||||
|
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
if (autoManagementEnabled)
|
if (autoManagementEnabled)
|
||||||
{
|
|
||||||
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
|
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
|
||||||
}
|
|
||||||
else if (boilerAction is not BoilerAction.NoChange)
|
else if (boilerAction is not BoilerAction.NoChange)
|
||||||
{
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation(
|
_logger.LogInformation(
|
||||||
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
|
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
|
||||||
boilerAction);
|
boilerAction);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var context = new BoilerMonitorUpdateContext
|
var context = new BoilerMonitorUpdateContext
|
||||||
{
|
{
|
||||||
@@ -479,17 +446,16 @@ public sealed class BoilerMonitorInit
|
|||||||
WaterReady = waterReady,
|
WaterReady = waterReady,
|
||||||
BoilerSwitchState = boilerSwitchState,
|
BoilerSwitchState = boilerSwitchState,
|
||||||
BoilerPowerWatts = boilerPowerWatts,
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
CooldownSince = _waterReadyService.WaterReadySince,
|
CooldownSince = _waterReadyService.WaterReadySince
|
||||||
};
|
};
|
||||||
|
|
||||||
await _entityService.UpdateEntitiesAsync(context);
|
await _entityService.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Debug))
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
_logger.LogDebug(
|
||||||
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||||
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
||||||
@@ -525,9 +491,7 @@ public sealed class BoilerMonitorInit
|
|||||||
if (!string.IsNullOrWhiteSpace(pollIntervalState)
|
if (!string.IsNullOrWhiteSpace(pollIntervalState)
|
||||||
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
|
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
|
||||||
&& pollIntervalValue > 0)
|
&& pollIntervalValue > 0)
|
||||||
{
|
|
||||||
pollInterval = (int)pollIntervalValue;
|
pollInterval = (int)pollIntervalValue;
|
||||||
}
|
|
||||||
|
|
||||||
double? heatingThreshold = null;
|
double? heatingThreshold = null;
|
||||||
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
||||||
@@ -535,9 +499,7 @@ public sealed class BoilerMonitorInit
|
|||||||
if (!string.IsNullOrWhiteSpace(thresholdState)
|
if (!string.IsNullOrWhiteSpace(thresholdState)
|
||||||
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
|
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
|
||||||
&& thresholdValue > 0)
|
&& thresholdValue > 0)
|
||||||
{
|
|
||||||
heatingThreshold = thresholdValue;
|
heatingThreshold = thresholdValue;
|
||||||
}
|
|
||||||
|
|
||||||
return new BoilerMonitorConfig
|
return new BoilerMonitorConfig
|
||||||
{
|
{
|
||||||
@@ -552,25 +514,18 @@ public sealed class BoilerMonitorInit
|
|||||||
{
|
{
|
||||||
var state = _haContext.GetState(entityId);
|
var state = _haContext.GetState(entityId);
|
||||||
|
|
||||||
if (state?.State is null or "unavailable" or "unknown")
|
if (state?.State is null or "unavailable" or "unknown") return null;
|
||||||
{
|
|
||||||
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)
|
if (entityState?.Attributes is not IDictionary<string, object> attributes) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (attributes.TryGetValue(attributeName, out var value))
|
if (attributes.TryGetValue(attributeName, out var value))
|
||||||
{
|
|
||||||
return value switch
|
return value switch
|
||||||
{
|
{
|
||||||
bool b => b,
|
bool b => b,
|
||||||
@@ -582,7 +537,6 @@ public sealed class BoilerMonitorInit
|
|||||||
_ => false
|
_ => false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
// Attribute not found or not parseable
|
// Attribute not found or not parseable
|
||||||
@@ -593,13 +547,9 @@ public sealed class BoilerMonitorInit
|
|||||||
|
|
||||||
private bool IsWithinNotificationCooldown()
|
private bool IsWithinNotificationCooldown()
|
||||||
{
|
{
|
||||||
if (_lastWaterReadyNotificationSentAt is null)
|
if (_lastWaterReadyNotificationSentAt is null) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
||||||
return elapsed < WaterReadyNotificationCooldown;
|
return elapsed < WaterReadyNotificationCooldown;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -14,10 +14,7 @@ public static class BoilerMonitorServiceRegistration
|
|||||||
.GetSection(BoilerMonitorOptions.SectionName)
|
.GetSection(BoilerMonitorOptions.SectionName)
|
||||||
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled) return services;
|
||||||
{
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
services
|
services
|
||||||
.AddNetDaemonApp<BoilerMonitorInit>()
|
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
|||||||
{
|
{
|
||||||
public void RecordPollResult()
|
public void RecordPollResult()
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public RunTimeSnapshot GetSnapshot()
|
public RunTimeSnapshot GetSnapshot()
|
||||||
@@ -21,11 +20,9 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
|||||||
|
|
||||||
public void Reset()
|
public void Reset()
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RestoreFromSnapshot()
|
public void RestoreFromSnapshot()
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,9 @@ namespace BoilerMonitorManager.Interface;
|
|||||||
|
|
||||||
public interface IWaterReadyService
|
public interface IWaterReadyService
|
||||||
{
|
{
|
||||||
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
|
||||||
bool IsInCooldown { get; }
|
bool IsInCooldown { get; }
|
||||||
DateTimeOffset? WaterReadySince { get; }
|
DateTimeOffset? WaterReadySince { get; }
|
||||||
|
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
||||||
void NotifyTurnedOn();
|
void NotifyTurnedOn();
|
||||||
void RecordHeatingObserved();
|
void RecordHeatingObserved();
|
||||||
void ResetCooldown();
|
void ResetCooldown();
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
{
|
{
|
||||||
private const string SwitchOnState = "on";
|
private const string SwitchOnState = "on";
|
||||||
private readonly Lock _lock = new();
|
private readonly Lock _lock = new();
|
||||||
private DateTimeOffset? _waterReadySince;
|
|
||||||
private bool _hasObservedHeating;
|
|
||||||
private int _consecutiveBelowThresholdCount;
|
private int _consecutiveBelowThresholdCount;
|
||||||
|
private bool _hasObservedHeating;
|
||||||
|
private DateTimeOffset? _waterReadySince;
|
||||||
|
|
||||||
public bool IsInCooldown
|
public bool IsInCooldown
|
||||||
{
|
{
|
||||||
@@ -41,31 +41,23 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
if (IsWithinCooldownPeriod())
|
if (IsWithinCooldownPeriod())
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
|
||||||
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
|
_waterReadySince);
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (switchState is null || powerWatts is null)
|
if (switchState is null || powerWatts is null) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
if (!_hasObservedHeating)
|
if (!_hasObservedHeating)
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
||||||
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value);
|
powerWatts.Value);
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -81,10 +73,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
|
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug(
|
||||||
logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
||||||
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value);
|
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
||||||
}
|
powerWatts.Value);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -92,9 +84,9 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
_waterReadySince ??= timeProvider.GetUtcNow();
|
_waterReadySince ??= timeProvider.GetUtcNow();
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
logger.LogInformation(
|
||||||
logger.LogInformation("Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", _consecutiveBelowThresholdCount);
|
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||||
}
|
_consecutiveBelowThresholdCount);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -108,17 +100,15 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
_consecutiveBelowThresholdCount = 0;
|
_consecutiveBelowThresholdCount = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogDebug("Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
logger.LogDebug(
|
||||||
|
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RecordHeatingObserved()
|
public void RecordHeatingObserved()
|
||||||
{
|
{
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
if (_hasObservedHeating)
|
if (_hasObservedHeating) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_hasObservedHeating = true;
|
_hasObservedHeating = true;
|
||||||
}
|
}
|
||||||
@@ -145,20 +135,20 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
if (waterReadySince < todayMidnightUtc)
|
if (waterReadySince < todayMidnightUtc)
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
|
||||||
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince);
|
waterReadySince);
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_waterReadySince = waterReadySince;
|
_waterReadySince = waterReadySince;
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private bool IsWithinCooldownPeriod() => _waterReadySince is not null;
|
private bool IsWithinCooldownPeriod()
|
||||||
|
{
|
||||||
|
return _waterReadySince is not null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -20,12 +20,6 @@ public static class BoilerMonitorConsts
|
|||||||
public const string ShowerStateEntityId = "sensor.showermonitor_state";
|
public const string ShowerStateEntityId = "sensor.showermonitor_state";
|
||||||
public const string ShowerActiveState = "Active";
|
public const string ShowerActiveState = "Active";
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Minimum interval between "hot water is ready" push notifications.
|
|
||||||
/// Prevents notification spam when power readings fluctuate around the heating threshold.
|
|
||||||
/// </summary>
|
|
||||||
public static readonly TimeSpan WaterReadyNotificationCooldown = TimeSpan.FromHours(1);
|
|
||||||
|
|
||||||
public const int MinPollIntervalSeconds = 5;
|
public const int MinPollIntervalSeconds = 5;
|
||||||
public const int MaxPollIntervalSeconds = 300;
|
public const int MaxPollIntervalSeconds = 300;
|
||||||
public const int PollIntervalStepSeconds = 5;
|
public const int PollIntervalStepSeconds = 5;
|
||||||
@@ -73,4 +67,10 @@ public static class BoilerMonitorConsts
|
|||||||
public const string DeviceIdentifier = "boiler_monitor";
|
public const string DeviceIdentifier = "boiler_monitor";
|
||||||
public const string DeviceName = "Boiler Monitor";
|
public const string DeviceName = "Boiler Monitor";
|
||||||
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Minimum interval between "hot water is ready" push notifications.
|
||||||
|
/// Prevents notification spam when power readings fluctuate around the heating threshold.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly TimeSpan WaterReadyNotificationCooldown = TimeSpan.FromHours(1);
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,6 @@ namespace BoilerMonitor.Models;
|
|||||||
|
|
||||||
public class BoilerMonitorEntity : EntityCreateModel
|
public class BoilerMonitorEntity : EntityCreateModel
|
||||||
{
|
{
|
||||||
private string Domain { get; }
|
|
||||||
private string Identifier { get; }
|
|
||||||
private string Name { get; }
|
|
||||||
|
|
||||||
public BoilerMonitorEntity(string domain, string identifier, string name)
|
public BoilerMonitorEntity(string domain, string identifier, string name)
|
||||||
{
|
{
|
||||||
Domain = domain;
|
Domain = domain;
|
||||||
@@ -22,4 +18,8 @@ public class BoilerMonitorEntity : EntityCreateModel
|
|||||||
Name = Name
|
Name = Name
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string Domain { get; }
|
||||||
|
private string Identifier { get; }
|
||||||
|
private string Name { get; }
|
||||||
}
|
}
|
||||||
@@ -23,10 +23,8 @@ public class EntityManager(
|
|||||||
public async Task CreateEntityAsync(EntityCreateModel createModel)
|
public async Task CreateEntityAsync(EntityCreateModel createModel)
|
||||||
{
|
{
|
||||||
if (createModel.EntityId != null)
|
if (createModel.EntityId != null)
|
||||||
{
|
|
||||||
await entityManager.CreateAsync(createModel.EntityId, createModel.Options, createModel.AdditionalConfig);
|
await entityManager.CreateAsync(createModel.EntityId, createModel.Options, createModel.AdditionalConfig);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public async Task SetEntityState(string entityId, string state)
|
public async Task SetEntityState(string entityId, string state)
|
||||||
{
|
{
|
||||||
@@ -53,14 +51,12 @@ 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;
|
||||||
@@ -70,11 +66,9 @@ public class EntityManager(
|
|||||||
{
|
{
|
||||||
var separatorIndex = entityId.IndexOf('.');
|
var separatorIndex = entityId.IndexOf('.');
|
||||||
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
|
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
|
||||||
{
|
|
||||||
throw new ArgumentException(
|
throw new ArgumentException(
|
||||||
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
|
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
|
||||||
nameof(entityId));
|
nameof(entityId));
|
||||||
}
|
|
||||||
|
|
||||||
var domain = entityId[..separatorIndex];
|
var domain = entityId[..separatorIndex];
|
||||||
var objectId = entityId[(separatorIndex + 1)..];
|
var objectId = entityId[(separatorIndex + 1)..];
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ namespace HomeAssistant.Models;
|
|||||||
|
|
||||||
public class EntityCreateModel
|
public class EntityCreateModel
|
||||||
{
|
{
|
||||||
public string? EntityId { get; init; }
|
public string? EntityId { get; protected init; }
|
||||||
public EntityCreationOptions? Options { get; init; } = new();
|
public EntityCreationOptions? Options { get; init; } = new();
|
||||||
public object? AdditionalConfig { get; init; }
|
public object? AdditionalConfig { get; init; }
|
||||||
}
|
}
|
||||||
@@ -11,7 +11,8 @@ public static class CustomLoggingProvider
|
|||||||
{
|
{
|
||||||
var configuration = new ConfigurationBuilder()
|
var configuration = new ConfigurationBuilder()
|
||||||
.AddJsonFile("appsettings.json")
|
.AddJsonFile("appsettings.json")
|
||||||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
|
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json",
|
||||||
|
true)
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
var logger = new LoggerConfiguration()
|
var logger = new LoggerConfiguration()
|
||||||
|
|||||||
@@ -25,9 +25,9 @@ public sealed class MqttRecreateApp
|
|||||||
private static readonly string[] AppDaemonIdentifiers = ["appdaemon"];
|
private static readonly string[] AppDaemonIdentifiers = ["appdaemon"];
|
||||||
|
|
||||||
private readonly IHaContext _haContext;
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<MqttRecreateApp> _logger;
|
||||||
private readonly IMqttEntityManager _mqttEntityManager;
|
private readonly IMqttEntityManager _mqttEntityManager;
|
||||||
private readonly IServiceProvider _serviceProvider;
|
private readonly IServiceProvider _serviceProvider;
|
||||||
private readonly ILogger<MqttRecreateApp> _logger;
|
|
||||||
|
|
||||||
public MqttRecreateApp(
|
public MqttRecreateApp(
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
@@ -69,9 +69,7 @@ public sealed class MqttRecreateApp
|
|||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId);
|
_logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId);
|
||||||
}
|
|
||||||
|
|
||||||
var button = new Entity(_haContext, RecreateButtonEntityId);
|
var button = new Entity(_haContext, RecreateButtonEntityId);
|
||||||
button.StateChanges()
|
button.StateChanges()
|
||||||
@@ -204,7 +202,6 @@ public sealed class MqttRecreateApp
|
|||||||
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,
|
||||||
@@ -212,14 +209,11 @@ public sealed class MqttRecreateApp
|
|||||||
_ => null
|
_ => null
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
if (_logger.IsEnabled(LogLevel.Debug))
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
|
||||||
_logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId);
|
_logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,28 @@
|
|||||||
# Project template for binary deploy
|
# Project template for binary deploy
|
||||||
|
|
||||||
This is the project template for binary deploy. This allows you to build a binary package and deploy it to NetDaemon.
|
This is the project template for binary deploy. This allows you to build a binary package and deploy it to NetDaemon.
|
||||||
|
|
||||||
This is generated using NetDaemon runtime version 5 and .NET 9.
|
This is generated using NetDaemon runtime version 5 and .NET 9.
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
Please see [netdaemon.xyz](https://netdaemon.xyz/docs) more information about getting starting developing apps for Home Assistant using NetDaemon.
|
|
||||||
|
Please see [netdaemon.xyz](https://netdaemon.xyz/docs) more information about getting starting developing apps for Home
|
||||||
|
Assistant using NetDaemon.
|
||||||
|
|
||||||
Please add code generation features in `program.cs` when using code generation features by removing comments!
|
Please add code generation features in `program.cs` when using code generation features by removing comments!
|
||||||
|
|
||||||
## Use the code generator
|
## Use the code generator
|
||||||
|
|
||||||
See https://netdaemon.xyz/docs/hass_model/hass_model_codegen
|
See https://netdaemon.xyz/docs/hass_model/hass_model_codegen
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
- If you have issues or suggestions of improvements to this template, please [add an issue](https://github.com/net-daemon/netdaemon-app-template)
|
- If you have issues or suggestions of improvements to this template,
|
||||||
- If you have issues or suggestions of improvements to NetDaemon, please [add an issue](https://github.com/net-daemon/netdaemon/issues)
|
please [add an issue](https://github.com/net-daemon/netdaemon-app-template)
|
||||||
|
- If you have issues or suggestions of improvements to NetDaemon,
|
||||||
|
please [add an issue](https://github.com/net-daemon/netdaemon/issues)
|
||||||
|
|
||||||
## Discuss the NetDaemon
|
## Discuss the NetDaemon
|
||||||
|
|
||||||
Please [join the Discord server](https://discord.gg/K3xwfcX) to get support or if you want to contribute and help others.
|
Please [join the Discord server](https://discord.gg/K3xwfcX) to get support or if you want to contribute and help
|
||||||
|
others.
|
||||||
|
|||||||
@@ -45,7 +45,10 @@
|
|||||||
"Enabled": true,
|
"Enabled": true,
|
||||||
"LightEntityId": "light.sonoff_1002214d40",
|
"LightEntityId": "light.sonoff_1002214d40",
|
||||||
"SunEntityId": "sun.sun",
|
"SunEntityId": "sun.sun",
|
||||||
"PersonEntityIds": ["person.marius", "person.erika"]
|
"PersonEntityIds": [
|
||||||
|
"person.marius",
|
||||||
|
"person.erika"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"BatteryMonitor": {
|
"BatteryMonitor": {
|
||||||
"Enabled": true,
|
"Enabled": true,
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
using BatteryMonitorManager;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
using HomeAssistant.Entities;
|
using HomeAssistant.Entities;
|
||||||
using HomeAssistant.Entities.Interfaces;
|
using HomeAssistant.Entities.Interfaces;
|
||||||
using HomeAssistantGenerated;
|
using HomeAssistantGenerated;
|
||||||
using HomeAssistantServer;
|
using HomeAssistantServer;
|
||||||
|
using LeakMonitorManager;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
using LightMonitor.Models;
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
using Mappings;
|
using Mappings;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
@@ -13,19 +21,12 @@ using NetDaemon.Extensions.MqttEntityManager;
|
|||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using NetDaemon.Extensions.Tts;
|
using NetDaemon.Extensions.Tts;
|
||||||
using NetDaemon.Runtime;
|
using NetDaemon.Runtime;
|
||||||
using BoilerMonitorManager;
|
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
using NordPoolManager;
|
using NordPoolManager;
|
||||||
using NordPoolManager.Models;
|
using NordPoolManager.Models;
|
||||||
using PowerMonitorManager;
|
using PowerMonitorManager;
|
||||||
using PowerMonitorManager.Models;
|
using PowerMonitorManager.Models;
|
||||||
using ShowerMonitorManager;
|
using ShowerMonitorManager;
|
||||||
using ShowerMonitorManager.Models;
|
using ShowerMonitorManager.Models;
|
||||||
using LightMonitorManager;
|
|
||||||
using BatteryMonitorManager;
|
|
||||||
using BatteryMonitorManager.Models;
|
|
||||||
using LeakMonitorManager;
|
|
||||||
using LeakMonitorManager.Models;
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -51,7 +52,7 @@ try
|
|||||||
})
|
})
|
||||||
.AddTransient<IEntityManager, EntityManager>()
|
.AddTransient<IEntityManager, EntityManager>()
|
||||||
.AddSingleton(TimeProvider.System)
|
.AddSingleton(TimeProvider.System)
|
||||||
.AddScoped<BoilerMonitor.Models.IBoilerConfigReader, BoilerConfigReader>()
|
.AddScoped<IBoilerConfigReader, BoilerConfigReader>()
|
||||||
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
||||||
.AddNordPool()
|
.AddNordPool()
|
||||||
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager;
|
||||||
|
using LeakMonitorManager.Interface;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LeakMonitor.Models;
|
|
||||||
using LeakMonitorManager;
|
|
||||||
using LeakMonitorManager.Interface;
|
|
||||||
using LeakMonitorManager.Models;
|
|
||||||
|
|
||||||
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();
|
||||||
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new();
|
|
||||||
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new();
|
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new();
|
||||||
|
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new();
|
||||||
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new();
|
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new();
|
||||||
|
|
||||||
public LeakMonitorInitTests()
|
public LeakMonitorInitTests()
|
||||||
@@ -145,7 +145,7 @@ public class LeakMonitorInitTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void InitializeAsync_WhenNoSensorsConfigured_ShouldNotSubscribeAndLogWarning()
|
public void InitializeAsync_WhenNoSensorsConfigured_ShouldNotSubscribeAndLogWarning()
|
||||||
{
|
{
|
||||||
var sut = CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: []));
|
var sut = CreateSut(LeakMonitorTestData.CreateOptions([]));
|
||||||
|
|
||||||
sut.Should().NotBeNull();
|
sut.Should().NotBeNull();
|
||||||
_stateChanges.SubscriptionCount.Should().Be(0);
|
_stateChanges.SubscriptionCount.Should().Be(0);
|
||||||
@@ -169,7 +169,7 @@ public class LeakMonitorInitTests
|
|||||||
[MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))]
|
[MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))]
|
||||||
public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId)
|
public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId)
|
||||||
{
|
{
|
||||||
CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [sensorEntityId]));
|
CreateSut(LeakMonitorTestData.CreateOptions([sensorEntityId]));
|
||||||
|
|
||||||
_stateChanges.SubscriptionCount.Should().Be(1);
|
_stateChanges.SubscriptionCount.Should().Be(1);
|
||||||
|
|
||||||
@@ -186,7 +186,7 @@ public class LeakMonitorInitTests
|
|||||||
public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors()
|
public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors()
|
||||||
{
|
{
|
||||||
CreateSut(LeakMonitorTestData.CreateOptions(
|
CreateSut(LeakMonitorTestData.CreateOptions(
|
||||||
sensorEntityIds: [null!, LeakMonitorTestData.BoilerSensorId]));
|
[null!, LeakMonitorTestData.BoilerSensorId]));
|
||||||
|
|
||||||
_stateChanges.SubscriptionCount.Should().Be(2);
|
_stateChanges.SubscriptionCount.Should().Be(2);
|
||||||
|
|
||||||
@@ -294,9 +294,7 @@ 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),
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LeakMonitor.Models;
|
|
||||||
using LeakMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace LeakMonitor.Manager.Tests;
|
namespace LeakMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -22,20 +22,6 @@ internal static class LeakMonitorTestData
|
|||||||
|
|
||||||
private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Builds leak monitor options with production-compatible defaults.
|
|
||||||
/// Pass <c>[]</c> for no sensors; omit the argument for the shared sensor set.
|
|
||||||
/// </summary>
|
|
||||||
public static LeakMonitorOptions CreateOptions(
|
|
||||||
IEnumerable<string>? sensorEntityIds = null,
|
|
||||||
int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes,
|
|
||||||
bool enabled = true) => new()
|
|
||||||
{
|
|
||||||
Enabled = enabled,
|
|
||||||
SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds],
|
|
||||||
NotificationCooldownMinutes = notificationCooldownMinutes
|
|
||||||
};
|
|
||||||
|
|
||||||
/// <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>
|
||||||
@@ -154,27 +140,52 @@ internal static class LeakMonitorTestData
|
|||||||
("on", "off")
|
("on", "off")
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds leak monitor options with production-compatible defaults.
|
||||||
|
/// Pass <c>[]</c> for no sensors; omit the argument for the shared sensor set.
|
||||||
|
/// </summary>
|
||||||
|
public static LeakMonitorOptions CreateOptions(
|
||||||
|
IEnumerable<string>? sensorEntityIds = null,
|
||||||
|
int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes,
|
||||||
|
bool enabled = true)
|
||||||
|
{
|
||||||
|
return new LeakMonitorOptions
|
||||||
|
{
|
||||||
|
Enabled = enabled,
|
||||||
|
SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds],
|
||||||
|
NotificationCooldownMinutes = notificationCooldownMinutes
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds an <see cref="EntityState" />, or <c>null</c> when the entity has no state at all.
|
/// Builds an <see cref="EntityState" />, or <c>null</c> when the entity has no state at all.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static EntityState? CreateOptionalState(string? state) =>
|
private static EntityState? CreateOptionalState(string? state)
|
||||||
state is null ? null : new EntityState { State = state };
|
{
|
||||||
|
return state is null ? null : new EntityState { State = state };
|
||||||
|
}
|
||||||
|
|
||||||
public static StateChange CreateStateChange(
|
public static StateChange CreateStateChange(
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
string entityId,
|
string entityId,
|
||||||
string? oldState,
|
string? oldState,
|
||||||
string? newState) =>
|
string? newState)
|
||||||
new(new Entity(haContext, entityId), CreateOptionalState(oldState), CreateOptionalState(newState));
|
{
|
||||||
|
return new StateChange(new Entity(haContext, entityId), CreateOptionalState(oldState),
|
||||||
|
CreateOptionalState(newState));
|
||||||
|
}
|
||||||
|
|
||||||
public static IReadOnlyList<StateChange> CreateStateChangeSequence(
|
public static IReadOnlyList<StateChange> CreateStateChangeSequence(
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
string entityId,
|
string entityId,
|
||||||
params (string? OldState, string? NewState)[] transitions) =>
|
params (string? OldState, string? NewState)[] transitions)
|
||||||
[.. transitions.Select(transition => CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))];
|
{
|
||||||
|
return
|
||||||
/// <summary>One captured <c>IHaContext.CallService</c> invocation.</summary>
|
[
|
||||||
public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data);
|
.. transitions.Select(transition =>
|
||||||
|
CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Wires <see cref="IHaContext.CallService" /> on the mock and returns the captured calls
|
/// Wires <see cref="IHaContext.CallService" /> on the mock and returns the captured calls
|
||||||
@@ -197,7 +208,13 @@ internal static class LeakMonitorTestData
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Serialises a captured service-call payload so tests can assert on it.</summary>
|
/// <summary>Serialises a captured service-call payload so tests can assert on it.</summary>
|
||||||
public static JsonElement SerializePayload(object? data) => JsonSerializer.SerializeToElement(data);
|
public static JsonElement SerializePayload(object? data)
|
||||||
|
{
|
||||||
|
return JsonSerializer.SerializeToElement(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One captured <c>IHaContext.CallService</c> invocation.</summary>
|
||||||
|
public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Deterministic clock so cooldown boundaries can be crossed without real waiting.
|
/// Deterministic clock so cooldown boundaries can be crossed without real waiting.
|
||||||
@@ -206,11 +223,20 @@ internal static class LeakMonitorTestData
|
|||||||
{
|
{
|
||||||
private DateTimeOffset _utcNow = start ?? DefaultStart;
|
private DateTimeOffset _utcNow = start ?? DefaultStart;
|
||||||
|
|
||||||
public override DateTimeOffset GetUtcNow() => _utcNow;
|
public override DateTimeOffset GetUtcNow()
|
||||||
|
{
|
||||||
|
return _utcNow;
|
||||||
|
}
|
||||||
|
|
||||||
public void Advance(TimeSpan duration) => _utcNow += duration;
|
public void Advance(TimeSpan duration)
|
||||||
|
{
|
||||||
|
_utcNow += duration;
|
||||||
|
}
|
||||||
|
|
||||||
public void AdvanceSeconds(int seconds) => Advance(TimeSpan.FromSeconds(seconds));
|
public void AdvanceSeconds(int seconds)
|
||||||
|
{
|
||||||
|
Advance(TimeSpan.FromSeconds(seconds));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -232,15 +258,15 @@ internal static class LeakMonitorTestData
|
|||||||
|
|
||||||
public void Publish(T value)
|
public void Publish(T value)
|
||||||
{
|
{
|
||||||
foreach (var observer in _observers.ToArray())
|
foreach (var observer in _observers.ToArray()) observer.OnNext(value);
|
||||||
{
|
|
||||||
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
|
||||||
{
|
{
|
||||||
public void Dispose() => observers.Remove(observer);
|
public void Dispose()
|
||||||
|
{
|
||||||
|
observers.Remove(observer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LeakMonitor.Models;
|
|
||||||
using LeakMonitorManager;
|
|
||||||
using LeakMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace LeakMonitor.Manager.Tests;
|
namespace LeakMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -156,10 +156,7 @@ 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++)
|
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId);
|
||||||
{
|
|
||||||
sut.SendLeakAlert(sensorId);
|
|
||||||
}
|
|
||||||
|
|
||||||
VerifyMobilePush(Times.Once());
|
VerifyMobilePush(Times.Once());
|
||||||
VerifyPersistentCreate(Times.Once());
|
VerifyPersistentCreate(Times.Once());
|
||||||
@@ -172,10 +169,7 @@ 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++)
|
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId);
|
||||||
{
|
|
||||||
sut.SendLeakAlert(sensorId);
|
|
||||||
}
|
|
||||||
|
|
||||||
VerifyMobilePush(Times.Exactly(repeats));
|
VerifyMobilePush(Times.Exactly(repeats));
|
||||||
VerifyPersistentCreate(Times.Exactly(repeats));
|
VerifyPersistentCreate(Times.Exactly(repeats));
|
||||||
@@ -220,10 +214,7 @@ public class LeakNotificationServiceTests
|
|||||||
{
|
{
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds)
|
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds) sut.SendLeakAlert(sensorId);
|
||||||
{
|
|
||||||
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));
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager.Interface;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LeakMonitor.Models;
|
|
||||||
using LeakMonitorManager.Interface;
|
|
||||||
using LeakMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace LeakMonitorManager;
|
namespace LeakMonitorManager;
|
||||||
|
|
||||||
@@ -13,8 +13,8 @@ namespace LeakMonitorManager;
|
|||||||
public sealed class LeakMonitorInit
|
public sealed class LeakMonitorInit
|
||||||
{
|
{
|
||||||
private readonly IHaContext _haContext;
|
private readonly IHaContext _haContext;
|
||||||
private readonly ILeakNotificationService _notificationService;
|
|
||||||
private readonly ILogger<LeakMonitorInit> _logger;
|
private readonly ILogger<LeakMonitorInit> _logger;
|
||||||
|
private readonly ILeakNotificationService _notificationService;
|
||||||
private readonly LeakMonitorOptions _options;
|
private readonly LeakMonitorOptions _options;
|
||||||
|
|
||||||
public LeakMonitorInit(
|
public LeakMonitorInit(
|
||||||
@@ -42,15 +42,11 @@ public sealed class LeakMonitorInit
|
|||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var sensorEntityId in _options.SensorEntityIds)
|
foreach (var sensorEntityId in _options.SensorEntityIds) SubscribeToLeakSensor(sensorEntityId);
|
||||||
{
|
|
||||||
SubscribeToLeakSensor(sensorEntityId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)",
|
||||||
_logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)", _options.SensorEntityIds.Length);
|
_options.SensorEntityIds.Length);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -78,10 +74,8 @@ public sealed class LeakMonitorInit
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId);
|
_logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
internal void HandleStateChange(string sensorEntityId, StateChange change)
|
internal void HandleStateChange(string sensorEntityId, StateChange change)
|
||||||
{
|
{
|
||||||
@@ -96,9 +90,7 @@ public sealed class LeakMonitorInit
|
|||||||
else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase))
|
else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId);
|
_logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId);
|
||||||
}
|
|
||||||
|
|
||||||
_notificationService.DismissLeakAlert(sensorEntityId);
|
_notificationService.DismissLeakAlert(sensorEntityId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
|
using LeakMonitorManager.Interface;
|
||||||
|
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;
|
||||||
using LeakMonitorManager.Interface;
|
|
||||||
using LeakMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace LeakMonitorManager;
|
namespace LeakMonitorManager;
|
||||||
|
|
||||||
@@ -14,10 +14,7 @@ public static class LeakMonitorServiceRegistration
|
|||||||
.GetSection(LeakMonitorOptions.SectionName)
|
.GetSection(LeakMonitorOptions.SectionName)
|
||||||
.Get<LeakMonitorOptions>() ?? new LeakMonitorOptions();
|
.Get<LeakMonitorOptions>() ?? new LeakMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
|
services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using NetDaemon.HassModel;
|
|
||||||
using LeakMonitor.Models;
|
using LeakMonitor.Models;
|
||||||
using LeakMonitorManager.Interface;
|
using LeakMonitorManager.Interface;
|
||||||
using LeakMonitorManager.Models;
|
using LeakMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
namespace LeakMonitorManager;
|
namespace LeakMonitorManager;
|
||||||
|
|
||||||
@@ -14,19 +14,17 @@ public sealed class LeakNotificationService(
|
|||||||
IOptions<LeakMonitorOptions> options,
|
IOptions<LeakMonitorOptions> options,
|
||||||
TimeProvider timeProvider) : ILeakNotificationService
|
TimeProvider timeProvider) : ILeakNotificationService
|
||||||
{
|
{
|
||||||
private readonly LeakMonitorOptions _options = options.Value;
|
|
||||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new();
|
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new();
|
||||||
|
private readonly LeakMonitorOptions _options = options.Value;
|
||||||
|
|
||||||
public void SendLeakAlert(string sensorEntityId)
|
public void SendLeakAlert(string sensorEntityId)
|
||||||
{
|
{
|
||||||
if (IsWithinCooldown(sensorEntityId))
|
if (IsWithinCooldown(sensorEntityId))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Skipping leak notification for {SensorId} -- within cooldown period",
|
"Skipping leak notification for {SensorId} -- within cooldown period",
|
||||||
sensorEntityId);
|
sensorEntityId);
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -52,10 +50,8 @@ public sealed class LeakNotificationService(
|
|||||||
data: new { notification_id = notificationId });
|
data: new { notification_id = notificationId });
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId);
|
logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private void SendMobilePushNotification(string message)
|
private void SendMobilePushNotification(string message)
|
||||||
{
|
{
|
||||||
@@ -95,10 +91,7 @@ public sealed class LeakNotificationService(
|
|||||||
|
|
||||||
private bool IsWithinCooldown(string sensorEntityId)
|
private bool IsWithinCooldown(string sensorEntityId)
|
||||||
{
|
{
|
||||||
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime))
|
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime)) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes);
|
var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes);
|
||||||
return timeProvider.GetUtcNow() - lastTime < cooldown;
|
return timeProvider.GetUtcNow() - lastTime < cooldown;
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
using LightMonitor.Models;
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LightMonitorManager;
|
|
||||||
|
|
||||||
namespace LightMonitor.Manager.Tests;
|
namespace LightMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ public class LightControlServiceTests
|
|||||||
public void TurnOnLight_ShouldTargetTheConfiguredLightEntity()
|
public void TurnOnLight_ShouldTargetTheConfiguredLightEntity()
|
||||||
{
|
{
|
||||||
const string customLightEntityId = "light.kitchen_ceiling";
|
const string customLightEntityId = "light.kitchen_ceiling";
|
||||||
var options = LightMonitorTestData.CreateOptions(lightEntityId: customLightEntityId);
|
var options = LightMonitorTestData.CreateOptions(customLightEntityId);
|
||||||
|
|
||||||
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
|
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
|
||||||
SetupState(customLightEntityId, "off");
|
SetupState(customLightEntityId, "off");
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
using System.Reactive.Subjects;
|
using System.Reactive.Subjects;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using LightMonitor.Models;
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
|
using LightMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LightMonitorManager;
|
|
||||||
using LightMonitorManager.Interface;
|
|
||||||
|
|
||||||
namespace LightMonitor.Manager.Tests;
|
namespace LightMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -16,25 +16,21 @@ public class LightMonitorInitTests
|
|||||||
private const string SunEntityId = LightMonitorTestData.SunEntityId;
|
private const string SunEntityId = LightMonitorTestData.SunEntityId;
|
||||||
private const string PersonEntityId = LightMonitorTestData.PrimaryPersonEntityId;
|
private const string PersonEntityId = LightMonitorTestData.PrimaryPersonEntityId;
|
||||||
|
|
||||||
private readonly Mock<IHaContext> _haContextMock = new();
|
|
||||||
private readonly Mock<IPresenceService> _presenceServiceMock = new();
|
|
||||||
private readonly Mock<ILightControlService> _lightControlServiceMock = new();
|
|
||||||
private readonly Subject<StateChange> _stateChangesSubject = new();
|
|
||||||
|
|
||||||
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||||
|
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new();
|
||||||
|
private readonly Mock<ILightControlService> _lightControlServiceMock = new();
|
||||||
|
private readonly Mock<IPresenceService> _presenceServiceMock = new();
|
||||||
|
private readonly Subject<StateChange> _stateChangesSubject = new();
|
||||||
|
|
||||||
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
|
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
|
||||||
{
|
{
|
||||||
if (subscriptionException is null)
|
if (subscriptionException is null)
|
||||||
{
|
|
||||||
_haContextMock.Setup(x => x.StateAllChanges())
|
_haContextMock.Setup(x => x.StateAllChanges())
|
||||||
.Returns(_stateChangesSubject);
|
.Returns(_stateChangesSubject);
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
_haContextMock.Setup(x => x.StateAllChanges())
|
_haContextMock.Setup(x => x.StateAllChanges())
|
||||||
.Throws(subscriptionException);
|
.Throws(subscriptionException);
|
||||||
}
|
|
||||||
|
|
||||||
return new LightMonitorInit(
|
return new LightMonitorInit(
|
||||||
_haContextMock.Object,
|
_haContextMock.Object,
|
||||||
@@ -57,14 +53,10 @@ public class LightMonitorInitTests
|
|||||||
private void VerifyTurnOn(bool shouldTurnOn)
|
private void VerifyTurnOn(bool shouldTurnOn)
|
||||||
{
|
{
|
||||||
if (shouldTurnOn)
|
if (shouldTurnOn)
|
||||||
{
|
|
||||||
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
|
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
|
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))]
|
[MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))]
|
||||||
@@ -237,7 +229,8 @@ public class LightMonitorInitTests
|
|||||||
{
|
{
|
||||||
CreateSut();
|
CreateSut();
|
||||||
|
|
||||||
EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState, LightMonitorConsts.SunBelowHorizon);
|
EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState,
|
||||||
|
LightMonitorConsts.SunBelowHorizon);
|
||||||
|
|
||||||
VerifyTurnOn(false);
|
VerifyTurnOn(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,33 +32,6 @@ internal static class LightMonitorTestData
|
|||||||
null
|
null
|
||||||
];
|
];
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Builds light monitor options with production-compatible defaults.
|
|
||||||
/// </summary>
|
|
||||||
public static LightMonitorOptions CreateOptions(
|
|
||||||
string lightEntityId = LightEntityId,
|
|
||||||
string sunEntityId = SunEntityId,
|
|
||||||
IEnumerable<string>? personEntityIds = null,
|
|
||||||
bool enabled = true) => new()
|
|
||||||
{
|
|
||||||
Enabled = enabled,
|
|
||||||
LightEntityId = lightEntityId,
|
|
||||||
SunEntityId = sunEntityId,
|
|
||||||
PersonEntityIds = personEntityIds?.ToArray() ?? [.. PersonEntityIds]
|
|
||||||
};
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Builds an <see cref="EntityState"/> carrying <paramref name="state"/>.
|
|
||||||
/// </summary>
|
|
||||||
public static EntityState CreateState(string? state) => new() { State = state };
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Builds an <see cref="EntityState"/>, or <c>null</c> when the entity has no state at all
|
|
||||||
/// (as returned by <c>IHaContext.GetState</c> for a missing entity).
|
|
||||||
/// </summary>
|
|
||||||
public static EntityState? CreateOptionalState(string? state) =>
|
|
||||||
state is null ? null : CreateState(state);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sun states that should (<c>true</c>) or should not (<c>false</c>) cause a light turn on.
|
/// Sun states that should (<c>true</c>) or should not (<c>false</c>) cause a light turn on.
|
||||||
/// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and
|
/// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and
|
||||||
@@ -158,20 +131,49 @@ internal static class LightMonitorTestData
|
|||||||
[" "]
|
[" "]
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds light monitor options with production-compatible defaults.
|
||||||
|
/// </summary>
|
||||||
|
public static LightMonitorOptions CreateOptions(
|
||||||
|
string lightEntityId = LightEntityId,
|
||||||
|
string sunEntityId = SunEntityId,
|
||||||
|
IEnumerable<string>? personEntityIds = null,
|
||||||
|
bool enabled = true)
|
||||||
|
{
|
||||||
|
return new LightMonitorOptions
|
||||||
|
{
|
||||||
|
Enabled = enabled,
|
||||||
|
LightEntityId = lightEntityId,
|
||||||
|
SunEntityId = sunEntityId,
|
||||||
|
PersonEntityIds = personEntityIds?.ToArray() ?? [.. PersonEntityIds]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an <see cref="EntityState" /> carrying <paramref name="state" />.
|
||||||
|
/// </summary>
|
||||||
|
public static EntityState CreateState(string? state)
|
||||||
|
{
|
||||||
|
return new EntityState { State = state };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an <see cref="EntityState" />, or <c>null</c> when the entity has no state at all
|
||||||
|
/// (as returned by <c>IHaContext.GetState</c> for a missing entity).
|
||||||
|
/// </summary>
|
||||||
|
public static EntityState? CreateOptionalState(string? state)
|
||||||
|
{
|
||||||
|
return state is null ? null : CreateState(state);
|
||||||
|
}
|
||||||
|
|
||||||
private static TheoryData<string?[]> CreatePresenceStateMatrix()
|
private static TheoryData<string?[]> CreatePresenceStateMatrix()
|
||||||
{
|
{
|
||||||
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,18 +1,17 @@
|
|||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using LightMonitor.Models;
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using LightMonitorManager;
|
|
||||||
|
|
||||||
namespace LightMonitor.Manager.Tests;
|
namespace LightMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class PresenceServiceTests
|
public class PresenceServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<IHaContext> _haContextMock = new();
|
|
||||||
|
|
||||||
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new();
|
||||||
|
|
||||||
private PresenceService CreateService(LightMonitorOptions? options = null)
|
private PresenceService CreateService(LightMonitorOptions? options = null)
|
||||||
{
|
{
|
||||||
@@ -96,10 +95,8 @@ 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()
|
||||||
@@ -123,8 +120,6 @@ 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,9 +1,9 @@
|
|||||||
|
using LightMonitor.Models;
|
||||||
|
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;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LightMonitor.Models;
|
|
||||||
using LightMonitorManager.Interface;
|
|
||||||
|
|
||||||
namespace LightMonitorManager;
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
@@ -22,9 +22,7 @@ public sealed class LightControlService(
|
|||||||
if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
|
||||||
logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState);
|
logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState);
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -34,9 +32,7 @@ public sealed class LightControlService(
|
|||||||
if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase))
|
if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
|
||||||
logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId);
|
logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId);
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -44,8 +40,6 @@ public sealed class LightControlService(
|
|||||||
haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId));
|
haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId));
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId);
|
logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using LightMonitor.Models;
|
|
||||||
using LightMonitorManager.Interface;
|
|
||||||
|
|
||||||
namespace LightMonitorManager;
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
@@ -12,10 +12,10 @@ namespace LightMonitorManager;
|
|||||||
public sealed class LightMonitorInit
|
public sealed class LightMonitorInit
|
||||||
{
|
{
|
||||||
private readonly IHaContext _haContext;
|
private readonly IHaContext _haContext;
|
||||||
private readonly ILogger<LightMonitorInit> _logger;
|
|
||||||
private readonly IPresenceService _presenceService;
|
|
||||||
private readonly ILightControlService _lightControlService;
|
private readonly ILightControlService _lightControlService;
|
||||||
|
private readonly ILogger<LightMonitorInit> _logger;
|
||||||
private readonly LightMonitorOptions _options;
|
private readonly LightMonitorOptions _options;
|
||||||
|
private readonly IPresenceService _presenceService;
|
||||||
|
|
||||||
public LightMonitorInit(
|
public LightMonitorInit(
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
@@ -41,9 +41,8 @@ public sealed class LightMonitorInit
|
|||||||
SubscribeToPersonStateChanges();
|
SubscribeToPersonStateChanges();
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons",
|
||||||
_logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", _options.PersonEntityIds.Length);
|
_options.PersonEntityIds.Length);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -61,27 +60,20 @@ public sealed class LightMonitorInit
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon,
|
||||||
{
|
StringComparison.OrdinalIgnoreCase)) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IsRecoveryTransition(e.Old?.State))
|
if (IsRecoveryTransition(e.Old?.State))
|
||||||
{
|
{
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State);
|
_logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State);
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_logger.LogInformation("Sun went below horizon, checking if anyone is home");
|
_logger.LogInformation("Sun went below horizon, checking if anyone is home");
|
||||||
|
|
||||||
if (_presenceService.IsAnyoneHome())
|
if (_presenceService.IsAnyoneHome()) _lightControlService.TurnOnLight();
|
||||||
{
|
|
||||||
_lightControlService.TurnOnLight();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -100,25 +92,21 @@ public sealed class LightMonitorInit
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState,
|
||||||
{
|
StringComparison.OrdinalIgnoreCase)) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IsRecoveryTransition(e.Old?.State))
|
if (IsRecoveryTransition(e.Old?.State))
|
||||||
{
|
{
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring",
|
||||||
_logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", personEntityId, e.Old?.State);
|
personEntityId, e.Old?.State);
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation("Person {EntityId} arrived home, checking if it is dark",
|
||||||
_logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId);
|
personEntityId);
|
||||||
}
|
|
||||||
|
|
||||||
_lightControlService.TurnOnLight();
|
_lightControlService.TurnOnLight();
|
||||||
}
|
}
|
||||||
@@ -130,5 +118,8 @@ public sealed class LightMonitorInit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool IsRecoveryTransition(string? oldState) => oldState is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState;
|
private static bool IsRecoveryTransition(string? oldState)
|
||||||
|
{
|
||||||
|
return oldState is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
using LightMonitor.Models;
|
using LightMonitor.Models;
|
||||||
|
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;
|
||||||
using LightMonitorManager.Interface;
|
|
||||||
|
|
||||||
namespace LightMonitorManager;
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
@@ -14,10 +14,7 @@ public static class LightMonitorServiceRegistration
|
|||||||
.GetSection(LightMonitorOptions.SectionName)
|
.GetSection(LightMonitorOptions.SectionName)
|
||||||
.Get<LightMonitorOptions>() ?? new LightMonitorOptions();
|
.Get<LightMonitorOptions>() ?? new LightMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled) return services;
|
||||||
{
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
services.AddNetDaemonApp<LightMonitorInit>()
|
services.AddNetDaemonApp<LightMonitorInit>()
|
||||||
.AddScoped<IPresenceService, PresenceService>()
|
.AddScoped<IPresenceService, PresenceService>()
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
|
using LightMonitor.Models;
|
||||||
|
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;
|
||||||
using LightMonitor.Models;
|
|
||||||
using LightMonitorManager.Interface;
|
|
||||||
|
|
||||||
namespace LightMonitorManager;
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
@@ -20,19 +20,12 @@ public sealed class PresenceService(
|
|||||||
var state = haContext.GetState(personEntityId);
|
var state = haContext.GetState(personEntityId);
|
||||||
|
|
||||||
if (state?.State is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState)
|
if (state?.State is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState)
|
||||||
{
|
|
||||||
continue;
|
continue;
|
||||||
}
|
|
||||||
|
|
||||||
if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState,
|
||||||
{
|
StringComparison.OrdinalIgnoreCase)) continue;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Person {EntityId} is home", personEntityId);
|
||||||
{
|
|
||||||
logger.LogDebug("Person {EntityId} is home", personEntityId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,17 +5,17 @@ public static class LightMonitorConsts
|
|||||||
public const string DefaultLightEntityId = "light.sonoff_1002214d40";
|
public const string DefaultLightEntityId = "light.sonoff_1002214d40";
|
||||||
public const string DefaultSunEntityId = "sun.sun";
|
public const string DefaultSunEntityId = "sun.sun";
|
||||||
|
|
||||||
public static readonly string[] DefaultPersonEntityIds =
|
|
||||||
[
|
|
||||||
"person.marius",
|
|
||||||
"person.erika",
|
|
||||||
"person.home_phone"
|
|
||||||
];
|
|
||||||
|
|
||||||
public const string SunBelowHorizon = "below_horizon";
|
public const string SunBelowHorizon = "below_horizon";
|
||||||
public const string SunAboveHorizon = "above_horizon";
|
public const string SunAboveHorizon = "above_horizon";
|
||||||
public const string PersonHomeState = "home";
|
public const string PersonHomeState = "home";
|
||||||
public const string LightOnState = "on";
|
public const string LightOnState = "on";
|
||||||
public const string UnavailableState = "unavailable";
|
public const string UnavailableState = "unavailable";
|
||||||
public const string UnknownState = "unknown";
|
public const string UnknownState = "unknown";
|
||||||
|
|
||||||
|
public static readonly string[] DefaultPersonEntityIds =
|
||||||
|
[
|
||||||
|
"person.marius",
|
||||||
|
"person.erika",
|
||||||
|
"person.home_phone"
|
||||||
|
];
|
||||||
}
|
}
|
||||||
@@ -8,16 +8,25 @@ namespace NordPool.Manager.Tests;
|
|||||||
|
|
||||||
public class CheapestIntervalsFinderTests
|
public class CheapestIntervalsFinderTests
|
||||||
{
|
{
|
||||||
|
private const int Hour = 3_600;
|
||||||
|
private const int Quarter = 15 * 60;
|
||||||
private static readonly DateTime DayStart = NordPoolTestData.DayStart;
|
private static readonly DateTime 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();
|
||||||
|
|
||||||
private CheapestIntervalsFinder CreateSut() => new(_loggerMock.Object);
|
private CheapestIntervalsFinder CreateSut()
|
||||||
|
{
|
||||||
|
return new CheapestIntervalsFinder(_loggerMock.Object);
|
||||||
|
}
|
||||||
|
|
||||||
private static bool IsPrice(double actual, double expected) => Math.Abs(actual - expected) < 0.000_001;
|
private static bool IsPrice(double actual, double expected)
|
||||||
|
{
|
||||||
|
return Math.Abs(actual - expected) < 0.000_001;
|
||||||
|
}
|
||||||
|
|
||||||
private static NordPoolPrice CreatePricesForDay(DateTime dayStart, int intervalCount = NordPoolConsts.MaxDailyIntervals)
|
private static NordPoolPrice CreatePricesForDay(DateTime dayStart,
|
||||||
|
int intervalCount = NordPoolConsts.MaxDailyIntervals)
|
||||||
{
|
{
|
||||||
return new NordPoolPrice
|
return new NordPoolPrice
|
||||||
{
|
{
|
||||||
@@ -44,9 +53,6 @@ public class CheapestIntervalsFinderTests
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private const int Hour = 3_600;
|
|
||||||
private const int Quarter = 15 * 60;
|
|
||||||
|
|
||||||
#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()
|
||||||
@@ -314,12 +320,25 @@ public class CheapestIntervalsFinderTests
|
|||||||
("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
|
("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
|
||||||
("exactly at start", 10 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
|
("exactly at start", 10 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
|
||||||
("exactly at end", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
|
("exactly at end", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
|
||||||
("outside all intervals", 12 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false),
|
("outside all intervals", 12 * Hour,
|
||||||
("boundary between adjacent intervals", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter, price: 8.96, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, price: 6.20, rank: 2)], true),
|
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false),
|
||||||
("unsorted intervals", 14 * Hour + 5 * 60, [Interval(14 * Hour, 14 * Hour + Quarter, price: 4.93, rank: 2), Interval(10 * Hour, 10 * Hour + Quarter, price: 6.20, rank: 1)], true),
|
("boundary between adjacent intervals", 10 * Hour + Quarter,
|
||||||
|
[
|
||||||
|
Interval(10 * Hour, 10 * Hour + Quarter, 8.96),
|
||||||
|
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, 6.20, 2)
|
||||||
|
], true),
|
||||||
|
("unsorted intervals", 14 * Hour + 5 * 60,
|
||||||
|
[Interval(14 * Hour, 14 * Hour + Quarter, 4.93, 2), Interval(10 * Hour, 10 * Hour + Quarter, 6.20)],
|
||||||
|
true),
|
||||||
("before first interval", 10 * Hour - 1, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
|
("before first interval", 10 * Hour - 1, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
|
||||||
("in gap between intervals", 10 * Hour + 2 * Quarter, [Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false),
|
("in gap between intervals", 10 * Hour + 2 * Quarter,
|
||||||
("middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60, [Interval(10 * Hour, 10 * Hour + Quarter, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2), Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3)], true),
|
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false),
|
||||||
|
("middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60,
|
||||||
|
[
|
||||||
|
Interval(10 * Hour, 10 * Hour + Quarter, rank: 1),
|
||||||
|
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2),
|
||||||
|
Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3)
|
||||||
|
], true),
|
||||||
("empty interval list", 12 * Hour, [], false)
|
("empty interval list", 12 * Hour, [], false)
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using NordPool.Models;
|
using NordPool.Models;
|
||||||
@@ -14,6 +15,18 @@ public class CompactNordPoolDayPriceTests
|
|||||||
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()
|
||||||
|
{
|
||||||
|
{ "empty array", "[]" },
|
||||||
|
{ "too few elements", "[1,2]" },
|
||||||
|
{ "extra elements", "[1,2,3,4]" },
|
||||||
|
{ "missing end of array", "[1,2,3" },
|
||||||
|
{ "non-numeric start", "[\"abc\",2,3]" },
|
||||||
|
{ "non-numeric end", "[1,\"abc\",3]" },
|
||||||
|
{ "non-numeric price", "[1,2,\"abc\"]" },
|
||||||
|
{ "object instead of array", "{\"start\":1}" }
|
||||||
|
};
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void FromDayPrice_ShouldConvertDateTimesToUnixEpochSeconds()
|
public void FromDayPrice_ShouldConvertDateTimesToUnixEpochSeconds()
|
||||||
{
|
{
|
||||||
@@ -150,7 +163,9 @@ public class CompactNordPoolDayPriceTests
|
|||||||
|
|
||||||
var json = JsonSerializer.Serialize(prices);
|
var json = JsonSerializer.Serialize(prices);
|
||||||
|
|
||||||
json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]");
|
json.Should()
|
||||||
|
.Be(
|
||||||
|
$"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -161,18 +176,6 @@ public class CompactNordPoolDayPriceTests
|
|||||||
act.Should().Throw<ArgumentNullException>();
|
act.Should().Throw<ArgumentNullException>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static TheoryData<string, string> InvalidJsonPayloads => new()
|
|
||||||
{
|
|
||||||
{ "empty array", "[]" },
|
|
||||||
{ "too few elements", "[1,2]" },
|
|
||||||
{ "extra elements", "[1,2,3,4]" },
|
|
||||||
{ "missing end of array", "[1,2,3" },
|
|
||||||
{ "non-numeric start", "[\"abc\",2,3]" },
|
|
||||||
{ "non-numeric end", "[1,\"abc\",3]" },
|
|
||||||
{ "non-numeric price", "[1,2,\"abc\"]" },
|
|
||||||
{ "object instead of array", "{\"start\":1}" }
|
|
||||||
};
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[MemberData(nameof(InvalidJsonPayloads))]
|
[MemberData(nameof(InvalidJsonPayloads))]
|
||||||
public void JsonDeserialization_WithInvalidPayload_ShouldThrowJsonException(string scenario, string json)
|
public void JsonDeserialization_WithInvalidPayload_ShouldThrowJsonException(string scenario, string json)
|
||||||
@@ -237,7 +240,8 @@ public class CompactNordPoolDayPriceTests
|
|||||||
result.Should().HaveCount(96);
|
result.Should().HaveCount(96);
|
||||||
result.Should().BeInAscendingOrder(p => p.Start);
|
result.Should().BeInAscendingOrder(p => p.Start);
|
||||||
result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds());
|
result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds());
|
||||||
result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval)).ToUnixTimeSeconds());
|
result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
|
||||||
|
.ToUnixTimeSeconds());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -284,7 +288,7 @@ public class CompactNordPoolDayPriceTests
|
|||||||
last_updated = DateTime.UtcNow.ToString("O")
|
last_updated = DateTime.UtcNow.ToString("O")
|
||||||
};
|
};
|
||||||
var json = JsonSerializer.Serialize(attributePayload);
|
var json = JsonSerializer.Serialize(attributePayload);
|
||||||
var byteCount = System.Text.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 @@
|
|||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using HomeAssistant.Entities.Interfaces;
|
using HomeAssistant.Entities.Interfaces;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -266,7 +268,8 @@ public class NordPoolEntityServiceTests
|
|||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), 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"), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"),
|
||||||
|
Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("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);
|
||||||
}
|
}
|
||||||
@@ -284,13 +287,20 @@ public class NordPoolEntityServiceTests
|
|||||||
await _sut.ResetEntitiesAsync();
|
await _sut.ResetEntitiesAsync();
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", 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>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
|
Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
|
||||||
|
Times.Once);
|
||||||
|
_entityManagerMock.Verify(
|
||||||
|
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
||||||
|
_entityManagerMock.Verify(
|
||||||
|
em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()),
|
||||||
|
Times.Once);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -299,7 +309,8 @@ 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 => em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
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);
|
||||||
@@ -325,7 +336,8 @@ 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>()), Times.Exactly(7));
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||||
|
Times.Exactly(7));
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -378,12 +390,16 @@ public class NordPoolEntityServiceTests
|
|||||||
await _sut.UpdateEntitiesAsync(context);
|
await _sut.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()),
|
||||||
|
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(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
|
_entityManagerMock.Verify(
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()), Times.Once);
|
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices",
|
||||||
|
It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()),
|
||||||
|
Times.Once);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -401,10 +417,14 @@ public class NordPoolEntityServiceTests
|
|||||||
await _sut.UpdateEntitiesAsync(context);
|
await _sut.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", 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>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
|
||||||
|
Times.Once);
|
||||||
|
_entityManagerMock.Verify(
|
||||||
|
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -448,26 +468,46 @@ public class NordPoolEntityServiceTests
|
|||||||
{
|
{
|
||||||
Prices =
|
Prices =
|
||||||
[
|
[
|
||||||
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
|
new NordPoolDayPrice
|
||||||
|
{
|
||||||
|
Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91
|
||||||
|
},
|
||||||
new NordPoolDayPrice { Start = null, End = todayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
|
new NordPoolDayPrice { Start = null, End = todayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
new NordPoolPrice
|
new NordPoolPrice
|
||||||
{
|
{
|
||||||
Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }]
|
Prices =
|
||||||
|
[
|
||||||
|
new NordPoolDayPrice
|
||||||
|
{ Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }
|
||||||
|
]
|
||||||
},
|
},
|
||||||
2
|
2
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"only today",
|
"only today",
|
||||||
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] },
|
new NordPoolPrice
|
||||||
|
{
|
||||||
|
Prices =
|
||||||
|
[
|
||||||
|
new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }
|
||||||
|
]
|
||||||
|
},
|
||||||
new NordPoolPrice { Prices = [] },
|
new NordPoolPrice { Prices = [] },
|
||||||
1
|
1
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"only tomorrow",
|
"only tomorrow",
|
||||||
new NordPoolPrice { Prices = [] },
|
new NordPoolPrice { Prices = [] },
|
||||||
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] },
|
new NordPoolPrice
|
||||||
|
{
|
||||||
|
Prices =
|
||||||
|
[
|
||||||
|
new NordPoolDayPrice
|
||||||
|
{ Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }
|
||||||
|
]
|
||||||
|
},
|
||||||
1
|
1
|
||||||
),
|
),
|
||||||
("empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0),
|
("empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0),
|
||||||
@@ -481,10 +521,13 @@ public class NordPoolEntityServiceTests
|
|||||||
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_today_tomorrow_prices", It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
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 => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||||
|
It.IsAny<object>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
var context = CreateDefaultContext() with
|
var context = CreateDefaultContext() with
|
||||||
@@ -513,12 +556,15 @@ public class NordPoolEntityServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
var todayPrice = new NordPoolPrice
|
var todayPrice = new NordPoolPrice
|
||||||
{
|
{
|
||||||
Prices = [new NordPoolDayPrice
|
Prices =
|
||||||
|
[
|
||||||
|
new NordPoolDayPrice
|
||||||
{
|
{
|
||||||
Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc),
|
Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc),
|
||||||
End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc),
|
End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc),
|
||||||
Price = 17.91
|
Price = 17.91
|
||||||
}]
|
}
|
||||||
|
]
|
||||||
};
|
};
|
||||||
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
|
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
|
||||||
|
|
||||||
@@ -563,10 +609,13 @@ public class NordPoolEntityServiceTests
|
|||||||
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_today_tomorrow_prices", It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
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 => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||||
|
It.IsAny<object>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
var context = CreateDefaultContext(
|
var context = CreateDefaultContext(
|
||||||
@@ -578,8 +627,8 @@ public class NordPoolEntityServiceTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
capturedAttributes.Should().NotBeNull();
|
capturedAttributes.Should().NotBeNull();
|
||||||
var json = System.Text.Json.JsonSerializer.Serialize(capturedAttributes);
|
var json = JsonSerializer.Serialize(capturedAttributes);
|
||||||
var byteCount = System.Text.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");
|
||||||
}
|
}
|
||||||
@@ -590,10 +639,11 @@ public class NordPoolEntityServiceTests
|
|||||||
[InlineData(-5.25, "-5.25")]
|
[InlineData(-5.25, "-5.25")]
|
||||||
[InlineData(1234.5, "1234.50")]
|
[InlineData(1234.5, "1234.50")]
|
||||||
[InlineData(17.916, "17.92")]
|
[InlineData(17.916, "17.92")]
|
||||||
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, string expected)
|
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price,
|
||||||
|
string expected)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var context = CreateDefaultContext(currentPrice: price);
|
var context = CreateDefaultContext(price);
|
||||||
|
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
@@ -617,7 +667,8 @@ public class NordPoolEntityServiceTests
|
|||||||
_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 => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
var context = CreateDefaultContext() with
|
var context = CreateDefaultContext() with
|
||||||
@@ -654,7 +705,9 @@ public class NordPoolEntityServiceTests
|
|||||||
_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 => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
|
||||||
|
It.IsAny<object>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
var first = new CheapestIntervalResult
|
var first = new CheapestIntervalResult
|
||||||
@@ -693,7 +746,8 @@ 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().HaveCount(2);
|
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should()
|
||||||
|
.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"));
|
||||||
@@ -714,7 +768,9 @@ public class NordPoolEntityServiceTests
|
|||||||
_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 => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
|
||||||
|
It.IsAny<object>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
var context = CreateDefaultContext() with { CheapestIntervals = null };
|
var context = CreateDefaultContext() with { CheapestIntervals = null };
|
||||||
@@ -740,10 +796,13 @@ public class NordPoolEntityServiceTests
|
|||||||
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_today_tomorrow_prices", It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
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 => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
|
_entityManagerMock.Setup(em =>
|
||||||
|
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
|
||||||
|
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);
|
||||||
@@ -751,7 +810,8 @@ public class NordPoolEntityServiceTests
|
|||||||
{
|
{
|
||||||
Prices =
|
Prices =
|
||||||
[
|
[
|
||||||
new NordPoolDayPrice { Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
|
new NordPoolDayPrice
|
||||||
|
{ Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
|
||||||
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
|
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
@@ -759,7 +819,8 @@ public class NordPoolEntityServiceTests
|
|||||||
{
|
{
|
||||||
Prices =
|
Prices =
|
||||||
[
|
[
|
||||||
new NordPoolDayPrice { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
|
new NordPoolDayPrice
|
||||||
|
{ Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
|
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
|
||||||
@@ -813,7 +874,8 @@ public class NordPoolEntityServiceTests
|
|||||||
l => l.Log(
|
l => l.Log(
|
||||||
LogLevel.Warning,
|
LogLevel.Warning,
|
||||||
It.IsAny<EventId>(),
|
It.IsAny<EventId>(),
|
||||||
It.Is<It.IsAnyType>((state, _) => state != null && state.ToString()!.Contains("exceeds expected maximum")),
|
It.Is<It.IsAnyType>((state, _) =>
|
||||||
|
state != null && state.ToString()!.Contains("exceeds expected maximum")),
|
||||||
It.IsAny<Exception?>(),
|
It.IsAny<Exception?>(),
|
||||||
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
|
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
|
||||||
Times.Once);
|
Times.Once);
|
||||||
@@ -826,7 +888,7 @@ public class NordPoolEntityServiceTests
|
|||||||
public static TheoryData<string, Func<NordPoolEntityService, Task>> CancelledOperations()
|
public static TheoryData<string, Func<NordPoolEntityService, Task>> CancelledOperations()
|
||||||
{
|
{
|
||||||
var data = new TheoryData<string, Func<NordPoolEntityService, Task>>();
|
var data = new TheoryData<string, Func<NordPoolEntityService, Task>>();
|
||||||
var cancelled = new CancellationToken(canceled: true);
|
var cancelled = new CancellationToken(true);
|
||||||
var context = CreateDefaultContext();
|
var context = CreateDefaultContext();
|
||||||
|
|
||||||
data.Add("create entities", sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled));
|
data.Add("create entities", sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled));
|
||||||
|
|||||||
@@ -15,14 +15,14 @@ namespace NordPool.Manager.Tests;
|
|||||||
|
|
||||||
public class NordPoolInitTests
|
public class NordPoolInitTests
|
||||||
{
|
{
|
||||||
|
private readonly Mock<INordPoolBoilerConfigProvider> _boilerConfigProviderMock;
|
||||||
|
private readonly Mock<ICheapestIntervalsFinder> _cheapestIntervalsFinderMock;
|
||||||
|
private readonly Entities _entities;
|
||||||
|
private readonly Mock<INordPoolEntityService> _entityServiceMock;
|
||||||
|
private readonly Mock<IHaContext> _haContextMock;
|
||||||
private readonly Mock<ILogger<NordPoolInit>> _loggerMock;
|
private readonly Mock<ILogger<NordPoolInit>> _loggerMock;
|
||||||
private readonly Mock<INordPoolPriceService> _priceServiceMock;
|
private readonly Mock<INordPoolPriceService> _priceServiceMock;
|
||||||
private readonly Mock<INordPoolEntityService> _entityServiceMock;
|
|
||||||
private readonly Mock<IScheduler> _schedulerMock;
|
private readonly Mock<IScheduler> _schedulerMock;
|
||||||
private readonly Mock<ICheapestIntervalsFinder> _cheapestIntervalsFinderMock;
|
|
||||||
private readonly Mock<INordPoolBoilerConfigProvider> _boilerConfigProviderMock;
|
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
|
||||||
private readonly Entities _entities;
|
|
||||||
|
|
||||||
public NordPoolInitTests()
|
public NordPoolInitTests()
|
||||||
{
|
{
|
||||||
@@ -37,10 +37,12 @@ public class NordPoolInitTests
|
|||||||
_entities = new Entities(_haContextMock.Object);
|
_entities = new Entities(_haContextMock.Object);
|
||||||
|
|
||||||
_priceServiceMock.Setup(p => p.FetchPricesAsync()).Returns(Task.CompletedTask);
|
_priceServiceMock.Setup(p => p.FetchPricesAsync()).Returns(Task.CompletedTask);
|
||||||
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>())).Returns(Task.CompletedTask);
|
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>()))
|
||||||
|
.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>())).Returns(Task.CompletedTask);
|
_entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>()))
|
||||||
|
.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);
|
||||||
@@ -49,7 +51,8 @@ public class NordPoolInitTests
|
|||||||
_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>>(), It.IsAny<DateTime>()))
|
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
|
||||||
|
It.IsAny<DateTime>()))
|
||||||
.Returns(false);
|
.Returns(false);
|
||||||
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig
|
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig
|
||||||
{
|
{
|
||||||
@@ -101,9 +104,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>()), Times.AtLeastOnce);
|
_entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()),
|
||||||
|
Times.AtLeastOnce);
|
||||||
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce);
|
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce);
|
||||||
_entityServiceMock.Verify(es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.AtLeastOnce);
|
_entityServiceMock.Verify(
|
||||||
|
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
|
||||||
|
Times.AtLeastOnce);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -118,6 +124,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(es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never);
|
_entityServiceMock.Verify(
|
||||||
|
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -115,14 +115,12 @@ 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);
|
||||||
@@ -133,7 +131,8 @@ 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, int minute, int expectedIndex)
|
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, 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);
|
||||||
@@ -233,7 +232,14 @@ public class NordPoolPriceServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
var dto = new NordPoolPriceResultDto
|
var dto = new NordPoolPriceResultDto
|
||||||
{
|
{
|
||||||
Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }]
|
Prices =
|
||||||
|
[
|
||||||
|
new NordPoolDayPriceDto
|
||||||
|
{
|
||||||
|
Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"),
|
||||||
|
Price = 100.0
|
||||||
|
}
|
||||||
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
var jsonString = JsonSerializer.Serialize(dto);
|
var jsonString = JsonSerializer.Serialize(dto);
|
||||||
@@ -243,7 +249,11 @@ public class NordPoolPriceServiceTests
|
|||||||
{
|
{
|
||||||
Prices = new List<NordPoolDayPrice>
|
Prices = new List<NordPoolDayPrice>
|
||||||
{
|
{
|
||||||
new() { Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture), End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0 }
|
new()
|
||||||
|
{
|
||||||
|
Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture),
|
||||||
|
End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -265,7 +275,14 @@ public class NordPoolPriceServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
var dto = new NordPoolPriceResultDto
|
var dto = new NordPoolPriceResultDto
|
||||||
{
|
{
|
||||||
Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }]
|
Prices =
|
||||||
|
[
|
||||||
|
new NordPoolDayPriceDto
|
||||||
|
{
|
||||||
|
Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"),
|
||||||
|
Price = 100.0
|
||||||
|
}
|
||||||
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
var jsonString = JsonSerializer.Serialize(dto);
|
var jsonString = JsonSerializer.Serialize(dto);
|
||||||
@@ -456,14 +473,12 @@ 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 };
|
||||||
|
|
||||||
@@ -667,10 +682,13 @@ public class NordPoolPriceServiceTests
|
|||||||
|
|
||||||
#region ShouldFetchNewPrices
|
#region ShouldFetchNewPrices
|
||||||
|
|
||||||
private static NordPoolPrice CreatePrices(params double?[] values) => new()
|
private static NordPoolPrice CreatePrices(params double?[] values)
|
||||||
|
{
|
||||||
|
return new NordPoolPrice
|
||||||
{
|
{
|
||||||
Prices = [.. values.Select(price => new NordPoolDayPrice { Price = price })]
|
Prices = [.. values.Select(price => new NordPoolDayPrice { Price = price })]
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00,
|
/// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00,
|
||||||
@@ -682,7 +700,8 @@ public class NordPoolPriceServiceTests
|
|||||||
{
|
{
|
||||||
var today = DateOnly.FromDateTime(DateTime.Now);
|
var today = DateOnly.FromDateTime(DateTime.Now);
|
||||||
|
|
||||||
(string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, bool Expected)[] cases =
|
(string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, bool
|
||||||
|
Expected)[] cases =
|
||||||
[
|
[
|
||||||
("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true),
|
("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true),
|
||||||
("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), true),
|
("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), true),
|
||||||
@@ -690,7 +709,8 @@ public class NordPoolPriceServiceTests
|
|||||||
("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true),
|
("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true),
|
||||||
("today prices are empty", today, new NordPoolPrice { Prices = [] }, CreatePrices(18.71), true),
|
("today prices are empty", today, new NordPoolPrice { Prices = [] }, CreatePrices(18.71), true),
|
||||||
("today and tomorrow prices present", today, CreatePrices(12.50), CreatePrices(18.71), false),
|
("today and tomorrow prices present", today, CreatePrices(12.50), CreatePrices(18.71), false),
|
||||||
("price values are null but entries exist", today, CreatePrices((double?)null), CreatePrices((double?)null), false),
|
("price values are null but entries exist", today, CreatePrices((double?)null),
|
||||||
|
CreatePrices((double?)null), false),
|
||||||
("all price payloads are null", today, null, null, true)
|
("all price payloads are null", today, null, null, true)
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -789,7 +809,7 @@ public class NordPoolPriceServiceTests
|
|||||||
foreach (var tomorrow in unusablePrices)
|
foreach (var tomorrow in unusablePrices)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = [new() { Price = 12.50 }] };
|
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = [new NordPoolDayPrice { Price = 12.50 }] };
|
||||||
_sut.TomorrowNordPoolPrice = tomorrow;
|
_sut.TomorrowNordPoolPrice = tomorrow;
|
||||||
_sut.DayQuartersIndex = 42;
|
_sut.DayQuartersIndex = 42;
|
||||||
var today = new DateOnly(2026, 4, 1);
|
var today = new DateOnly(2026, 4, 1);
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ namespace NordPoolManager;
|
|||||||
|
|
||||||
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
||||||
{
|
{
|
||||||
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
|
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
|
||||||
|
double priceCap, DateTime deadline)
|
||||||
{
|
{
|
||||||
if (prices.Prices is not { Count: > 0 })
|
if (prices.Prices is not { Count: > 0 })
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ namespace NordPoolManager.Interface;
|
|||||||
|
|
||||||
public interface ICheapestIntervalsFinder
|
public interface ICheapestIntervalsFinder
|
||||||
{
|
{
|
||||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline);
|
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
|
||||||
|
double priceCap, DateTime deadline);
|
||||||
|
|
||||||
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
||||||
}
|
}
|
||||||
@@ -8,5 +8,8 @@ namespace NordPoolManager;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class NordPoolBoilerConfigProvider(IBoilerConfigReader boilerConfigReader) : INordPoolBoilerConfigProvider
|
public sealed class NordPoolBoilerConfigProvider(IBoilerConfigReader boilerConfigReader) : INordPoolBoilerConfigProvider
|
||||||
{
|
{
|
||||||
public BoilerConfig GetCurrentConfiguration() => boilerConfigReader.ReadConfig();
|
public BoilerConfig GetCurrentConfiguration()
|
||||||
|
{
|
||||||
|
return boilerConfigReader.ReadConfig();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,8 @@ using NordPoolManager.Models;
|
|||||||
|
|
||||||
namespace NordPoolManager;
|
namespace NordPoolManager;
|
||||||
|
|
||||||
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger) : INordPoolEntityService
|
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger)
|
||||||
|
: INordPoolEntityService
|
||||||
{
|
{
|
||||||
private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time";
|
private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time";
|
||||||
private const string TodayPricesEntityId = "sensor.nordpool_today_prices";
|
private const string TodayPricesEntityId = "sensor.nordpool_today_prices";
|
||||||
@@ -63,6 +64,59 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
).ConfigureAwait(false);
|
).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
var utcNow = DateTime.UtcNow;
|
||||||
|
var timestamp = utcNow.ToString("O");
|
||||||
|
var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
|
||||||
|
var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture);
|
||||||
|
var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0;
|
||||||
|
var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0;
|
||||||
|
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
|
||||||
|
|
||||||
|
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
||||||
|
logger.LogWarning(
|
||||||
|
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
||||||
|
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||||
|
|
||||||
|
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
logger.LogInformation(
|
||||||
|
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
|
||||||
|
cheapestCount, ctx.IsNowCheap);
|
||||||
|
|
||||||
|
var updateTasks = new[]
|
||||||
|
{
|
||||||
|
UpdateLastUpdateTimeAsync(updateTimeState),
|
||||||
|
UpdateCurrentPriceAsync(priceValue, ctx, timestamp),
|
||||||
|
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
|
||||||
|
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
|
||||||
|
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
|
||||||
|
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp)
|
||||||
|
};
|
||||||
|
|
||||||
|
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
|
||||||
|
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error cleaning up NordPool entities");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task ResetLastUpdateTimeAsync()
|
private async Task ResetLastUpdateTimeAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
|
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
|
||||||
@@ -149,43 +203,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
|
||||||
|
|
||||||
var utcNow = DateTime.UtcNow;
|
|
||||||
var timestamp = utcNow.ToString("O");
|
|
||||||
var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
|
|
||||||
var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture);
|
|
||||||
var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0;
|
|
||||||
var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0;
|
|
||||||
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
|
|
||||||
|
|
||||||
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
|
||||||
{
|
|
||||||
logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
|
||||||
}
|
|
||||||
|
|
||||||
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
|
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
|
||||||
{
|
|
||||||
logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap);
|
|
||||||
}
|
|
||||||
|
|
||||||
var updateTasks = new[]
|
|
||||||
{
|
|
||||||
UpdateLastUpdateTimeAsync(updateTimeState),
|
|
||||||
UpdateCurrentPriceAsync(priceValue, ctx, timestamp),
|
|
||||||
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
|
|
||||||
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
|
|
||||||
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
|
|
||||||
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp)
|
|
||||||
};
|
|
||||||
|
|
||||||
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
|
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(LastUpdateTimeEntityId, updateTimeState).ConfigureAwait(false);
|
await SetEntityStateSafe(LastUpdateTimeEntityId, updateTimeState).ConfigureAwait(false);
|
||||||
@@ -229,7 +246,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState, string timestamp)
|
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState,
|
||||||
|
string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false);
|
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
|
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
|
||||||
@@ -260,22 +278,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
|
|
||||||
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, "Error cleaning up NordPool entities");
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
|
internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
|
||||||
{
|
{
|
||||||
const string currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId;
|
const string currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId;
|
||||||
|
|||||||
@@ -17,19 +17,16 @@ namespace NordPoolManager;
|
|||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public class NordPoolInit
|
public class NordPoolInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<NordPoolInit> _logger;
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly INordPoolPriceService _priceService;
|
|
||||||
private readonly INordPoolEntityService _entityService;
|
|
||||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
|
||||||
private readonly INordPoolBoilerConfigProvider _boilerConfigProvider;
|
private readonly INordPoolBoilerConfigProvider _boilerConfigProvider;
|
||||||
private readonly IScheduler _scheduler;
|
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
||||||
|
private readonly INordPoolEntityService _entityService;
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<NordPoolInit> _logger;
|
||||||
private readonly NordPoolOptions _options;
|
private readonly NordPoolOptions _options;
|
||||||
|
private readonly INordPoolPriceService _priceService;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
private readonly TimeProvider _timeProvider;
|
private readonly TimeProvider _timeProvider;
|
||||||
|
|
||||||
private string? UnitOfMeasurement { get; }
|
|
||||||
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
|
|
||||||
|
|
||||||
public NordPoolInit(
|
public NordPoolInit(
|
||||||
Entities entities,
|
Entities entities,
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
@@ -58,16 +55,16 @@ public class NordPoolInit
|
|||||||
_ = InitializeAndScheduleAsync();
|
_ = InitializeAndScheduleAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string? UnitOfMeasurement { get; }
|
||||||
|
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
public async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||||
|
|
||||||
if (_options.CleanupEntitiesOnStartup)
|
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync();
|
||||||
{
|
|
||||||
await _entityService.CleanupEntitiesAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
|
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
|
||||||
await _entityService.ResetEntitiesAsync();
|
await _entityService.ResetEntitiesAsync();
|
||||||
@@ -118,14 +115,9 @@ public class NordPoolInit
|
|||||||
var today = DateOnly.FromDateTime(nowCet);
|
var today = DateOnly.FromDateTime(nowCet);
|
||||||
|
|
||||||
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
|
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
|
||||||
{
|
|
||||||
_priceService.RollOverPrices(today);
|
_priceService.RollOverPrices(today);
|
||||||
}
|
|
||||||
|
|
||||||
if (_priceService.ShouldFetchNewPrices(today))
|
if (_priceService.ShouldFetchNewPrices(today)) await _priceService.FetchPricesAsync();
|
||||||
{
|
|
||||||
await _priceService.FetchPricesAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
_priceService.UpdateCurrentPrice();
|
_priceService.UpdateCurrentPrice();
|
||||||
|
|
||||||
@@ -165,7 +157,8 @@ public class NordPoolInit
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline);
|
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice,
|
||||||
|
effectiveIntervalCount, effectivePriceCap, config.Deadline);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -183,7 +176,8 @@ public class NordPoolInit
|
|||||||
var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour;
|
var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour;
|
||||||
var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
|
var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
|
var isNowCheap = CheapestIntervals != null &&
|
||||||
|
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
|
||||||
|
|
||||||
var nextCheapInterval = CheapestIntervals?
|
var nextCheapInterval = CheapestIntervals?
|
||||||
.Where(i => i.Start > currentDateTime)
|
.Where(i => i.Start > currentDateTime)
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ using NordPoolManager.Models.Consts;
|
|||||||
|
|
||||||
namespace NordPoolManager;
|
namespace NordPoolManager;
|
||||||
|
|
||||||
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger) : INordPoolPriceService
|
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger)
|
||||||
|
: INordPoolPriceService
|
||||||
{
|
{
|
||||||
private readonly NordpoolServices _nordPoolServices = services.Nordpool;
|
private readonly NordpoolServices _nordPoolServices = services.Nordpool;
|
||||||
|
|
||||||
@@ -29,19 +30,16 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today))
|
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
|
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
|
||||||
}
|
|
||||||
|
|
||||||
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
|
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today.AddDays(1)))
|
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) &&
|
||||||
|
ShouldFetchNewPrices(today.AddDays(1)))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
|
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
|
||||||
}
|
|
||||||
|
|
||||||
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
|
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
|
||||||
}
|
}
|
||||||
@@ -55,31 +53,24 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
var index = GetTimeQuarterIndex(DateTime.UtcNow);
|
var index = GetTimeQuarterIndex(DateTime.UtcNow);
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index,
|
||||||
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||||
}
|
|
||||||
|
|
||||||
if (DayQuartersIndex == index)
|
if (DayQuartersIndex == index) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
|
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
|
||||||
{
|
{
|
||||||
var price = TodayNordPoolPrice.Prices[index].Price;
|
var price = TodayNordPoolPrice.Prices[index].Price;
|
||||||
|
|
||||||
if (price.HasValue)
|
if (price.HasValue)
|
||||||
{
|
|
||||||
CurrentPrice = price.Value;
|
CurrentPrice = price.Value;
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
logger.LogWarning("Price at index {Index} is null", index);
|
logger.LogWarning("Price at index {Index} is null", index);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}",
|
||||||
|
index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
DayQuartersIndex = index;
|
DayQuartersIndex = index;
|
||||||
@@ -92,25 +83,13 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
|
|
||||||
public bool ShouldFetchNewPrices(DateOnly today)
|
public bool ShouldFetchNewPrices(DateOnly today)
|
||||||
{
|
{
|
||||||
if (!LastFetchedDate.HasValue)
|
if (!LastFetchedDate.HasValue) return true;
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (LastFetchedDate.Value < today)
|
if (LastFetchedDate.Value < today) return true;
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true;
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
|
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var currentHour = DateTime.Now.Hour;
|
var currentHour = DateTime.Now.Hour;
|
||||||
|
|
||||||
@@ -119,7 +98,9 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
|
|
||||||
public void RollOverPrices(DateOnly today)
|
public void RollOverPrices(DateOnly today)
|
||||||
{
|
{
|
||||||
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } ? TomorrowNordPoolPrice : new NordPoolPrice();
|
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 }
|
||||||
|
? TomorrowNordPoolPrice
|
||||||
|
: new NordPoolPrice();
|
||||||
|
|
||||||
TomorrowNordPoolPrice = null;
|
TomorrowNordPoolPrice = null;
|
||||||
|
|
||||||
@@ -130,7 +111,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, string label)
|
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, string label)
|
||||||
{
|
{
|
||||||
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
|
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
|
||||||
{
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return await GetNordPoolPriceAsync(date);
|
return await GetNordPoolPriceAsync(date);
|
||||||
@@ -138,18 +118,23 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts)
|
catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts)
|
||||||
{
|
{
|
||||||
var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1));
|
var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1));
|
||||||
logger.LogWarning(ex, "Attempt {Attempt}/{MaxAttempts} to fetch {Label} prices for {Date} failed. Retrying in {Delay}", attempt, NordPoolConsts.MaxFetchRetryAttempts, label, date, delay);
|
logger.LogWarning(ex,
|
||||||
|
"Attempt {Attempt}/{MaxAttempts} to fetch {Label} prices for {Date} failed. Retrying in {Delay}",
|
||||||
|
attempt, NordPoolConsts.MaxFetchRetryAttempts, label, date, delay);
|
||||||
|
|
||||||
await Task.Delay(delay);
|
await Task.Delay(delay);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Failed to fetch {Label} prices for {Date} on attempt {Attempt} with unexpected error", label, date, attempt);
|
logger.LogError(ex,
|
||||||
|
"Failed to fetch {Label} prices for {Date} on attempt {Attempt} with unexpected error", label, date,
|
||||||
|
attempt);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
logger.LogWarning("All {MaxAttempts} attempts to fetch {Label} prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, label, date);
|
logger.LogWarning(
|
||||||
|
"All {MaxAttempts} attempts to fetch {Label} prices for {Date} exhausted; returning empty prices",
|
||||||
|
NordPoolConsts.MaxFetchRetryAttempts, label, date);
|
||||||
|
|
||||||
return new NordPoolPrice();
|
return new NordPoolPrice();
|
||||||
}
|
}
|
||||||
@@ -172,14 +157,13 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
|
|
||||||
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
||||||
{
|
{
|
||||||
if (element == null)
|
if (element == null) return new NordPoolPrice();
|
||||||
{
|
|
||||||
return new NordPoolPrice();
|
|
||||||
}
|
|
||||||
|
|
||||||
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
||||||
|
|
||||||
return priceResult != null ? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult) : new NordPoolPrice();
|
return priceResult != null
|
||||||
|
? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult)
|
||||||
|
: new NordPoolPrice();
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
|
internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
|
||||||
@@ -189,17 +173,11 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
|||||||
Prices = new List<NordPoolDayPrice>()
|
Prices = new List<NordPoolDayPrice>()
|
||||||
};
|
};
|
||||||
|
|
||||||
if (todayNordPoolPrice.Prices is null)
|
if (todayNordPoolPrice.Prices is null) return recalculatedPrice;
|
||||||
{
|
|
||||||
return recalculatedPrice;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var price in todayNordPoolPrice.Prices)
|
foreach (var price in todayNordPoolPrice.Prices)
|
||||||
{
|
{
|
||||||
if (price.Price is null)
|
if (price.Price is null) continue;
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
recalculatedPrice.Prices.Add(new NordPoolDayPrice
|
recalculatedPrice.Prices.Add(new NordPoolDayPrice
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,15 +4,11 @@ namespace NordPool.Models;
|
|||||||
|
|
||||||
public class CheapestIntervalResult
|
public class CheapestIntervalResult
|
||||||
{
|
{
|
||||||
[JsonPropertyName("start")]
|
[JsonPropertyName("start")] public DateTime Start { get; init; }
|
||||||
public DateTime Start { get; init; }
|
|
||||||
|
|
||||||
[JsonPropertyName("end")]
|
[JsonPropertyName("end")] public DateTime End { get; init; }
|
||||||
public DateTime End { get; init; }
|
|
||||||
|
|
||||||
[JsonPropertyName("price")]
|
[JsonPropertyName("price")] public double Price { get; init; }
|
||||||
public double Price { get; init; }
|
|
||||||
|
|
||||||
[JsonPropertyName("rank")]
|
[JsonPropertyName("rank")] public int Rank { get; init; }
|
||||||
public int Rank { get; init; }
|
|
||||||
}
|
}
|
||||||
@@ -40,31 +40,23 @@ 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, JsonSerializerOptions options)
|
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert,
|
||||||
|
JsonSerializerOptions options)
|
||||||
{
|
{
|
||||||
if (reader.TokenType != JsonTokenType.StartArray)
|
if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("Expected start of array.");
|
||||||
{
|
|
||||||
throw new JsonException("Expected start of array.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
||||||
{
|
|
||||||
throw new JsonException("Expected number for Start at position 0.");
|
throw new JsonException("Expected number for Start at position 0.");
|
||||||
}
|
|
||||||
|
|
||||||
var start = reader.GetInt64();
|
var start = reader.GetInt64();
|
||||||
|
|
||||||
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
||||||
{
|
|
||||||
throw new JsonException("Expected number for End at position 1.");
|
throw new JsonException("Expected number for End at position 1.");
|
||||||
}
|
|
||||||
|
|
||||||
var end = reader.GetInt64();
|
var end = reader.GetInt64();
|
||||||
|
|
||||||
if (!reader.Read() || (reader.TokenType != JsonTokenType.Number && reader.TokenType != JsonTokenType.Null))
|
if (!reader.Read() || (reader.TokenType != JsonTokenType.Number && reader.TokenType != JsonTokenType.Null))
|
||||||
{
|
|
||||||
throw new JsonException("Expected number or null for Price at position 2.");
|
throw new JsonException("Expected number or null for Price at position 2.");
|
||||||
}
|
|
||||||
|
|
||||||
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
|
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
|
||||||
|
|
||||||
@@ -82,13 +74,9 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNo
|
|||||||
writer.WriteNumberValue(value.End);
|
writer.WriteNumberValue(value.End);
|
||||||
|
|
||||||
if (value.Price.HasValue)
|
if (value.Price.HasValue)
|
||||||
{
|
|
||||||
writer.WriteNumberValue(value.Price.Value);
|
writer.WriteNumberValue(value.Price.Value);
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
|
||||||
writer.WriteNullValue();
|
writer.WriteNullValue();
|
||||||
}
|
|
||||||
|
|
||||||
writer.WriteEndArray();
|
writer.WriteEndArray();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,9 @@ namespace NordPool.Models.Dtos;
|
|||||||
|
|
||||||
public class NordPoolDayPriceDto
|
public class NordPoolDayPriceDto
|
||||||
{
|
{
|
||||||
[JsonPropertyName("start")]
|
[JsonPropertyName("start")] public string? Start { get; init; }
|
||||||
public string? Start { get; init; }
|
|
||||||
[JsonPropertyName("end")]
|
[JsonPropertyName("end")] public string? End { get; init; }
|
||||||
public string? End { get; init; }
|
|
||||||
[JsonPropertyName("price")]
|
[JsonPropertyName("price")] public double? Price { get; init; }
|
||||||
public double? Price { get; init; }
|
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,5 @@ namespace NordPool.Models.Dtos;
|
|||||||
|
|
||||||
public class NordPoolPriceResultDto
|
public class NordPoolPriceResultDto
|
||||||
{
|
{
|
||||||
[JsonPropertyName("LT")]
|
[JsonPropertyName("LT")] public List<NordPoolDayPriceDto>? Prices { get; init; }
|
||||||
public List<NordPoolDayPriceDto>? Prices { get; init; }
|
|
||||||
}
|
}
|
||||||
@@ -13,10 +13,6 @@ public class NordPoolEntity : EntityCreateModel
|
|||||||
manufacturer = NordPoolConsts.DeviceManufacturer
|
manufacturer = NordPoolConsts.DeviceManufacturer
|
||||||
};
|
};
|
||||||
|
|
||||||
public string Domain { get; }
|
|
||||||
public string Identifier { get; }
|
|
||||||
public string Name { get; }
|
|
||||||
|
|
||||||
public NordPoolEntity(string domain, string identifier, string name)
|
public NordPoolEntity(string domain, string identifier, string name)
|
||||||
{
|
{
|
||||||
Domain = domain;
|
Domain = domain;
|
||||||
@@ -33,6 +29,10 @@ public class NordPoolEntity : EntityCreateModel
|
|||||||
AdditionalConfig = new { device = DeviceBlock };
|
AdditionalConfig = new { device = DeviceBlock };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public string Domain { get; }
|
||||||
|
public string Identifier { get; }
|
||||||
|
public string Name { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates an AdditionalConfig that merges custom properties with the NordPool device block.
|
/// Creates an AdditionalConfig that merges custom properties with the NordPool device block.
|
||||||
/// Use this when an entity needs extra config beyond the default device assignment.
|
/// Use this when an entity needs extra config beyond the default device assignment.
|
||||||
|
|||||||
@@ -13,6 +13,60 @@ public class CostAccumulatorTests
|
|||||||
Month
|
Month
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#region Thread safety
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AddCost_ConcurrentAccess_ShouldNotLoseData()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = PowerMonitorTestData.FixedNow;
|
||||||
|
var sut = new CostAccumulator(now);
|
||||||
|
const double incrementPerCall = 0.001;
|
||||||
|
const int callsPerThread = 1000;
|
||||||
|
const int threadCount = 10;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var tasks = Enumerable.Range(0, threadCount)
|
||||||
|
.Select(_ => Task.Run(() =>
|
||||||
|
{
|
||||||
|
for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
||||||
|
}))
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
var snapshot = sut.GetSnapshot();
|
||||||
|
const double expected = incrementPerCall * callsPerThread * threadCount;
|
||||||
|
snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
private static double GetCurrent(CostSnapshot snapshot, CostWindow window)
|
||||||
|
{
|
||||||
|
return window switch
|
||||||
|
{
|
||||||
|
CostWindow.FifteenMinutes => snapshot.Cost15Min,
|
||||||
|
CostWindow.Hour => snapshot.Cost1Hour,
|
||||||
|
CostWindow.Day => snapshot.CostDaily,
|
||||||
|
CostWindow.Month => snapshot.CostMonthly,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(window))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double GetPrevious(CostSnapshot snapshot, CostWindow window)
|
||||||
|
{
|
||||||
|
return window switch
|
||||||
|
{
|
||||||
|
CostWindow.FifteenMinutes => snapshot.Previous15Min,
|
||||||
|
CostWindow.Hour => snapshot.Previous1Hour,
|
||||||
|
CostWindow.Day => snapshot.PreviousDaily,
|
||||||
|
CostWindow.Month => snapshot.PreviousMonthly,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(window))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
#region AddCost and GetSnapshot
|
#region AddCost and GetSnapshot
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -67,10 +121,7 @@ public class CostAccumulatorTests
|
|||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
foreach (var increment in increments)
|
foreach (var increment in increments) sut.AddCost(increment, now.AddSeconds(1));
|
||||||
{
|
|
||||||
sut.AddCost(increment, now.AddSeconds(1));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
var expected = increments.Sum();
|
var expected = increments.Sum();
|
||||||
@@ -142,21 +193,66 @@ public class CostAccumulatorTests
|
|||||||
|
|
||||||
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new()
|
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new()
|
||||||
{
|
{
|
||||||
{ "15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), new DateTime(2026, 3, 17, 10, 15, 0), 0.10, 0.02 },
|
{
|
||||||
{ "15 minute slot ends across the hour", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.10, 0.02 },
|
"15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0),
|
||||||
{ "15 minute slot ends at midnight", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.10, 0.02 },
|
new DateTime(2026, 3, 17, 10, 15, 0), 0.10, 0.02
|
||||||
{ "15 minute slot ends on DST spring forward", CostWindow.FifteenMinutes, new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.10, 0.02 },
|
},
|
||||||
{ "15 minute slot ends on DST fall back", CostWindow.FifteenMinutes, new DateTime(2026, 10, 25, 2, 45, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.10, 0.02 },
|
{
|
||||||
{ "hour ends", CostWindow.Hour, new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.50, 0.01 },
|
"15 minute slot ends across the hour", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 45, 0),
|
||||||
{ "hour ends at midnight", CostWindow.Hour, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.50, 0.01 },
|
new DateTime(2026, 3, 17, 11, 0, 0), 0.10, 0.02
|
||||||
{ "hour ends on DST spring forward", CostWindow.Hour, new DateTime(2026, 3, 29, 2, 59, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.50, 0.01 },
|
},
|
||||||
{ "hour ends on DST fall back", CostWindow.Hour, new DateTime(2026, 10, 25, 2, 59, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.50, 0.01 },
|
{
|
||||||
{ "day changes", CostWindow.Day, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 5.00, 0.01 },
|
"15 minute slot ends at midnight", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 23, 45, 0),
|
||||||
{ "day changes at month end", CostWindow.Day, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 5.00, 0.01 },
|
new DateTime(2026, 3, 18, 0, 0, 0), 0.10, 0.02
|
||||||
{ "day changes at year end", CostWindow.Day, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 5.00, 0.01 },
|
},
|
||||||
{ "month changes", CostWindow.Month, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 100.00, 0.01 },
|
{
|
||||||
{ "year changes", CostWindow.Month, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 100.00, 0.01 },
|
"15 minute slot ends on DST spring forward", CostWindow.FifteenMinutes, new DateTime(2026, 3, 29, 2, 45, 0),
|
||||||
{ "month changes on leap day", CostWindow.Month, new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), 100.00, 0.01 }
|
new DateTime(2026, 3, 29, 3, 0, 0), 0.10, 0.02
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"15 minute slot ends on DST fall back", CostWindow.FifteenMinutes, new DateTime(2026, 10, 25, 2, 45, 0),
|
||||||
|
new DateTime(2026, 10, 25, 3, 0, 0), 0.10, 0.02
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hour ends", CostWindow.Hour, new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 0, 0),
|
||||||
|
0.50, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hour ends at midnight", CostWindow.Hour, new DateTime(2026, 3, 17, 23, 59, 0),
|
||||||
|
new DateTime(2026, 3, 18, 0, 0, 0), 0.50, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hour ends on DST spring forward", CostWindow.Hour, new DateTime(2026, 3, 29, 2, 59, 0),
|
||||||
|
new DateTime(2026, 3, 29, 3, 0, 0), 0.50, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hour ends on DST fall back", CostWindow.Hour, new DateTime(2026, 10, 25, 2, 59, 0),
|
||||||
|
new DateTime(2026, 10, 25, 3, 0, 0), 0.50, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"day changes", CostWindow.Day, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0),
|
||||||
|
5.00, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"day changes at month end", CostWindow.Day, new DateTime(2026, 3, 31, 23, 59, 0),
|
||||||
|
new DateTime(2026, 4, 1, 0, 0, 0), 5.00, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"day changes at year end", CostWindow.Day, new DateTime(2026, 12, 31, 23, 59, 0),
|
||||||
|
new DateTime(2027, 1, 1, 0, 0, 0), 5.00, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"month changes", CostWindow.Month, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0),
|
||||||
|
100.00, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"year changes", CostWindow.Month, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0),
|
||||||
|
100.00, 0.01
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"month changes on leap day", CostWindow.Month, new DateTime(2028, 2, 29, 23, 59, 0),
|
||||||
|
new DateTime(2028, 3, 1, 0, 0, 0), 100.00, 0.01
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -251,7 +347,9 @@ public class CostAccumulatorTests
|
|||||||
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new()
|
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new()
|
||||||
{
|
{
|
||||||
{ "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
|
{ "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
|
||||||
{ "same hour, later minute", new DateTime(2026, 3, 17, 10, 10, 0), new DateTime(2026, 3, 17, 10, 11, 0), false },
|
{
|
||||||
|
"same hour, later minute", new DateTime(2026, 3, 17, 10, 10, 0), new DateTime(2026, 3, 17, 10, 11, 0), false
|
||||||
|
},
|
||||||
{ "same hour, last minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 59, 59), false },
|
{ "same hour, last minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 59, 59), false },
|
||||||
{ "next hour", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 11, 0, 0), true },
|
{ "next hour", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 11, 0, 0), true },
|
||||||
{ "next hour, late minute", new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 59, 0), true },
|
{ "next hour, late minute", new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 59, 0), true },
|
||||||
@@ -292,7 +390,10 @@ public class CostAccumulatorTests
|
|||||||
{ "same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false },
|
{ "same month, 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 },
|
||||||
{ "next month", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true },
|
{ "next month", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true },
|
||||||
{ "clock moved into previous month", new DateTime(2026, 4, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 0), true },
|
{
|
||||||
|
"clock moved into previous month", new DateTime(2026, 4, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 0),
|
||||||
|
true
|
||||||
|
},
|
||||||
{ "year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true },
|
{ "year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true },
|
||||||
{ "leap day rollover", new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), true }
|
{ "leap day rollover", new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), true }
|
||||||
};
|
};
|
||||||
@@ -305,55 +406,4 @@ public class CostAccumulatorTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Thread safety
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task AddCost_ConcurrentAccess_ShouldNotLoseData()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var now = PowerMonitorTestData.FixedNow;
|
|
||||||
var sut = new CostAccumulator(now);
|
|
||||||
const double incrementPerCall = 0.001;
|
|
||||||
const int callsPerThread = 1000;
|
|
||||||
const int threadCount = 10;
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var tasks = Enumerable.Range(0, threadCount)
|
|
||||||
.Select(_ => Task.Run(() =>
|
|
||||||
{
|
|
||||||
for (var i = 0; i < callsPerThread; i++)
|
|
||||||
{
|
|
||||||
sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
await Task.WhenAll(tasks);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = sut.GetSnapshot();
|
|
||||||
const double expected = incrementPerCall * callsPerThread * threadCount;
|
|
||||||
snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
private static double GetCurrent(CostSnapshot snapshot, CostWindow window) => window switch
|
|
||||||
{
|
|
||||||
CostWindow.FifteenMinutes => snapshot.Cost15Min,
|
|
||||||
CostWindow.Hour => snapshot.Cost1Hour,
|
|
||||||
CostWindow.Day => snapshot.CostDaily,
|
|
||||||
CostWindow.Month => snapshot.CostMonthly,
|
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(window))
|
|
||||||
};
|
|
||||||
|
|
||||||
private static double GetPrevious(CostSnapshot snapshot, CostWindow window) => window switch
|
|
||||||
{
|
|
||||||
CostWindow.FifteenMinutes => snapshot.Previous15Min,
|
|
||||||
CostWindow.Hour => snapshot.Previous1Hour,
|
|
||||||
CostWindow.Day => snapshot.PreviousDaily,
|
|
||||||
CostWindow.Month => snapshot.PreviousMonthly,
|
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(window))
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
@@ -41,7 +41,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
string expectedDataQuality)
|
string expectedDataQuality)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 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);
|
||||||
@@ -62,7 +62,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Calculate_ShouldIncludeAllDeviceReadingsInResult()
|
public void Calculate_ShouldIncludeAllDeviceReadingsInResult()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 1);
|
var sut = CreateSut(1);
|
||||||
var devices = PowerMonitorTestData.CreateCostDeviceReadings();
|
var devices = PowerMonitorTestData.CreateCostDeviceReadings();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -78,7 +78,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Calculate_ShouldCopyDeviceReadingsInsteadOfAliasingThem()
|
public void Calculate_ShouldCopyDeviceReadingsInsteadOfAliasingThem()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 1);
|
var sut = CreateSut(1);
|
||||||
var devices = new Dictionary<string, double> { ["sensor.tv_power"] = 100.0 };
|
var devices = new Dictionary<string, double> { ["sensor.tv_power"] = 100.0 };
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -98,7 +98,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Calculate_FirstSample_ShouldReturnRawValueWithoutSmoothing()
|
public void Calculate_FirstSample_ShouldReturnRawValueWithoutSmoothing()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 10);
|
var sut = CreateSut();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var result = sut.Calculate(341.97, new Dictionary<string, double>());
|
var result = sut.Calculate(341.97, new Dictionary<string, double>());
|
||||||
@@ -111,7 +111,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage()
|
public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 4);
|
var sut = CreateSut(4);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var result1 = sut.Calculate(341.97, new Dictionary<string, double>());
|
var result1 = sut.Calculate(341.97, new Dictionary<string, double>());
|
||||||
@@ -127,7 +127,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Calculate_WithSmoothingWindowOfOne_ShouldFollowRawValueExactly()
|
public void Calculate_WithSmoothingWindowOfOne_ShouldFollowRawValueExactly()
|
||||||
{
|
{
|
||||||
// Arrange - alpha becomes 1, so the previous value has no influence.
|
// Arrange - alpha becomes 1, so the previous value has no influence.
|
||||||
var sut = CreateSut(smoothingWindowSize: 1);
|
var sut = CreateSut(1);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
sut.Calculate(500.0, new Dictionary<string, double>());
|
sut.Calculate(500.0, new Dictionary<string, double>());
|
||||||
@@ -141,7 +141,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Calculate_ShouldDampenSingleSpike()
|
public void Calculate_ShouldDampenSingleSpike()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 10);
|
var sut = CreateSut();
|
||||||
sut.Calculate(100.0, new Dictionary<string, double>());
|
sut.Calculate(100.0, new Dictionary<string, double>());
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -166,10 +166,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
|
|
||||||
// Act
|
// Act
|
||||||
PowerCalculationResult? result = null;
|
PowerCalculationResult? result = null;
|
||||||
for (var i = 0; i < 200; i++)
|
for (var i = 0; i < 200; i++) result = sut.Calculate(200.0, new Dictionary<string, double>());
|
||||||
{
|
|
||||||
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);
|
||||||
@@ -179,7 +176,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Calculate_WithGeneratedSeries_ShouldNeverOvershootTheInputRange()
|
public void Calculate_WithGeneratedSeries_ShouldNeverOvershootTheInputRange()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 5);
|
var sut = CreateSut(5);
|
||||||
var samples = PowerMonitorTestData.CreatePowerSampleSeries(50);
|
var samples = PowerMonitorTestData.CreatePowerSampleSeries(50);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -198,7 +195,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Reset_ShouldClearSmoothedState()
|
public void Reset_ShouldClearSmoothedState()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 10);
|
var sut = CreateSut();
|
||||||
sut.Calculate(341.97, new Dictionary<string, double>());
|
sut.Calculate(341.97, new Dictionary<string, double>());
|
||||||
sut.Calculate(341.97, new Dictionary<string, double>());
|
sut.Calculate(341.97, new Dictionary<string, double>());
|
||||||
|
|
||||||
@@ -214,7 +211,7 @@ public class OtherPowerCalculationServiceTests
|
|||||||
public void Reset_WhenCalledBeforeAnyCalculation_ShouldKeepFirstSampleRaw()
|
public void Reset_WhenCalledBeforeAnyCalculation_ShouldKeepFirstSampleRaw()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut(smoothingWindowSize: 10);
|
var sut = CreateSut();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
sut.Reset();
|
sut.Reset();
|
||||||
|
|||||||
@@ -14,6 +14,70 @@ public class PowerCostCalculationServiceTests
|
|||||||
|
|
||||||
private readonly PowerCostCalculationService _sut = new();
|
private readonly PowerCostCalculationService _sut = new();
|
||||||
|
|
||||||
|
#region Snapshot defaults
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(CostBucket.Total)]
|
||||||
|
[InlineData(CostBucket.Other)]
|
||||||
|
public void GetSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot(CostBucket bucket)
|
||||||
|
{
|
||||||
|
// Act
|
||||||
|
var snapshot = bucket == CostBucket.Total
|
||||||
|
? _sut.GetTotalCostSnapshot()
|
||||||
|
: _sut.GetOtherCostSnapshot();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
snapshot.Cost15Min.Should().Be(0);
|
||||||
|
snapshot.Cost1Hour.Should().Be(0);
|
||||||
|
snapshot.CostDaily.Should().Be(0);
|
||||||
|
snapshot.CostMonthly.Should().Be(0);
|
||||||
|
snapshot.PartialWindow.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Thread safety
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var now = PowerMonitorTestData.FixedNow;
|
||||||
|
var result = PowerMonitorTestData.CreateCalculation();
|
||||||
|
const int callsPerThread = 100;
|
||||||
|
const int threadCount = 10;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var tasks = Enumerable.Range(0, threadCount)
|
||||||
|
.Select(_ => Task.Run(() =>
|
||||||
|
{
|
||||||
|
for (var i = 0; i < callsPerThread; i++)
|
||||||
|
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
|
||||||
|
}))
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
var total = _sut.GetTotalCostSnapshot();
|
||||||
|
total.CostDaily.Should().BeGreaterThan(0);
|
||||||
|
|
||||||
|
var devices = _sut.GetAllDeviceCostSnapshots();
|
||||||
|
devices.Should().HaveCount(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
private static double ExpectedCost(
|
||||||
|
double powerWatts,
|
||||||
|
double pricePerKwh,
|
||||||
|
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds)
|
||||||
|
{
|
||||||
|
return powerWatts / PowerMonitorConsts.WattsPerKilowatt
|
||||||
|
* pricePerKwh
|
||||||
|
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||||
|
}
|
||||||
|
|
||||||
#region CalculateCostIncrement
|
#region CalculateCostIncrement
|
||||||
|
|
||||||
public static TheoryData<string, double, double, int, double> CostIncrementCases => new()
|
public static TheoryData<string, double, double, int, double> CostIncrementCases => new()
|
||||||
@@ -57,16 +121,15 @@ public class PowerCostCalculationServiceTests
|
|||||||
|
|
||||||
// Act
|
// Act
|
||||||
var costs = samples
|
var costs = samples
|
||||||
.Select(watts => PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds))
|
.Select(watts =>
|
||||||
|
PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one");
|
costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one");
|
||||||
for (var i = 0; i < samples.Count; i++)
|
for (var i = 0; i < samples.Count; i++)
|
||||||
{
|
|
||||||
costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15);
|
costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -80,11 +143,14 @@ public class PowerCostCalculationServiceTests
|
|||||||
var result = PowerMonitorTestData.CreateCalculation();
|
var result = PowerMonitorTestData.CreateCalculation();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
|
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||||
|
now);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
var expectedTotal = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
var expectedTotal =
|
||||||
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||||
|
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts,
|
||||||
|
PowerMonitorTestData.DefaultPricePerKwh);
|
||||||
|
|
||||||
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12);
|
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12);
|
||||||
_sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12);
|
_sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12);
|
||||||
@@ -101,7 +167,8 @@ public class PowerCostCalculationServiceTests
|
|||||||
var result = PowerMonitorTestData.CreateCalculation();
|
var result = PowerMonitorTestData.CreateCalculation();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
|
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||||
|
now);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
var snapshot = _sut.GetDeviceCostSnapshot(entityId);
|
var snapshot = _sut.GetDeviceCostSnapshot(entityId);
|
||||||
@@ -119,7 +186,8 @@ public class PowerCostCalculationServiceTests
|
|||||||
var result = PowerMonitorTestData.CreateCalculation();
|
var result = PowerMonitorTestData.CreateCalculation();
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
|
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||||
|
now);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
var total = _sut.GetTotalCostSnapshot();
|
var total = _sut.GetTotalCostSnapshot();
|
||||||
@@ -157,7 +225,8 @@ public class PowerCostCalculationServiceTests
|
|||||||
_sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
_sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
|
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
|
||||||
|
|
||||||
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
|
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15,
|
||||||
|
now.AddSeconds(15));
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
|
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
|
||||||
@@ -202,9 +271,9 @@ public class PowerCostCalculationServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
var now = PowerMonitorTestData.FixedNow;
|
var now = PowerMonitorTestData.FixedNow;
|
||||||
var result = PowerMonitorTestData.CreateCalculation(
|
var result = PowerMonitorTestData.CreateCalculation(
|
||||||
totalWatts: 0,
|
0,
|
||||||
smoothedOtherWatts: 0,
|
0,
|
||||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||||
@@ -321,9 +390,9 @@ public class PowerCostCalculationServiceTests
|
|||||||
for (var slot = 0; slot < timestamps.Count; slot++)
|
for (var slot = 0; slot < timestamps.Count; slot++)
|
||||||
{
|
{
|
||||||
var result = PowerMonitorTestData.CreateCalculation(
|
var result = PowerMonitorTestData.CreateCalculation(
|
||||||
totalWatts: wattSamples[slot],
|
wattSamples[slot],
|
||||||
smoothedOtherWatts: wattSamples[slot] / 2,
|
wattSamples[slot] / 2,
|
||||||
deviceReadings: new Dictionary<string, double>());
|
new Dictionary<string, double>());
|
||||||
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
|
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -348,9 +417,9 @@ public class PowerCostCalculationServiceTests
|
|||||||
{
|
{
|
||||||
var watts = 500.0 + start.Hour * 125.0;
|
var watts = 500.0 + start.Hour * 125.0;
|
||||||
var result = PowerMonitorTestData.CreateCalculation(
|
var result = PowerMonitorTestData.CreateCalculation(
|
||||||
totalWatts: watts,
|
watts,
|
||||||
smoothedOtherWatts: watts / 4,
|
watts / 4,
|
||||||
deviceReadings: 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));
|
||||||
}
|
}
|
||||||
@@ -407,7 +476,8 @@ 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 = 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
var expected =
|
||||||
|
2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||||
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
|
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -486,68 +556,4 @@ public class PowerCostCalculationServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Snapshot defaults
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(CostBucket.Total)]
|
|
||||||
[InlineData(CostBucket.Other)]
|
|
||||||
public void GetSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot(CostBucket bucket)
|
|
||||||
{
|
|
||||||
// Act
|
|
||||||
var snapshot = bucket == CostBucket.Total
|
|
||||||
? _sut.GetTotalCostSnapshot()
|
|
||||||
: _sut.GetOtherCostSnapshot();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
snapshot.Cost15Min.Should().Be(0);
|
|
||||||
snapshot.Cost1Hour.Should().Be(0);
|
|
||||||
snapshot.CostDaily.Should().Be(0);
|
|
||||||
snapshot.CostMonthly.Should().Be(0);
|
|
||||||
snapshot.PartialWindow.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Thread safety
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var now = PowerMonitorTestData.FixedNow;
|
|
||||||
var result = PowerMonitorTestData.CreateCalculation();
|
|
||||||
const int callsPerThread = 100;
|
|
||||||
const int threadCount = 10;
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var tasks = Enumerable.Range(0, threadCount)
|
|
||||||
.Select(_ => Task.Run(() =>
|
|
||||||
{
|
|
||||||
for (var i = 0; i < callsPerThread; i++)
|
|
||||||
{
|
|
||||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
await Task.WhenAll(tasks);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var total = _sut.GetTotalCostSnapshot();
|
|
||||||
total.CostDaily.Should().BeGreaterThan(0);
|
|
||||||
|
|
||||||
var devices = _sut.GetAllDeviceCostSnapshots();
|
|
||||||
devices.Should().HaveCount(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
private static double ExpectedCost(
|
|
||||||
double powerWatts,
|
|
||||||
double pricePerKwh,
|
|
||||||
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) =>
|
|
||||||
powerWatts / PowerMonitorConsts.WattsPerKilowatt
|
|
||||||
* pricePerKwh
|
|
||||||
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
|
||||||
}
|
}
|
||||||
@@ -18,40 +18,52 @@ public class PowerLimitEnforcementServiceTests
|
|||||||
|
|
||||||
private readonly Mock<IHaContext> _haContextMock = new();
|
private readonly Mock<IHaContext> _haContextMock = new();
|
||||||
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
|
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
|
||||||
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
|
|
||||||
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
|
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
|
||||||
|
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
|
||||||
|
|
||||||
private PowerLimitEnforcementService CreateSut() =>
|
private PowerLimitEnforcementService CreateSut()
|
||||||
new(
|
{
|
||||||
|
return new PowerLimitEnforcementService(
|
||||||
_haContextMock.Object,
|
_haContextMock.Object,
|
||||||
_loggerMock.Object,
|
_loggerMock.Object,
|
||||||
Options.Create(_options),
|
Options.Create(_options),
|
||||||
_timeProvider);
|
_timeProvider);
|
||||||
|
}
|
||||||
|
|
||||||
private void VerifyNoServiceCalls() =>
|
private void VerifyNoServiceCalls()
|
||||||
|
{
|
||||||
_haContextMock.Verify(
|
_haContextMock.Verify(
|
||||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||||
Times.Never);
|
Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
private void VerifyTurnOff(string entityId, int expectedCalls) =>
|
private void VerifyTurnOff(string entityId, int expectedCalls)
|
||||||
|
{
|
||||||
_haContextMock.Verify(
|
_haContextMock.Verify(
|
||||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
||||||
Times.Exactly(expectedCalls));
|
Times.Exactly(expectedCalls));
|
||||||
|
}
|
||||||
|
|
||||||
private void VerifyTurnOn(string entityId, int expectedCalls) =>
|
private void VerifyTurnOn(string entityId, int expectedCalls)
|
||||||
|
{
|
||||||
_haContextMock.Verify(
|
_haContextMock.Verify(
|
||||||
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
||||||
Times.Exactly(expectedCalls));
|
Times.Exactly(expectedCalls));
|
||||||
|
}
|
||||||
|
|
||||||
private void VerifyNotificationCreated(int expectedCalls) =>
|
private void VerifyNotificationCreated(int expectedCalls)
|
||||||
|
{
|
||||||
_haContextMock.Verify(
|
_haContextMock.Verify(
|
||||||
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||||
Times.Exactly(expectedCalls));
|
Times.Exactly(expectedCalls));
|
||||||
|
}
|
||||||
|
|
||||||
private void VerifyNotificationDismissed(int expectedCalls) =>
|
private void VerifyNotificationDismissed(int expectedCalls)
|
||||||
|
{
|
||||||
_haContextMock.Verify(
|
_haContextMock.Verify(
|
||||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||||
Times.Exactly(expectedCalls));
|
Times.Exactly(expectedCalls));
|
||||||
|
}
|
||||||
|
|
||||||
#region EnforceLimit
|
#region EnforceLimit
|
||||||
|
|
||||||
@@ -120,7 +132,8 @@ 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>(), It.IsAny<object?>()))
|
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(),
|
||||||
|
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();
|
||||||
@@ -131,7 +144,8 @@ public class PowerLimitEnforcementServiceTests
|
|||||||
// Assert
|
// Assert
|
||||||
var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList();
|
var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList();
|
||||||
turnOffCalls.Should().HaveCount(2);
|
turnOffCalls.Should().HaveCount(2);
|
||||||
turnOffCalls[0].entityId.Should().Be(BoilerSwitch, "boiler switch must be turned off before auto_management (race-safe order)");
|
turnOffCalls[0].entityId.Should().Be(BoilerSwitch,
|
||||||
|
"boiler switch must be turned off before auto_management (race-safe order)");
|
||||||
turnOffCalls[1].entityId.Should().Be(AutoManagement);
|
turnOffCalls[1].entityId.Should().Be(AutoManagement);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,7 +267,8 @@ public class PowerLimitEnforcementServiceTests
|
|||||||
[InlineData(30, true)]
|
[InlineData(30, true)]
|
||||||
[InlineData(31, true)]
|
[InlineData(31, true)]
|
||||||
[InlineData(600, true)]
|
[InlineData(600, true)]
|
||||||
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, bool expectedLimitActive)
|
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery,
|
||||||
|
bool expectedLimitActive)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|||||||
@@ -33,13 +33,65 @@ public class PowerMonitorEntityServiceTests
|
|||||||
public PowerMonitorEntityServiceTests()
|
public PowerMonitorEntityServiceTests()
|
||||||
{
|
{
|
||||||
var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
|
var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
|
||||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>())).Returns(Task.CompletedTask);
|
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())).Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())).Returns(Task.CompletedTask);
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#region GetDeviceCostEntityIds
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("sonoff_abc")]
|
||||||
|
[InlineData("tv")]
|
||||||
|
[InlineData("akvariumas")]
|
||||||
|
public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName)
|
||||||
|
{
|
||||||
|
// Act
|
||||||
|
var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().HaveCount(4);
|
||||||
|
string[] expectedEntityIds =
|
||||||
|
[
|
||||||
|
$"sensor.powermonitor_{deviceName}_cost_15min",
|
||||||
|
$"sensor.powermonitor_{deviceName}_cost_1h",
|
||||||
|
$"sensor.powermonitor_{deviceName}_cost_daily",
|
||||||
|
$"sensor.powermonitor_{deviceName}_cost_monthly"
|
||||||
|
];
|
||||||
|
result.Should().BeEquivalentTo(expectedEntityIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region CreateDeviceEntitiesAsync
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0, 0)]
|
||||||
|
[InlineData(1, 4)]
|
||||||
|
[InlineData(2, 8)]
|
||||||
|
[InlineData(5, 20)]
|
||||||
|
public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sensors = Enumerable.Range(0, sensorCount)
|
||||||
|
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await _sut.CreateDeviceEntitiesAsync(sensors);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()),
|
||||||
|
Times.Exactly(expectedCreates));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region GetSystemEntitiesList
|
#region GetSystemEntitiesList
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -159,31 +211,6 @@ public class PowerMonitorEntityServiceTests
|
|||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region GetDeviceCostEntityIds
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("sonoff_abc")]
|
|
||||||
[InlineData("tv")]
|
|
||||||
[InlineData("akvariumas")]
|
|
||||||
public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName)
|
|
||||||
{
|
|
||||||
// Act
|
|
||||||
var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().HaveCount(4);
|
|
||||||
string[] expectedEntityIds =
|
|
||||||
[
|
|
||||||
$"sensor.powermonitor_{deviceName}_cost_15min",
|
|
||||||
$"sensor.powermonitor_{deviceName}_cost_1h",
|
|
||||||
$"sensor.powermonitor_{deviceName}_cost_daily",
|
|
||||||
$"sensor.powermonitor_{deviceName}_cost_monthly"
|
|
||||||
];
|
|
||||||
result.Should().BeEquivalentTo(expectedEntityIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region CreateSystemEntitiesAsync
|
#region CreateSystemEntitiesAsync
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -201,7 +228,8 @@ public class PowerMonitorEntityServiceTests
|
|||||||
{
|
{
|
||||||
// Arrange - both 1h cost entities fail, the remaining twelve must still be created.
|
// Arrange - both 1h cost entities fail, the remaining twelve must still be created.
|
||||||
_entityManagerMock
|
_entityManagerMock
|
||||||
.Setup(em => em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
|
.Setup(em =>
|
||||||
|
em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
|
||||||
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
|
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@@ -213,29 +241,6 @@ public class PowerMonitorEntityServiceTests
|
|||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region CreateDeviceEntitiesAsync
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(0, 0)]
|
|
||||||
[InlineData(1, 4)]
|
|
||||||
[InlineData(2, 8)]
|
|
||||||
[InlineData(5, 20)]
|
|
||||||
public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates)
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sensors = Enumerable.Range(0, sensorCount)
|
|
||||||
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
await _sut.CreateDeviceEntitiesAsync(sensors);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(expectedCreates));
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region ResetEntitiesAsync
|
#region ResetEntitiesAsync
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -299,7 +304,8 @@ public class PowerMonitorEntityServiceTests
|
|||||||
await _sut.RemoveSystemEntitiesAsync();
|
await _sut.RemoveSystemEntitiesAsync();
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))), Times.Exactly(14));
|
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))),
|
||||||
|
Times.Exactly(14));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -399,12 +405,10 @@ 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")]
|
||||||
@@ -412,13 +416,14 @@ public class PowerMonitorEntityServiceTests
|
|||||||
public async Task UpdateEntitiesAsync_ShouldProjectAnomalyState(bool isAnomaly, string expectedState)
|
public async Task UpdateEntitiesAsync_ShouldProjectAnomalyState(bool isAnomaly, string expectedState)
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly: isAnomaly);
|
var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
await _sut.UpdateEntitiesAsync(context);
|
await _sut.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState),
|
||||||
|
Times.Once);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -450,7 +455,8 @@ 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"), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"),
|
||||||
|
Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,7 +475,8 @@ 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>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()),
|
||||||
|
Times.Once);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -513,7 +520,7 @@ public class PowerMonitorEntityServiceTests
|
|||||||
public static TheoryData<string, Func<PowerMonitorEntityService, Task>> CancelledOperations()
|
public static TheoryData<string, Func<PowerMonitorEntityService, Task>> CancelledOperations()
|
||||||
{
|
{
|
||||||
var data = new TheoryData<string, Func<PowerMonitorEntityService, Task>>();
|
var data = new TheoryData<string, Func<PowerMonitorEntityService, Task>>();
|
||||||
var cancelled = new CancellationToken(canceled: true);
|
var cancelled = new CancellationToken(true);
|
||||||
List<PowerSensorInfo> sensors = [PowerMonitorTestData.CreateSensor("sensor.tv_power")];
|
List<PowerSensorInfo> sensors = [PowerMonitorTestData.CreateSensor("sensor.tv_power")];
|
||||||
var context = PowerMonitorTestData.CreateUpdateContext();
|
var context = PowerMonitorTestData.CreateUpdateContext();
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ namespace PowerMonitor.Manager.Tests;
|
|||||||
|
|
||||||
public class PowerMonitorOptionsTests
|
public class PowerMonitorOptionsTests
|
||||||
{
|
{
|
||||||
|
public static TheoryData<string> CollectionProperties =>
|
||||||
|
[
|
||||||
|
nameof(PowerMonitorOptions.ExcludedSensorPatterns),
|
||||||
|
nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds),
|
||||||
|
nameof(PowerMonitorOptions.PauseAndRestoreEntityIds)
|
||||||
|
];
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(nameof(PowerMonitorOptions.Enabled), false)]
|
[InlineData(nameof(PowerMonitorOptions.Enabled), false)]
|
||||||
[InlineData(nameof(PowerMonitorOptions.MainMeterEntityId), "")]
|
[InlineData(nameof(PowerMonitorOptions.MainMeterEntityId), "")]
|
||||||
@@ -31,13 +38,6 @@ public class PowerMonitorOptionsTests
|
|||||||
actual.Should().Be(expected);
|
actual.Should().Be(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static TheoryData<string> CollectionProperties =>
|
|
||||||
[
|
|
||||||
nameof(PowerMonitorOptions.ExcludedSensorPatterns),
|
|
||||||
nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds),
|
|
||||||
nameof(PowerMonitorOptions.PauseAndRestoreEntityIds)
|
|
||||||
];
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[MemberData(nameof(CollectionProperties))]
|
[MemberData(nameof(CollectionProperties))]
|
||||||
public void Defaults_ShouldExposeEmptyCollection(string propertyName)
|
public void Defaults_ShouldExposeEmptyCollection(string propertyName)
|
||||||
|
|||||||
@@ -30,16 +30,21 @@ internal static class PowerMonitorTestData
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Two-device reading set used by the cost calculation tests.
|
/// Two-device reading set used by the cost calculation tests.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static IReadOnlyDictionary<string, double> CreateCostDeviceReadings() => new Dictionary<string, double>
|
public static IReadOnlyDictionary<string, double> CreateCostDeviceReadings()
|
||||||
|
{
|
||||||
|
return new Dictionary<string, double>
|
||||||
{
|
{
|
||||||
["sensor.sonoff_100215c534_power"] = 101.0,
|
["sensor.sonoff_100215c534_power"] = 101.0,
|
||||||
["sensor.sonoff_10018909cb_power"] = 109.93
|
["sensor.sonoff_10018909cb_power"] = 109.93
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Realistic seven-device reading set used by the entity projection tests.
|
/// Realistic seven-device reading set used by the entity projection tests.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static Dictionary<string, double> CreateDeviceReadings() => new()
|
private static Dictionary<string, double> CreateDeviceReadings()
|
||||||
|
{
|
||||||
|
return new Dictionary<string, double>
|
||||||
{
|
{
|
||||||
["sensor.sonoff_100215c534_power"] = 8.55,
|
["sensor.sonoff_100215c534_power"] = 8.55,
|
||||||
["sensor.sonoff_10018909cb_power"] = 36.93,
|
["sensor.sonoff_10018909cb_power"] = 36.93,
|
||||||
@@ -49,9 +54,12 @@ internal static class PowerMonitorTestData
|
|||||||
["sensor.temp_power"] = 14.0,
|
["sensor.temp_power"] = 14.0,
|
||||||
["sensor.balkony_laps_power"] = 9.39
|
["sensor.balkony_laps_power"] = 9.39
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static IReadOnlyDictionary<string, double> CreateReadings(params (string EntityId, double Watts)[] readings) =>
|
public static IReadOnlyDictionary<string, double> CreateReadings(params (string EntityId, double Watts)[] readings)
|
||||||
readings.ToDictionary(r => r.EntityId, r => r.Watts);
|
{
|
||||||
|
return readings.ToDictionary(r => r.EntityId, r => r.Watts);
|
||||||
|
}
|
||||||
|
|
||||||
public static PowerCalculationResult CreateCalculation(
|
public static PowerCalculationResult CreateCalculation(
|
||||||
double totalWatts = DefaultTotalWatts,
|
double totalWatts = DefaultTotalWatts,
|
||||||
@@ -77,7 +85,9 @@ internal static class PowerMonitorTestData
|
|||||||
double cost1Hour = 0.004,
|
double cost1Hour = 0.004,
|
||||||
double costDaily = 0.03,
|
double costDaily = 0.03,
|
||||||
double costMonthly = 0.9,
|
double costMonthly = 0.9,
|
||||||
bool partialWindow = true) => new()
|
bool partialWindow = true)
|
||||||
|
{
|
||||||
|
return new CostSnapshot
|
||||||
{
|
{
|
||||||
Cost15Min = cost15Min,
|
Cost15Min = cost15Min,
|
||||||
Cost1Hour = cost1Hour,
|
Cost1Hour = cost1Hour,
|
||||||
@@ -85,6 +95,7 @@ internal static class PowerMonitorTestData
|
|||||||
CostMonthly = costMonthly,
|
CostMonthly = costMonthly,
|
||||||
PartialWindow = partialWindow
|
PartialWindow = partialWindow
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static PowerUpdateContext CreateUpdateContext(
|
public static PowerUpdateContext CreateUpdateContext(
|
||||||
bool isAnomaly = false,
|
bool isAnomaly = false,
|
||||||
@@ -98,10 +109,10 @@ internal static class PowerMonitorTestData
|
|||||||
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(
|
||||||
cost15Min: 0.0005 * (index + 1),
|
0.0005 * (index + 1),
|
||||||
cost1Hour: 0.002 * (index + 1),
|
0.002 * (index + 1),
|
||||||
costDaily: 0.03 * (index + 1),
|
0.03 * (index + 1),
|
||||||
costMonthly: 0.9 * (index + 1))))
|
0.9 * (index + 1))))
|
||||||
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
|
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
|
||||||
|
|
||||||
return new PowerUpdateContext
|
return new PowerUpdateContext
|
||||||
@@ -135,8 +146,9 @@ internal static class PowerMonitorTestData
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null) =>
|
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null)
|
||||||
CreateOptions(options =>
|
{
|
||||||
|
return CreateOptions(options =>
|
||||||
{
|
{
|
||||||
options.EnforceLimitEnabled = true;
|
options.EnforceLimitEnabled = true;
|
||||||
options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts;
|
options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts;
|
||||||
@@ -146,18 +158,22 @@ internal static class PowerMonitorTestData
|
|||||||
options.PauseAndRestoreEntityIds = [AutoManagementEntityId];
|
options.PauseAndRestoreEntityIds = [AutoManagementEntityId];
|
||||||
configure?.Invoke(options);
|
configure?.Invoke(options);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public static PowerSensorInfo CreateSensor(
|
public static PowerSensorInfo CreateSensor(
|
||||||
string entityId,
|
string entityId,
|
||||||
string? friendlyName = null,
|
string? friendlyName = null,
|
||||||
string? deviceName = null,
|
string? deviceName = null,
|
||||||
string unitOfMeasurement = PowerMonitorConsts.WattUnit) => new()
|
string unitOfMeasurement = PowerMonitorConsts.WattUnit)
|
||||||
|
{
|
||||||
|
return new PowerSensorInfo
|
||||||
{
|
{
|
||||||
EntityId = entityId,
|
EntityId = entityId,
|
||||||
FriendlyName = friendlyName ?? entityId,
|
FriendlyName = friendlyName ?? entityId,
|
||||||
DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId),
|
DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId),
|
||||||
UnitOfMeasurement = unitOfMeasurement
|
UnitOfMeasurement = unitOfMeasurement
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static JsonElement CreateAttributesJson(
|
public static JsonElement CreateAttributesJson(
|
||||||
string? deviceClass,
|
string? deviceClass,
|
||||||
@@ -166,20 +182,11 @@ internal static class PowerMonitorTestData
|
|||||||
{
|
{
|
||||||
var attributes = new Dictionary<string, object?>();
|
var attributes = new Dictionary<string, object?>();
|
||||||
|
|
||||||
if (deviceClass is not null)
|
if (deviceClass is not null) attributes["device_class"] = deviceClass;
|
||||||
{
|
|
||||||
attributes["device_class"] = deviceClass;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (unitOfMeasurement is not null)
|
if (unitOfMeasurement is not null) attributes["unit_of_measurement"] = unitOfMeasurement;
|
||||||
{
|
|
||||||
attributes["unit_of_measurement"] = unitOfMeasurement;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (friendlyName is not null)
|
if (friendlyName is not null) attributes["friendly_name"] = friendlyName;
|
||||||
{
|
|
||||||
attributes["friendly_name"] = friendlyName;
|
|
||||||
}
|
|
||||||
|
|
||||||
return JsonSerializer.SerializeToElement(attributes);
|
return JsonSerializer.SerializeToElement(attributes);
|
||||||
}
|
}
|
||||||
@@ -188,20 +195,26 @@ internal static class PowerMonitorTestData
|
|||||||
/// Deterministic, strictly positive and monotonically increasing power samples
|
/// Deterministic, strictly positive and monotonically increasing power samples
|
||||||
/// used by the looping scenarios.
|
/// used by the looping scenarios.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static IReadOnlyList<double> CreatePowerSampleSeries(int count = 96) =>
|
public static IReadOnlyList<double> CreatePowerSampleSeries(int count = 96)
|
||||||
|
{
|
||||||
|
return
|
||||||
[
|
[
|
||||||
.. Enumerable.Range(0, count)
|
.. Enumerable.Range(0, count)
|
||||||
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
|
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
|
||||||
];
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Deterministic, strictly positive hourly tariff series (EUR/kWh).
|
/// Deterministic, strictly positive hourly tariff series (EUR/kWh).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static IReadOnlyList<double> CreateTariffPriceSeries(int count = 24) =>
|
private static IReadOnlyList<double> CreateTariffPriceSeries(int count = 24)
|
||||||
|
{
|
||||||
|
return
|
||||||
[
|
[
|
||||||
.. Enumerable.Range(0, count)
|
.. Enumerable.Range(0, count)
|
||||||
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
|
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
|
||||||
];
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart)
|
public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart)
|
||||||
{
|
{
|
||||||
@@ -214,9 +227,12 @@ internal static class PowerMonitorTestData
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) =>
|
public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15)
|
||||||
|
{
|
||||||
|
return
|
||||||
[
|
[
|
||||||
.. Enumerable.Range(0, count)
|
.. Enumerable.Range(0, count)
|
||||||
.Select(i => start.AddMinutes(i * intervalMinutes))
|
.Select(i => start.AddMinutes(i * intervalMinutes))
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
}
|
||||||
@@ -37,15 +37,63 @@ public class PowerSensorDiscoveryServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void SetupEntities(
|
private void SetupEntities(
|
||||||
params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) =>
|
params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities)
|
||||||
|
{
|
||||||
_haContextMock
|
_haContextMock
|
||||||
.Setup(h => h.GetAllEntities())
|
.Setup(h => h.GetAllEntities())
|
||||||
.Returns([.. entities.Select(entity => SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))]);
|
.Returns([
|
||||||
|
.. entities.Select(entity =>
|
||||||
|
SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
private void SetupEntitiesWithoutState(params string[] entityIds) =>
|
private void SetupEntitiesWithoutState(params string[] entityIds)
|
||||||
|
{
|
||||||
_haContextMock
|
_haContextMock
|
||||||
.Setup(h => h.GetAllEntities())
|
.Setup(h => h.GetAllEntities())
|
||||||
.Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
|
.Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region ExtractDeviceName
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")]
|
||||||
|
[InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")]
|
||||||
|
[InlineData("sensor.tv_power", "tv")]
|
||||||
|
[InlineData("sensor.temp_power", "temp")]
|
||||||
|
[InlineData("sensor.power", "power")]
|
||||||
|
[InlineData("sensor.TV_POWER", "TV")]
|
||||||
|
[InlineData("sensor.boiler_output_power", "boiler_output")]
|
||||||
|
[InlineData("sensor.temperature", "temperature")]
|
||||||
|
[InlineData("tv_power", "tv")]
|
||||||
|
[InlineData("sensor.", "")]
|
||||||
|
public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected)
|
||||||
|
{
|
||||||
|
PowerSensorDiscoveryService.ExtractDeviceName(entityId).Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region GlobToRegex
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)]
|
||||||
|
[InlineData("sensor.nordpool_*", "sensor.tv_power", false)]
|
||||||
|
[InlineData("sensor.nordpool_*", "SENSOR.NORDPOOL_CURRENT_PRICE", true)]
|
||||||
|
[InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)]
|
||||||
|
[InlineData("*_power", "sensor.sonoff_100215c534_power", true)]
|
||||||
|
[InlineData("*_power", "sensor.sonoff_100215c534_energy", false)]
|
||||||
|
[InlineData("sensor.tv_power", "sensor.tv_power", true)]
|
||||||
|
[InlineData("sensor.tv_power", "sensor.tv_power_2", false)]
|
||||||
|
[InlineData("sensor.?.power", "sensor.a.power", false)]
|
||||||
|
[InlineData("*", "anything at all", true)]
|
||||||
|
public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected)
|
||||||
|
{
|
||||||
|
var regex = PowerSensorDiscoveryService.GlobToRegex(glob);
|
||||||
|
regex.IsMatch(input).Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region Discovery
|
#region Discovery
|
||||||
|
|
||||||
@@ -96,7 +144,7 @@ public class PowerSensorDiscoveryServiceTests
|
|||||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||||
("sensor.tv_power", "power", "W", "TV Power"));
|
("sensor.tv_power", "power", "W", "TV Power"));
|
||||||
|
|
||||||
var sut = CreateSut(mainMeterEntityId: string.Empty);
|
var sut = CreateSut(string.Empty);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
var result = sut.DiscoverDeviceSensors();
|
var result = sut.DiscoverDeviceSensors();
|
||||||
@@ -271,47 +319,6 @@ public class PowerSensorDiscoveryServiceTests
|
|||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region ExtractDeviceName
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")]
|
|
||||||
[InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")]
|
|
||||||
[InlineData("sensor.tv_power", "tv")]
|
|
||||||
[InlineData("sensor.temp_power", "temp")]
|
|
||||||
[InlineData("sensor.power", "power")]
|
|
||||||
[InlineData("sensor.TV_POWER", "TV")]
|
|
||||||
[InlineData("sensor.boiler_output_power", "boiler_output")]
|
|
||||||
[InlineData("sensor.temperature", "temperature")]
|
|
||||||
[InlineData("tv_power", "tv")]
|
|
||||||
[InlineData("sensor.", "")]
|
|
||||||
public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected)
|
|
||||||
{
|
|
||||||
PowerSensorDiscoveryService.ExtractDeviceName(entityId).Should().Be(expected);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region GlobToRegex
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)]
|
|
||||||
[InlineData("sensor.nordpool_*", "sensor.tv_power", false)]
|
|
||||||
[InlineData("sensor.nordpool_*", "SENSOR.NORDPOOL_CURRENT_PRICE", true)]
|
|
||||||
[InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)]
|
|
||||||
[InlineData("*_power", "sensor.sonoff_100215c534_power", true)]
|
|
||||||
[InlineData("*_power", "sensor.sonoff_100215c534_energy", false)]
|
|
||||||
[InlineData("sensor.tv_power", "sensor.tv_power", true)]
|
|
||||||
[InlineData("sensor.tv_power", "sensor.tv_power_2", false)]
|
|
||||||
[InlineData("sensor.?.power", "sensor.a.power", false)]
|
|
||||||
[InlineData("*", "anything at all", true)]
|
|
||||||
public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected)
|
|
||||||
{
|
|
||||||
var regex = PowerSensorDiscoveryService.GlobToRegex(glob);
|
|
||||||
regex.IsMatch(input).Should().Be(expected);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region IsPowerSensor
|
#region IsPowerSensor
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ namespace PowerMonitorManager.Interface;
|
|||||||
|
|
||||||
public interface IPowerCostCalculationService
|
public interface IPowerCostCalculationService
|
||||||
{
|
{
|
||||||
|
double LastKnownPrice { get; }
|
||||||
|
string PriceSource { get; }
|
||||||
void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now);
|
void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now);
|
||||||
CostSnapshot GetTotalCostSnapshot();
|
CostSnapshot GetTotalCostSnapshot();
|
||||||
CostSnapshot GetOtherCostSnapshot();
|
CostSnapshot GetOtherCostSnapshot();
|
||||||
IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots();
|
IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots();
|
||||||
double LastKnownPrice { get; }
|
|
||||||
string PriceSource { get; }
|
|
||||||
}
|
}
|
||||||
@@ -2,11 +2,10 @@ namespace PowerMonitorManager.Interface;
|
|||||||
|
|
||||||
public interface IPowerLimitEnforcementService
|
public interface IPowerLimitEnforcementService
|
||||||
{
|
{
|
||||||
|
bool IsLimitActive { get; }
|
||||||
void EnforceLimit(double currentPowerWatts);
|
void EnforceLimit(double currentPowerWatts);
|
||||||
|
|
||||||
void TriggerLimitBreach();
|
void TriggerLimitBreach();
|
||||||
|
|
||||||
void ResetLimitBreach();
|
void ResetLimitBreach();
|
||||||
|
|
||||||
bool IsLimitActive { get; }
|
|
||||||
}
|
}
|
||||||
@@ -6,9 +6,14 @@ namespace PowerMonitorManager.Interface;
|
|||||||
public interface IPowerMonitorEntityService
|
public interface IPowerMonitorEntityService
|
||||||
{
|
{
|
||||||
Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors, CancellationToken cancellationToken = default);
|
|
||||||
|
Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors,
|
||||||
|
CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default);
|
Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default);
|
||||||
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
Task RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
Task RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames, CancellationToken cancellationToken = default);
|
|
||||||
|
Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames,
|
||||||
|
CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,6 @@ namespace PowerMonitorManager.Interface;
|
|||||||
|
|
||||||
public interface IPowerSensorDiscoveryService
|
public interface IPowerSensorDiscoveryService
|
||||||
{
|
{
|
||||||
IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors();
|
|
||||||
IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors { get; }
|
IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors { get; }
|
||||||
|
IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors();
|
||||||
}
|
}
|
||||||
@@ -9,11 +9,6 @@ public sealed class CostAccumulator(DateTime now)
|
|||||||
private double _costDaily;
|
private double _costDaily;
|
||||||
private double _costMonthly;
|
private double _costMonthly;
|
||||||
|
|
||||||
private double _previous15Min;
|
|
||||||
private double _previous1Hour;
|
|
||||||
private double _previousDaily;
|
|
||||||
private double _previousMonthly;
|
|
||||||
|
|
||||||
private DateTime _last15MinReset = now;
|
private DateTime _last15MinReset = now;
|
||||||
private DateTime _last1HourReset = now;
|
private DateTime _last1HourReset = now;
|
||||||
private DateTime _lastDailyReset = now;
|
private DateTime _lastDailyReset = now;
|
||||||
@@ -21,6 +16,11 @@ public sealed class CostAccumulator(DateTime now)
|
|||||||
|
|
||||||
private bool _partialWindow = true;
|
private bool _partialWindow = true;
|
||||||
|
|
||||||
|
private double _previous15Min;
|
||||||
|
private double _previous1Hour;
|
||||||
|
private double _previousDaily;
|
||||||
|
private double _previousMonthly;
|
||||||
|
|
||||||
public void AddCost(double costIncrement, DateTime now)
|
public void AddCost(double costIncrement, DateTime now)
|
||||||
{
|
{
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
@@ -77,10 +77,7 @@ public sealed class CostAccumulator(DateTime now)
|
|||||||
_lastDailyReset = now;
|
_lastDailyReset = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!IsNewMonthWindow(now, _lastMonthlyReset))
|
if (!IsNewMonthWindow(now, _lastMonthlyReset)) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_previousMonthly = _costMonthly;
|
_previousMonthly = _costMonthly;
|
||||||
_costMonthly = 0;
|
_costMonthly = 0;
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ namespace PowerMonitorManager;
|
|||||||
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
||||||
{
|
{
|
||||||
private readonly double _alpha;
|
private readonly double _alpha;
|
||||||
private double? _previousSmoothed;
|
|
||||||
private readonly Lock _lock = new();
|
private readonly Lock _lock = new();
|
||||||
|
private double? _previousSmoothed;
|
||||||
|
|
||||||
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
|
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,35 +7,39 @@ namespace PowerMonitorManager;
|
|||||||
|
|
||||||
public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||||
{
|
{
|
||||||
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
|
|
||||||
private CostAccumulator? _totalAccumulator;
|
|
||||||
private CostAccumulator? _otherAccumulator;
|
|
||||||
private readonly Lock _accumulatorLock = new();
|
private readonly Lock _accumulatorLock = new();
|
||||||
|
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
|
||||||
|
private readonly Lock _priceLock = new();
|
||||||
|
|
||||||
private double _lastKnownPrice;
|
private double _lastKnownPrice;
|
||||||
|
private CostAccumulator? _otherAccumulator;
|
||||||
private string _priceSource = "live";
|
private string _priceSource = "live";
|
||||||
private readonly Lock _priceLock = new();
|
private CostAccumulator? _totalAccumulator;
|
||||||
|
|
||||||
public double LastKnownPrice
|
public double LastKnownPrice
|
||||||
{
|
{
|
||||||
get { lock (_priceLock) { return _lastKnownPrice; } }
|
get
|
||||||
|
{
|
||||||
|
lock (_priceLock)
|
||||||
|
{
|
||||||
|
return _lastKnownPrice;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public string PriceSource
|
public string PriceSource
|
||||||
{
|
{
|
||||||
get { lock (_priceLock) { return _priceSource; } }
|
get
|
||||||
}
|
|
||||||
|
|
||||||
public void SetPrice(double price)
|
|
||||||
{
|
{
|
||||||
lock (_priceLock)
|
lock (_priceLock)
|
||||||
{
|
{
|
||||||
_lastKnownPrice = price;
|
return _priceSource;
|
||||||
_priceSource = "stale";
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now)
|
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds,
|
||||||
|
DateTime now)
|
||||||
{
|
{
|
||||||
lock (_priceLock)
|
lock (_priceLock)
|
||||||
{
|
{
|
||||||
@@ -51,7 +55,8 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
|||||||
var totalCost = CalculateCostIncrement(calculation.TotalPowerWatts, effectivePrice, pollIntervalSeconds);
|
var totalCost = CalculateCostIncrement(calculation.TotalPowerWatts, effectivePrice, pollIntervalSeconds);
|
||||||
GetOrCreateTotalAccumulator(now).AddCost(totalCost, now);
|
GetOrCreateTotalAccumulator(now).AddCost(totalCost, now);
|
||||||
|
|
||||||
var otherCost = CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
|
var otherCost =
|
||||||
|
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)
|
||||||
@@ -78,13 +83,6 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public CostSnapshot GetDeviceCostSnapshot(string entityId)
|
|
||||||
{
|
|
||||||
return _deviceAccumulators.TryGetValue(entityId, out var accumulator)
|
|
||||||
? accumulator.GetSnapshot()
|
|
||||||
: CreateEmptySnapshot();
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots()
|
public IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots()
|
||||||
{
|
{
|
||||||
return _deviceAccumulators.ToDictionary(
|
return _deviceAccumulators.ToDictionary(
|
||||||
@@ -92,6 +90,22 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
|||||||
kvp => kvp.Value.GetSnapshot());
|
kvp => kvp.Value.GetSnapshot());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void SetPrice(double price)
|
||||||
|
{
|
||||||
|
lock (_priceLock)
|
||||||
|
{
|
||||||
|
_lastKnownPrice = price;
|
||||||
|
_priceSource = "stale";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CostSnapshot GetDeviceCostSnapshot(string entityId)
|
||||||
|
{
|
||||||
|
return _deviceAccumulators.TryGetValue(entityId, out var accumulator)
|
||||||
|
? accumulator.GetSnapshot()
|
||||||
|
: CreateEmptySnapshot();
|
||||||
|
}
|
||||||
|
|
||||||
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
|
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
|
||||||
{
|
{
|
||||||
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
|
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
|
||||||
|
|||||||
@@ -25,10 +25,7 @@ public sealed class PowerLimitEnforcementService(
|
|||||||
|
|
||||||
public void EnforceLimit(double currentPowerWatts)
|
public void EnforceLimit(double currentPowerWatts)
|
||||||
{
|
{
|
||||||
if (!_options.EnforceLimitEnabled)
|
if (!_options.EnforceLimitEnabled) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var now = timeProvider.GetUtcNow();
|
var now = timeProvider.GetUtcNow();
|
||||||
|
|
||||||
@@ -67,15 +64,9 @@ public sealed class PowerLimitEnforcementService(
|
|||||||
|
|
||||||
private void ExecuteEnforce(double currentPowerWatts)
|
private void ExecuteEnforce(double currentPowerWatts)
|
||||||
{
|
{
|
||||||
foreach (var entityId in _options.EnforceSwitchOffEntityIds)
|
foreach (var entityId in _options.EnforceSwitchOffEntityIds) TurnOff(entityId);
|
||||||
{
|
|
||||||
TurnOff(entityId);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOff(entityId);
|
||||||
{
|
|
||||||
TurnOff(entityId);
|
|
||||||
}
|
|
||||||
|
|
||||||
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
|
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
|
||||||
|
|
||||||
@@ -87,10 +78,7 @@ public sealed class PowerLimitEnforcementService(
|
|||||||
|
|
||||||
private void ExecuteRecover()
|
private void ExecuteRecover()
|
||||||
{
|
{
|
||||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
|
||||||
{
|
|
||||||
TurnOn(entityId);
|
|
||||||
}
|
|
||||||
|
|
||||||
DismissLimitNotification();
|
DismissLimitNotification();
|
||||||
|
|
||||||
@@ -100,22 +88,20 @@ public sealed class PowerLimitEnforcementService(
|
|||||||
|
|
||||||
private void TryEnforce(double currentPowerWatts, DateTimeOffset now)
|
private void TryEnforce(double currentPowerWatts, DateTimeOffset now)
|
||||||
{
|
{
|
||||||
if (currentPowerWatts <= _options.PowerLimitWatts)
|
if (currentPowerWatts <= _options.PowerLimitWatts) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
|
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
logger.LogDebug(
|
||||||
logger.LogDebug("Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", currentPowerWatts, _options.PowerLimitWatts);
|
"Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping",
|
||||||
}
|
currentPowerWatts, _options.PowerLimitWatts);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts, _options.PowerLimitWatts);
|
logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts,
|
||||||
|
_options.PowerLimitWatts);
|
||||||
|
|
||||||
ExecuteEnforce(currentPowerWatts);
|
ExecuteEnforce(currentPowerWatts);
|
||||||
}
|
}
|
||||||
@@ -124,28 +110,23 @@ public sealed class PowerLimitEnforcementService(
|
|||||||
{
|
{
|
||||||
var elapsed = now - _enforcedAt;
|
var elapsed = now - _enforcedAt;
|
||||||
|
|
||||||
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds))
|
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds)) return;
|
||||||
{
|
|
||||||
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", currentPowerWatts, _options.PowerLimitWatts);
|
logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced",
|
||||||
|
currentPowerWatts, _options.PowerLimitWatts);
|
||||||
_enforcedAt = now;
|
_enforcedAt = now;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
logger.LogInformation(
|
||||||
logger.LogInformation("Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors", currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
|
"Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors",
|
||||||
}
|
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
|
||||||
|
|
||||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
|
||||||
{
|
|
||||||
TurnOn(entityId);
|
|
||||||
}
|
|
||||||
|
|
||||||
DismissLimitNotification();
|
DismissLimitNotification();
|
||||||
|
|
||||||
@@ -155,17 +136,20 @@ public sealed class PowerLimitEnforcementService(
|
|||||||
|
|
||||||
private void TurnOff(string entityId)
|
private void TurnOff(string entityId)
|
||||||
{
|
{
|
||||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService, ServiceTarget.FromEntity(entityId));
|
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService,
|
||||||
|
ServiceTarget.FromEntity(entityId));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void TurnOn(string entityId)
|
private void TurnOn(string entityId)
|
||||||
{
|
{
|
||||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService, ServiceTarget.FromEntity(entityId));
|
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService,
|
||||||
|
ServiceTarget.FromEntity(entityId));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts)
|
private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts)
|
||||||
{
|
{
|
||||||
var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt, limitWatts / PowerMonitorConsts.WattsPerKilowatt);
|
var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt,
|
||||||
|
limitWatts / PowerMonitorConsts.WattsPerKilowatt);
|
||||||
|
|
||||||
haContext.CallService(
|
haContext.CallService(
|
||||||
PowerMonitorConsts.PersistentNotificationDomain,
|
PowerMonitorConsts.PersistentNotificationDomain,
|
||||||
|
|||||||
@@ -49,9 +49,7 @@ public sealed class PowerMonitorEntityService(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
|
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
|
||||||
}
|
|
||||||
|
|
||||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -64,7 +62,8 @@ public sealed class PowerMonitorEntityService(
|
|||||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors, CancellationToken cancellationToken = default)
|
public async Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
@@ -74,9 +73,7 @@ public sealed class PowerMonitorEntityService(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (logger.IsEnabled(LogLevel.Information))
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
||||||
}
|
|
||||||
|
|
||||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -98,15 +95,23 @@ public sealed class PowerMonitorEntityService(
|
|||||||
var tasks = new List<Task>
|
var tasks = new List<Task>
|
||||||
{
|
{
|
||||||
UpdateTotalPowerAsync(context, timestamp),
|
UpdateTotalPowerAsync(context, timestamp),
|
||||||
UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost, "Total cost (15 min)", timestamp),
|
UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost,
|
||||||
UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost, "Total cost (1h)", timestamp),
|
"Total cost (15 min)", timestamp),
|
||||||
UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost, "Total cost (daily)", timestamp),
|
UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost,
|
||||||
UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost, "Total cost (monthly)", timestamp),
|
"Total cost (1h)", timestamp),
|
||||||
|
UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost,
|
||||||
|
"Total cost (daily)", timestamp),
|
||||||
|
UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost,
|
||||||
|
"Total cost (monthly)", timestamp),
|
||||||
UpdateOtherPowerAsync(context, timestamp),
|
UpdateOtherPowerAsync(context, timestamp),
|
||||||
UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost, "Other cost (15 min)", timestamp),
|
UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost,
|
||||||
UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost, "Other cost (1h)", timestamp),
|
"Other cost (15 min)", timestamp),
|
||||||
UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost, "Other cost (daily)", timestamp),
|
UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost,
|
||||||
UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost, "Other cost (monthly)", timestamp),
|
"Other cost (1h)", timestamp),
|
||||||
|
UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost,
|
||||||
|
"Other cost (daily)", timestamp),
|
||||||
|
UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost,
|
||||||
|
"Other cost (monthly)", timestamp),
|
||||||
UpdateAnomalyAsync(context, timestamp),
|
UpdateAnomalyAsync(context, timestamp),
|
||||||
UpdateStatusAsync(context, timestamp)
|
UpdateStatusAsync(context, timestamp)
|
||||||
};
|
};
|
||||||
@@ -114,10 +119,14 @@ 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, costSnapshot, $"{deviceName} cost (15 min)", timestamp));
|
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min,
|
||||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour, costSnapshot, $"{deviceName} cost (1h)", timestamp));
|
costSnapshot, $"{deviceName} cost (15 min)", timestamp));
|
||||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily, costSnapshot, $"{deviceName} cost (daily)", timestamp));
|
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour,
|
||||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly, costSnapshot, $"{deviceName} cost (monthly)", timestamp));
|
costSnapshot, $"{deviceName} cost (1h)", timestamp));
|
||||||
|
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily,
|
||||||
|
costSnapshot, $"{deviceName} cost (daily)", timestamp));
|
||||||
|
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly,
|
||||||
|
costSnapshot, $"{deviceName} cost (monthly)", timestamp));
|
||||||
}
|
}
|
||||||
|
|
||||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||||
@@ -166,7 +175,8 @@ public sealed class PowerMonitorEntityService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames, CancellationToken cancellationToken = default)
|
public async Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
@@ -178,10 +188,7 @@ public sealed class PowerMonitorEntityService(
|
|||||||
{
|
{
|
||||||
await entityManager.RemoveEntity(id).ConfigureAwait(false);
|
await entityManager.RemoveEntity(id).ConfigureAwait(false);
|
||||||
|
|
||||||
if (logger.IsEnabled(LogLevel.Debug))
|
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Entity removed: {EntityId}", id);
|
||||||
{
|
|
||||||
logger.LogDebug("Entity removed: {EntityId}", id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -199,7 +206,12 @@ public sealed class PowerMonitorEntityService(
|
|||||||
{
|
{
|
||||||
new("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
new("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = PowerMonitorConsts.WattUnit, device_class = PowerMonitorConsts.PowerDeviceClass, state_class = PowerMonitorConsts.MeasurementStateClass }
|
AdditionalConfig = new
|
||||||
|
{
|
||||||
|
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||||
|
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||||
|
state_class = PowerMonitorConsts.MeasurementStateClass
|
||||||
|
}
|
||||||
},
|
},
|
||||||
CreateCostEntity("powermonitor_total_cost_15min", "PowerMonitor total cost (15 min)"),
|
CreateCostEntity("powermonitor_total_cost_15min", "PowerMonitor total cost (15 min)"),
|
||||||
CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"),
|
CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"),
|
||||||
@@ -207,7 +219,12 @@ public sealed class PowerMonitorEntityService(
|
|||||||
CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"),
|
CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"),
|
||||||
new("sensor", "powermonitor_other_power", "PowerMonitor other power")
|
new("sensor", "powermonitor_other_power", "PowerMonitor other power")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = PowerMonitorConsts.WattUnit, device_class = PowerMonitorConsts.PowerDeviceClass, state_class = PowerMonitorConsts.MeasurementStateClass }
|
AdditionalConfig = new
|
||||||
|
{
|
||||||
|
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||||
|
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||||
|
state_class = PowerMonitorConsts.MeasurementStateClass
|
||||||
|
}
|
||||||
},
|
},
|
||||||
CreateCostEntity("powermonitor_other_cost_15min", "PowerMonitor other cost (15 min)"),
|
CreateCostEntity("powermonitor_other_cost_15min", "PowerMonitor other cost (15 min)"),
|
||||||
CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"),
|
CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"),
|
||||||
@@ -293,7 +310,8 @@ public sealed class PowerMonitorEntityService(
|
|||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateCostEntityAsync(string entityId, double costValue, CostSnapshot snapshot, string friendlyName, string timestamp)
|
private async Task UpdateCostEntityAsync(string entityId, double costValue, CostSnapshot snapshot,
|
||||||
|
string friendlyName, string timestamp)
|
||||||
{
|
{
|
||||||
var value = costValue.ToString("F4", CultureInfo.InvariantCulture);
|
var value = costValue.ToString("F4", CultureInfo.InvariantCulture);
|
||||||
await SetEntityStateSafe(entityId, value).ConfigureAwait(false);
|
await SetEntityStateSafe(entityId, value).ConfigureAwait(false);
|
||||||
|
|||||||
@@ -15,21 +15,21 @@ namespace PowerMonitorManager;
|
|||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class PowerMonitorInit
|
public sealed class PowerMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<PowerMonitorInit> _logger;
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly PowerMonitorOptions _options;
|
|
||||||
private readonly IPowerSensorDiscoveryService _discoveryService;
|
|
||||||
private readonly IOtherPowerCalculationService _calculationService;
|
private readonly IOtherPowerCalculationService _calculationService;
|
||||||
private readonly IPowerCostCalculationService _costService;
|
private readonly IPowerCostCalculationService _costService;
|
||||||
private readonly IPowerMonitorEntityService _entityService;
|
private readonly IPowerSensorDiscoveryService _discoveryService;
|
||||||
private readonly IPowerNotificationService _notificationService;
|
|
||||||
private readonly IPowerLimitEnforcementService _enforcementService;
|
private readonly IPowerLimitEnforcementService _enforcementService;
|
||||||
|
private readonly IPowerMonitorEntityService _entityService;
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<PowerMonitorInit> _logger;
|
||||||
|
private readonly IPowerNotificationService _notificationService;
|
||||||
|
private readonly PowerMonitorOptions _options;
|
||||||
private readonly TimeProvider _timeProvider;
|
private readonly TimeProvider _timeProvider;
|
||||||
|
private DateTimeOffset? _anomalyStartTime;
|
||||||
|
private bool _highPowerNotificationActive;
|
||||||
|
private DateTimeOffset? _lastPollTimestamp;
|
||||||
|
|
||||||
private int _mainMeterConsecutiveFailures;
|
private int _mainMeterConsecutiveFailures;
|
||||||
private DateTimeOffset? _anomalyStartTime;
|
|
||||||
private DateTimeOffset? _lastPollTimestamp;
|
|
||||||
private bool _highPowerNotificationActive;
|
|
||||||
|
|
||||||
public PowerMonitorInit(
|
public PowerMonitorInit(
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
@@ -99,9 +99,7 @@ public sealed class PowerMonitorInit
|
|||||||
await _entityService.CreateDeviceEntitiesAsync(sensors);
|
await _entityService.CreateDeviceEntitiesAsync(sensors);
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count);
|
_logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count);
|
||||||
}
|
|
||||||
|
|
||||||
await PollAndUpdateAsync();
|
await PollAndUpdateAsync();
|
||||||
}
|
}
|
||||||
@@ -136,19 +134,14 @@ public sealed class PowerMonitorInit
|
|||||||
meter.StateChanges()
|
meter.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
if (e.Old?.State == e.New?.State)
|
if (e.Old?.State == e.New?.State) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = PollAndUpdateAsync();
|
_ = PollAndUpdateAsync();
|
||||||
});
|
});
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
|
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private void SubscribeToRediscoverButton()
|
private void SubscribeToRediscoverButton()
|
||||||
{
|
{
|
||||||
@@ -197,20 +190,14 @@ public sealed class PowerMonitorInit
|
|||||||
{
|
{
|
||||||
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)
|
if (removed.Count > 0) await RemoreDevicePriceEntities(removed);
|
||||||
{
|
|
||||||
await RemoreDevicePriceEntities(removed);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)",
|
||||||
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", newSensors.Count, added.Count, removed.Count);
|
newSensors.Count, added.Count, removed.Count);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -224,10 +211,8 @@ public sealed class PowerMonitorInit
|
|||||||
await _entityService.RemoveDeviceEntitiesAsync(removedNames);
|
await _entityService.RemoveDeviceEntitiesAsync(removedNames);
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
|
||||||
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
|
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private async Task PollAndUpdateAsync()
|
private async Task PollAndUpdateAsync()
|
||||||
{
|
{
|
||||||
@@ -237,7 +222,8 @@ public sealed class PowerMonitorInit
|
|||||||
if (totalPower is null)
|
if (totalPower is null)
|
||||||
{
|
{
|
||||||
_mainMeterConsecutiveFailures++;
|
_mainMeterConsecutiveFailures++;
|
||||||
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures,
|
||||||
|
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -302,10 +288,10 @@ public sealed class PowerMonitorInit
|
|||||||
_enforcementService.EnforceLimit(calculation.TotalPowerWatts);
|
_enforcementService.EnforceLimit(calculation.TotalPowerWatts);
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Debug))
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
_logger.LogDebug(
|
||||||
_logger.LogDebug("Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
||||||
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, effectivePrice);
|
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
|
||||||
}
|
effectivePrice);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -323,15 +309,10 @@ public sealed class PowerMonitorInit
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0)
|
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) return price;
|
||||||
{
|
|
||||||
return price;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Debug))
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
|
||||||
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
|
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -357,10 +338,7 @@ 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")
|
if (state?.State is null or "unavailable" or "unknown") return null;
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
|
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
|
||||||
? value
|
? value
|
||||||
@@ -384,7 +362,8 @@ public sealed class PowerMonitorInit
|
|||||||
|
|
||||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
|
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
|
||||||
{
|
{
|
||||||
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase)
|
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit,
|
||||||
|
StringComparison.OrdinalIgnoreCase)
|
||||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||||
: value;
|
: value;
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,8 @@ public sealed class PowerNotificationService(
|
|||||||
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", currentKw, thresholdKw);
|
logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)",
|
||||||
|
currentKw, thresholdKw);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void DismissHighPowerNotification()
|
public void DismissHighPowerNotification()
|
||||||
|
|||||||
@@ -13,15 +13,13 @@ namespace PowerMonitorManager;
|
|||||||
|
|
||||||
public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||||
{
|
{
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly PowerMonitorOptions _options;
|
|
||||||
private readonly ILogger<PowerSensorDiscoveryService> _logger;
|
|
||||||
private readonly Regex[] _exclusionPatterns;
|
private readonly Regex[] _exclusionPatterns;
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<PowerSensorDiscoveryService> _logger;
|
||||||
|
private readonly PowerMonitorOptions _options;
|
||||||
|
|
||||||
private volatile IReadOnlyList<PowerSensorInfo> _currentDeviceSensors = [];
|
private volatile IReadOnlyList<PowerSensorInfo> _currentDeviceSensors = [];
|
||||||
|
|
||||||
public IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors => _currentDeviceSensors;
|
|
||||||
|
|
||||||
public PowerSensorDiscoveryService(
|
public PowerSensorDiscoveryService(
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
IOptions<PowerMonitorOptions> options,
|
IOptions<PowerMonitorOptions> options,
|
||||||
@@ -33,6 +31,8 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
|||||||
_exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)];
|
_exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors => _currentDeviceSensors;
|
||||||
|
|
||||||
public IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors()
|
public IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors()
|
||||||
{
|
{
|
||||||
var allEntities = _haContext.GetAllEntities();
|
var allEntities = _haContext.GetAllEntities();
|
||||||
@@ -53,26 +53,19 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
|||||||
_currentDeviceSensors = powerSensors;
|
_currentDeviceSensors = powerSensors;
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Information))
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
_logger.LogInformation(
|
||||||
_logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||||
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
||||||
}
|
|
||||||
|
|
||||||
return powerSensors;
|
return powerSensors;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static bool IsPowerSensor(Entity entity)
|
internal static bool IsPowerSensor(Entity entity)
|
||||||
{
|
{
|
||||||
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase))
|
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var attributes = entity.EntityState?.AttributesJson;
|
var attributes = entity.EntityState?.AttributesJson;
|
||||||
if (attributes is null)
|
if (attributes is null) return false;
|
||||||
{
|
|
||||||
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");
|
||||||
@@ -117,10 +110,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
|||||||
|
|
||||||
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||||
{
|
{
|
||||||
if (element is null)
|
if (element is null) return null;
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return element.Value.TryGetProperty(propertyName, out var value)
|
return element.Value.TryGetProperty(propertyName, out var value)
|
||||||
? value.GetString()
|
? value.GetString()
|
||||||
|
|||||||
@@ -5,10 +5,6 @@ namespace PowerMonitor.Models;
|
|||||||
|
|
||||||
public class PowerMonitorEntity : EntityCreateModel
|
public class PowerMonitorEntity : EntityCreateModel
|
||||||
{
|
{
|
||||||
public string Domain { get; }
|
|
||||||
public string Identifier { get; }
|
|
||||||
public string Name { get; }
|
|
||||||
|
|
||||||
public PowerMonitorEntity(string domain, string identifier, string name)
|
public PowerMonitorEntity(string domain, string identifier, string name)
|
||||||
{
|
{
|
||||||
Domain = domain;
|
Domain = domain;
|
||||||
@@ -22,4 +18,8 @@ public class PowerMonitorEntity : EntityCreateModel
|
|||||||
Name = Name
|
Name = Name
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public string Domain { get; }
|
||||||
|
public string Identifier { get; }
|
||||||
|
public string Name { get; }
|
||||||
}
|
}
|
||||||
@@ -15,8 +15,8 @@ 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 FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider();
|
|
||||||
private readonly Mock<IHaContext> _haContextMock = new();
|
private readonly Mock<IHaContext> _haContextMock = new();
|
||||||
|
private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider();
|
||||||
|
|
||||||
private DateTimeOffset Now => _timeProvider.GetUtcNow();
|
private DateTimeOffset Now => _timeProvider.GetUtcNow();
|
||||||
|
|
||||||
@@ -237,7 +237,7 @@ public class ExhaustFanControlServiceTests
|
|||||||
[InlineData(null)]
|
[InlineData(null)]
|
||||||
public void Evaluate_WithConfiguredFanEntityId_TargetsThatExactEntity(string? entityId)
|
public void Evaluate_WithConfiguredFanEntityId_TargetsThatExactEntity(string? entityId)
|
||||||
{
|
{
|
||||||
var service = CreateService(ShowerMonitorTestData.CreateOptions(exhaustFanEntityId: entityId!));
|
var service = CreateService(ShowerMonitorTestData.CreateOptions(entityId!));
|
||||||
|
|
||||||
service.Evaluate(ShowerState.Active, Now);
|
service.Evaluate(ShowerState.Active, Now);
|
||||||
|
|
||||||
|
|||||||
@@ -49,9 +49,7 @@ 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}");
|
||||||
}
|
}
|
||||||
@@ -61,18 +59,15 @@ public class HumidityRateCalculatorTests
|
|||||||
{
|
{
|
||||||
const double ratePerMinute = 2.5;
|
const double ratePerMinute = 2.5;
|
||||||
var series = ShowerMonitorTestData.CreateLinearHumiditySeries(
|
var series = ShowerMonitorTestData.CreateLinearHumiditySeries(
|
||||||
startHumidity: 45.0,
|
45.0,
|
||||||
ratePerMinute: ratePerMinute,
|
ratePerMinute,
|
||||||
sampleCount: 12);
|
12);
|
||||||
|
|
||||||
for (var windowSize = 2; windowSize <= series.Count; windowSize++)
|
for (var windowSize = 2; windowSize <= series.Count; windowSize++)
|
||||||
{
|
{
|
||||||
var calculator = new HumidityRateCalculator(windowSize);
|
var calculator = new HumidityRateCalculator(windowSize);
|
||||||
|
|
||||||
foreach (var sample in series)
|
foreach (var sample in series) calculator.RecordReading(sample.Humidity, Now + sample.Offset);
|
||||||
{
|
|
||||||
calculator.RecordReading(sample.Humidity, Now + sample.Offset);
|
|
||||||
}
|
|
||||||
|
|
||||||
calculator.GetRatePerMinute()
|
calculator.GetRatePerMinute()
|
||||||
.Should()
|
.Should()
|
||||||
|
|||||||
@@ -158,10 +158,7 @@ public class ShowerDetectionServiceTests
|
|||||||
service.TodaySessionCount.Should().Be(0);
|
service.TodaySessionCount.Should().Be(0);
|
||||||
service.LastCompletedSession.Should().BeNull();
|
service.LastCompletedSession.Should().BeNull();
|
||||||
|
|
||||||
if (expectedState == ShowerState.Active)
|
if (expectedState == ShowerState.Active) service.CurrentSession.Should().NotBeNull();
|
||||||
{
|
|
||||||
service.CurrentSession.Should().NotBeNull();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -16,7 +16,10 @@ internal static class ShowerMonitorTestData
|
|||||||
private static readonly DateTimeOffset BaseTimestamp = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
private static readonly DateTimeOffset BaseTimestamp = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
/// <summary>Creates a fake clock positioned at <see cref="BaseTimestamp" /> unless overridden.</summary>
|
/// <summary>Creates a fake clock positioned at <see cref="BaseTimestamp" /> unless overridden.</summary>
|
||||||
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) => new(start ?? BaseTimestamp);
|
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null)
|
||||||
|
{
|
||||||
|
return new FakeTimeProvider(start ?? BaseTimestamp);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds monitor options from the production defaults, overriding only the
|
/// Builds monitor options from the production defaults, overriding only the
|
||||||
@@ -50,15 +53,20 @@ internal static class ShowerMonitorTestData
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Creates the HA state payload for the exhaust fan.</summary>
|
/// <summary>Creates the HA state payload for the exhaust fan.</summary>
|
||||||
public static EntityState FanState(string? state) => new() { State = state };
|
public static EntityState FanState(string? state)
|
||||||
|
{
|
||||||
/// <summary>A humidity sample with its offset from a test's base timestamp.</summary>
|
return new EntityState { State = state };
|
||||||
public readonly record struct HumiditySample(double Humidity, TimeSpan Offset);
|
}
|
||||||
|
|
||||||
/// <summary>Builds a sample series from (humidity, offset-in-seconds) pairs.</summary>
|
/// <summary>Builds a sample series from (humidity, offset-in-seconds) pairs.</summary>
|
||||||
public static IReadOnlyList<HumiditySample> CreateHumiditySeries(
|
public static IReadOnlyList<HumiditySample> CreateHumiditySeries(
|
||||||
params (double Humidity, int OffsetSeconds)[] samples) =>
|
params (double Humidity, int OffsetSeconds)[] samples)
|
||||||
[.. samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds)))];
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds)))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Generates evenly spaced samples along a constant humidity slope, useful for
|
/// Generates evenly spaced samples along a constant humidity slope, useful for
|
||||||
@@ -68,9 +76,17 @@ internal static class ShowerMonitorTestData
|
|||||||
double startHumidity,
|
double startHumidity,
|
||||||
double ratePerMinute,
|
double ratePerMinute,
|
||||||
int sampleCount,
|
int sampleCount,
|
||||||
int intervalSeconds = 60) =>
|
int intervalSeconds = 60)
|
||||||
[.. Enumerable.Range(0, sampleCount)
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, sampleCount)
|
||||||
.Select(i => new HumiditySample(
|
.Select(i => new HumiditySample(
|
||||||
startHumidity + ratePerMinute * i * intervalSeconds / 60.0,
|
startHumidity + ratePerMinute * i * intervalSeconds / 60.0,
|
||||||
TimeSpan.FromSeconds(i * intervalSeconds)))];
|
TimeSpan.FromSeconds(i * intervalSeconds)))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A humidity sample with its offset from a test's base timestamp.</summary>
|
||||||
|
public readonly record struct HumiditySample(double Humidity, TimeSpan Offset);
|
||||||
}
|
}
|
||||||
@@ -11,8 +11,8 @@ public sealed class ExhaustFanControlService(
|
|||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
IOptions<ShowerMonitorOptions> options) : IExhaustFanControlService
|
IOptions<ShowerMonitorOptions> options) : IExhaustFanControlService
|
||||||
{
|
{
|
||||||
private readonly ShowerMonitorOptions _options = options.Value;
|
|
||||||
private readonly Lock _lock = new();
|
private readonly Lock _lock = new();
|
||||||
|
private readonly ShowerMonitorOptions _options = options.Value;
|
||||||
|
|
||||||
private bool _fanTurnedOnByUs;
|
private bool _fanTurnedOnByUs;
|
||||||
private DateTimeOffset? _showerEndedAt;
|
private DateTimeOffset? _showerEndedAt;
|
||||||
@@ -55,10 +55,8 @@ public sealed class ExhaustFanControlService(
|
|||||||
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
|
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
|
||||||
|
|
||||||
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
|
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
|
||||||
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
|
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
_fanTurnedOnByUs = false;
|
_fanTurnedOnByUs = false;
|
||||||
_showerEndedAt = null;
|
_showerEndedAt = null;
|
||||||
@@ -67,16 +65,10 @@ public sealed class ExhaustFanControlService(
|
|||||||
|
|
||||||
private void TurnOnFanIfNeeded()
|
private void TurnOnFanIfNeeded()
|
||||||
{
|
{
|
||||||
if (_fanTurnedOnByUs)
|
if (_fanTurnedOnByUs) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
|
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
|
||||||
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
|
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
|
haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
|
||||||
_fanTurnedOnByUs = true;
|
_fanTurnedOnByUs = true;
|
||||||
@@ -84,18 +76,12 @@ public sealed class ExhaustFanControlService(
|
|||||||
|
|
||||||
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp)
|
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp)
|
||||||
{
|
{
|
||||||
if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue)
|
if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var elapsed = timestamp - _showerEndedAt.Value;
|
var elapsed = timestamp - _showerEndedAt.Value;
|
||||||
var runAfterDuration = TimeSpan.FromMinutes(_options.FanRunAfterShowerMinutes);
|
var runAfterDuration = TimeSpan.FromMinutes(_options.FanRunAfterShowerMinutes);
|
||||||
|
|
||||||
if (elapsed < runAfterDuration)
|
if (elapsed < runAfterDuration) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
|
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
|
||||||
_fanTurnedOnByUs = false;
|
_fanTurnedOnByUs = false;
|
||||||
|
|||||||
@@ -10,7 +10,13 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
|
|||||||
|
|
||||||
public double? PreviousReading
|
public double? PreviousReading
|
||||||
{
|
{
|
||||||
get { lock (_lock) { return _previousReading; } }
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _previousReading;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RecordReading(double humidity, DateTimeOffset timestamp)
|
public void RecordReading(double humidity, DateTimeOffset timestamp)
|
||||||
@@ -20,10 +26,7 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
|
|||||||
_readings.Enqueue((humidity, timestamp));
|
_readings.Enqueue((humidity, timestamp));
|
||||||
_previousReading = humidity;
|
_previousReading = humidity;
|
||||||
|
|
||||||
while (_readings.Count > windowSize)
|
while (_readings.Count > windowSize) _readings.Dequeue();
|
||||||
{
|
|
||||||
_readings.Dequeue();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,19 +34,13 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
|
|||||||
{
|
{
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
if (_readings.Count < 2)
|
if (_readings.Count < 2) return 0.0;
|
||||||
{
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
var oldest = _readings.Peek();
|
var oldest = _readings.Peek();
|
||||||
var newest = _readings.Last();
|
var newest = _readings.Last();
|
||||||
var elapsedMinutes = (newest.Timestamp - oldest.Timestamp).TotalMinutes;
|
var elapsedMinutes = (newest.Timestamp - oldest.Timestamp).TotalMinutes;
|
||||||
|
|
||||||
if (elapsedMinutes <= 0)
|
if (elapsedMinutes <= 0) return 0.0;
|
||||||
{
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (newest.Humidity - oldest.Humidity) / elapsedMinutes;
|
return (newest.Humidity - oldest.Humidity) / elapsedMinutes;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ namespace ShowerMonitorManager.Interface;
|
|||||||
|
|
||||||
public interface IHumidityRateCalculator
|
public interface IHumidityRateCalculator
|
||||||
{
|
{
|
||||||
|
double? PreviousReading { get; }
|
||||||
void RecordReading(double humidity, DateTimeOffset timestamp);
|
void RecordReading(double humidity, DateTimeOffset timestamp);
|
||||||
double GetRatePerMinute();
|
double GetRatePerMinute();
|
||||||
void Reset();
|
void Reset();
|
||||||
double? PreviousReading { get; }
|
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,10 @@ public sealed class ShowerMonitorOptions
|
|||||||
public double MinDifferentialHumidity { get; init; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity;
|
public double MinDifferentialHumidity { get; init; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity;
|
||||||
public double PeakHumidityThreshold { get; init; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold;
|
public double PeakHumidityThreshold { get; init; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold;
|
||||||
public int ConfirmationWindowMinutes { get; init; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes;
|
public int ConfirmationWindowMinutes { get; init; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes;
|
||||||
public double RecoveryDifferentialThreshold { get; init; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold;
|
|
||||||
|
public double RecoveryDifferentialThreshold { get; init; } =
|
||||||
|
ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold;
|
||||||
|
|
||||||
public int MaxShowerDurationMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes;
|
public int MaxShowerDurationMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes;
|
||||||
public int FanRunAfterShowerMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes;
|
public int FanRunAfterShowerMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes;
|
||||||
public int RateWindowSize { get; init; } = ShowerMonitorConsts.DefaultRateWindowSize;
|
public int RateWindowSize { get; init; } = ShowerMonitorConsts.DefaultRateWindowSize;
|
||||||
|
|||||||
@@ -11,39 +11,69 @@ public sealed class ShowerDetectionService(
|
|||||||
IOptions<ShowerMonitorOptions> options)
|
IOptions<ShowerMonitorOptions> options)
|
||||||
: IShowerDetectionService
|
: IShowerDetectionService
|
||||||
{
|
{
|
||||||
private readonly ShowerMonitorOptions _options = options.Value;
|
|
||||||
private readonly Lock _lock = new();
|
private readonly Lock _lock = new();
|
||||||
|
private readonly ShowerMonitorOptions _options = options.Value;
|
||||||
|
private ShowerSession? _currentSession;
|
||||||
|
|
||||||
private ShowerState _currentState = ShowerState.Idle;
|
private ShowerState _currentState = ShowerState.Idle;
|
||||||
private ShowerSession? _currentSession;
|
|
||||||
private ShowerSession? _lastCompletedSession;
|
private ShowerSession? _lastCompletedSession;
|
||||||
private int _todaySessionCount;
|
|
||||||
private DateTimeOffset? _suspectedSince;
|
|
||||||
private double _lastRate;
|
private double _lastRate;
|
||||||
|
private DateTimeOffset? _suspectedSince;
|
||||||
|
private int _todaySessionCount;
|
||||||
|
|
||||||
public ShowerState CurrentState
|
public ShowerState CurrentState
|
||||||
{
|
{
|
||||||
get { lock (_lock) { return _currentState; } }
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _currentState;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public ShowerSession? CurrentSession
|
public ShowerSession? CurrentSession
|
||||||
{
|
{
|
||||||
get { lock (_lock) { return _currentSession; } }
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _currentSession;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public ShowerSession? LastCompletedSession
|
public ShowerSession? LastCompletedSession
|
||||||
{
|
{
|
||||||
get { lock (_lock) { return _lastCompletedSession; } }
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _lastCompletedSession;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public int TodaySessionCount
|
public int TodaySessionCount
|
||||||
{
|
{
|
||||||
get { lock (_lock) { return _todaySessionCount; } }
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _todaySessionCount;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public double LastRate
|
public double LastRate
|
||||||
{
|
{
|
||||||
get { lock (_lock) { return _lastRate; } }
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _lastRate;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp)
|
public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp)
|
||||||
@@ -83,10 +113,7 @@ public sealed class ShowerDetectionService(
|
|||||||
var showerSuspected = rate >= _options.SpikeRateThreshold
|
var showerSuspected = rate >= _options.SpikeRateThreshold
|
||||||
&& differential >= _options.MinDifferentialHumidity;
|
&& differential >= _options.MinDifferentialHumidity;
|
||||||
|
|
||||||
if (!showerSuspected)
|
if (!showerSuspected) return ShowerState.Idle;
|
||||||
{
|
|
||||||
return ShowerState.Idle;
|
|
||||||
}
|
|
||||||
|
|
||||||
_suspectedSince = timestamp;
|
_suspectedSince = timestamp;
|
||||||
_currentSession = new ShowerSession
|
_currentSession = new ShowerSession
|
||||||
@@ -113,15 +140,10 @@ public sealed class ShowerDetectionService(
|
|||||||
if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow
|
if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow
|
||||||
&& humidity >= _options.PeakHumidityThreshold
|
&& humidity >= _options.PeakHumidityThreshold
|
||||||
&& differential >= _options.MinDifferentialHumidity)
|
&& differential >= _options.MinDifferentialHumidity)
|
||||||
{
|
|
||||||
return ShowerState.Active;
|
return ShowerState.Active;
|
||||||
}
|
|
||||||
|
|
||||||
var showerAbandoned = rate < 0 && differential < _options.MinDifferentialHumidity;
|
var showerAbandoned = rate < 0 && differential < _options.MinDifferentialHumidity;
|
||||||
if (!showerAbandoned)
|
if (!showerAbandoned) return ShowerState.Suspected;
|
||||||
{
|
|
||||||
return ShowerState.Suspected;
|
|
||||||
}
|
|
||||||
|
|
||||||
CompleteSessionCleanup();
|
CompleteSessionCleanup();
|
||||||
|
|
||||||
@@ -141,10 +163,7 @@ public sealed class ShowerDetectionService(
|
|||||||
&& _currentSession.GetDuration(timestamp) >= maxDuration;
|
&& _currentSession.GetDuration(timestamp) >= maxDuration;
|
||||||
var humidityRecovered = rate < 0 && differential < _options.MinDifferentialHumidity;
|
var humidityRecovered = rate < 0 && differential < _options.MinDifferentialHumidity;
|
||||||
|
|
||||||
if (maxDurationReached || humidityRecovered)
|
if (maxDurationReached || humidityRecovered) return TransitionToDeclining();
|
||||||
{
|
|
||||||
return TransitionToDeclining();
|
|
||||||
}
|
|
||||||
|
|
||||||
return ShowerState.Active;
|
return ShowerState.Active;
|
||||||
}
|
}
|
||||||
@@ -162,10 +181,7 @@ public sealed class ShowerDetectionService(
|
|||||||
var maxDurationReached = _currentSession is not null
|
var maxDurationReached = _currentSession is not null
|
||||||
&& _currentSession.GetDuration(timestamp) >= maxDuration;
|
&& _currentSession.GetDuration(timestamp) >= maxDuration;
|
||||||
|
|
||||||
if (!maxDurationReached)
|
if (!maxDurationReached) return ShowerState.Declining;
|
||||||
{
|
|
||||||
return ShowerState.Declining;
|
|
||||||
}
|
|
||||||
|
|
||||||
CompleteSession(timestamp);
|
CompleteSession(timestamp);
|
||||||
|
|
||||||
@@ -186,10 +202,7 @@ public sealed class ShowerDetectionService(
|
|||||||
|
|
||||||
private void CompleteSession(DateTimeOffset endTime)
|
private void CompleteSession(DateTimeOffset endTime)
|
||||||
{
|
{
|
||||||
if (_currentSession is null)
|
if (_currentSession is null) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_currentSession.EndTime = endTime;
|
_currentSession.EndTime = endTime;
|
||||||
_lastCompletedSession = _currentSession;
|
_lastCompletedSession = _currentSession;
|
||||||
|
|||||||
@@ -25,14 +25,6 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
CleanupButtonEntityId
|
CleanupButtonEntityId
|
||||||
];
|
];
|
||||||
|
|
||||||
private static object CreateDeviceBlock() => new
|
|
||||||
{
|
|
||||||
identifiers = new[] { DeviceIdentifier },
|
|
||||||
name = DeviceName,
|
|
||||||
model = DeviceName,
|
|
||||||
manufacturer = DeviceManufacturer
|
|
||||||
};
|
|
||||||
|
|
||||||
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -91,6 +83,17 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static object CreateDeviceBlock()
|
||||||
|
{
|
||||||
|
return new
|
||||||
|
{
|
||||||
|
identifiers = new[] { DeviceIdentifier },
|
||||||
|
name = DeviceName,
|
||||||
|
model = DeviceName,
|
||||||
|
manufacturer = DeviceManufacturer
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static ICollection<ShowerMonitorEntity> GetAllEntities()
|
private static ICollection<ShowerMonitorEntity> GetAllEntities()
|
||||||
{
|
{
|
||||||
var device = CreateDeviceBlock();
|
var device = CreateDeviceBlock();
|
||||||
@@ -107,7 +110,8 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
},
|
},
|
||||||
new ShowerMonitorEntity("sensor", "showermonitor_differential_humidity", "Bathroom differential humidity")
|
new ShowerMonitorEntity("sensor", "showermonitor_differential_humidity", "Bathroom differential humidity")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device }
|
||||||
},
|
},
|
||||||
new ShowerMonitorEntity("sensor", "showermonitor_humidity_rate", "Humidity rate of change")
|
new ShowerMonitorEntity("sensor", "showermonitor_humidity_rate", "Humidity rate of change")
|
||||||
{
|
{
|
||||||
@@ -119,7 +123,8 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
},
|
},
|
||||||
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_duration", "Last shower duration")
|
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_duration", "Last shower duration")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
||||||
},
|
},
|
||||||
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_time", "Last shower time")
|
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_time", "Last shower time")
|
||||||
{
|
{
|
||||||
@@ -134,7 +139,8 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateDifferentialAsync(double differential, string timestamp)
|
private async Task UpdateDifferentialAsync(double differential, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(DifferentialEntityId, Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(DifferentialEntityId,
|
||||||
|
Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(DifferentialEntityId, new
|
await SetEntityAttributesSafe(DifferentialEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = "%",
|
unit_of_measurement = "%",
|
||||||
@@ -145,7 +151,8 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateHumidityRateAsync(double rate, string timestamp)
|
private async Task UpdateHumidityRateAsync(double rate, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(HumidityRateEntityId, new
|
await SetEntityAttributesSafe(HumidityRateEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = "%/min",
|
unit_of_measurement = "%/min",
|
||||||
@@ -156,7 +163,8 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateTodaySessionCountAsync(int count, string timestamp)
|
private async Task UpdateTodaySessionCountAsync(int count, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(TodaySessionCountEntityId, new
|
await SetEntityAttributesSafe(TodaySessionCountEntityId, new
|
||||||
{
|
{
|
||||||
friendly_name = "Showers today",
|
friendly_name = "Showers today",
|
||||||
@@ -166,13 +174,11 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp)
|
private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp)
|
||||||
{
|
{
|
||||||
if (session is null)
|
if (session is null) return;
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var durationSeconds = (int)session.Duration.TotalSeconds;
|
var durationSeconds = (int)session.Duration.TotalSeconds;
|
||||||
await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(LastShowerDurationEntityId, new
|
await SetEntityAttributesSafe(LastShowerDurationEntityId, new
|
||||||
{
|
{
|
||||||
formatted = FormatDuration(session.Duration),
|
formatted = FormatDuration(session.Duration),
|
||||||
@@ -181,7 +187,8 @@ public sealed class ShowerMonitorEntityService(
|
|||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityStateSafe(LastShowerTimeEntityId, session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(LastShowerTimeEntityId,
|
||||||
|
session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(LastShowerTimeEntityId, new
|
await SetEntityAttributesSafe(LastShowerTimeEntityId, new
|
||||||
{
|
{
|
||||||
friendly_name = "Last shower time",
|
friendly_name = "Last shower time",
|
||||||
|
|||||||
@@ -15,13 +15,13 @@ namespace ShowerMonitorManager;
|
|||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class ShowerMonitorInit
|
public sealed class ShowerMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<ShowerMonitorInit> _logger;
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly IScheduler _scheduler;
|
|
||||||
private readonly IShowerDetectionService _detectionService;
|
private readonly IShowerDetectionService _detectionService;
|
||||||
private readonly IExhaustFanControlService _fanControlService;
|
|
||||||
private readonly IShowerMonitorEntityService _entityService;
|
private readonly IShowerMonitorEntityService _entityService;
|
||||||
|
private readonly IExhaustFanControlService _fanControlService;
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<ShowerMonitorInit> _logger;
|
||||||
private readonly ShowerMonitorOptions _options;
|
private readonly ShowerMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
private readonly TimeProvider _timeProvider;
|
private readonly TimeProvider _timeProvider;
|
||||||
|
|
||||||
private volatile bool _cleanedUp;
|
private volatile bool _cleanedUp;
|
||||||
@@ -69,10 +69,7 @@ public sealed class ShowerMonitorInit
|
|||||||
{
|
{
|
||||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||||
|
|
||||||
if (_options.CleanupEntitiesOnStartup)
|
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync();
|
||||||
{
|
|
||||||
await _entityService.CleanupEntitiesAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
await _entityService.CreateEntitiesAsync();
|
await _entityService.CreateEntitiesAsync();
|
||||||
|
|
||||||
@@ -158,9 +155,8 @@ public sealed class ShowerMonitorInit
|
|||||||
if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue)
|
if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue)
|
||||||
{
|
{
|
||||||
if (_logger.IsEnabled(LogLevel.Debug))
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
_logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})",
|
||||||
_logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity);
|
bathroomHumidity, mainHomeHumidity);
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -183,11 +179,9 @@ public sealed class ShowerMonitorInit
|
|||||||
await _entityService.UpdateEntitiesAsync(context);
|
await _entityService.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
if (_logger.IsEnabled(LogLevel.Debug))
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
|
||||||
_logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}",
|
_logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}",
|
||||||
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state);
|
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error during ShowerMonitor poll");
|
_logger.LogError(ex, "Error during ShowerMonitor poll");
|
||||||
@@ -198,10 +192,7 @@ public sealed class ShowerMonitorInit
|
|||||||
{
|
{
|
||||||
var state = _haContext.GetState(entityId);
|
var state = _haContext.GetState(entityId);
|
||||||
|
|
||||||
if (state?.State is null or "unavailable" or "unknown")
|
if (state?.State is null or "unavailable" or "unknown") return null;
|
||||||
{
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,10 +14,7 @@ public static class ShowerMonitorServiceRegistration
|
|||||||
.GetSection(ShowerMonitorOptions.SectionName)
|
.GetSection(ShowerMonitorOptions.SectionName)
|
||||||
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
|
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled) return services;
|
||||||
{
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
services
|
services
|
||||||
.AddNetDaemonApp<ShowerMonitorInit>()
|
.AddNetDaemonApp<ShowerMonitorInit>()
|
||||||
|
|||||||
@@ -11,9 +11,6 @@ public static class ShowerMonitorConsts
|
|||||||
public const double DefaultRecoveryDifferentialThreshold = 5.0;
|
public const double DefaultRecoveryDifferentialThreshold = 5.0;
|
||||||
public const int DefaultRateWindowSize = 5;
|
public const int DefaultRateWindowSize = 5;
|
||||||
|
|
||||||
public static readonly TimeSpan DefaultMaxShowerDuration = TimeSpan.FromMinutes(60);
|
|
||||||
public static readonly TimeSpan DefaultFanRunAfterShower = TimeSpan.FromMinutes(10);
|
|
||||||
|
|
||||||
public const string BathroomHumidityEntityId = "sensor.bathroom_humidity";
|
public const string BathroomHumidityEntityId = "sensor.bathroom_humidity";
|
||||||
public const string MainHomeHumidityEntityId = "sensor.main_home_humidity";
|
public const string MainHomeHumidityEntityId = "sensor.main_home_humidity";
|
||||||
public const string BathroomTemperatureEntityId = "sensor.bathroom_temperature";
|
public const string BathroomTemperatureEntityId = "sensor.bathroom_temperature";
|
||||||
@@ -31,4 +28,7 @@ public static class ShowerMonitorConsts
|
|||||||
public const string DeviceIdentifier = "shower_monitor";
|
public const string DeviceIdentifier = "shower_monitor";
|
||||||
public const string DeviceName = "Shower Monitor";
|
public const string DeviceName = "Shower Monitor";
|
||||||
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
||||||
|
|
||||||
|
public static readonly TimeSpan DefaultMaxShowerDuration = TimeSpan.FromMinutes(60);
|
||||||
|
public static readonly TimeSpan DefaultFanRunAfterShower = TimeSpan.FromMinutes(10);
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,6 @@ namespace ShowerMonitor.Models;
|
|||||||
|
|
||||||
public class ShowerMonitorEntity : EntityCreateModel
|
public class ShowerMonitorEntity : EntityCreateModel
|
||||||
{
|
{
|
||||||
private string Domain { get; }
|
|
||||||
private string Identifier { get; }
|
|
||||||
private string Name { get; }
|
|
||||||
|
|
||||||
public ShowerMonitorEntity(string domain, string identifier, string name)
|
public ShowerMonitorEntity(string domain, string identifier, string name)
|
||||||
{
|
{
|
||||||
Domain = domain;
|
Domain = domain;
|
||||||
@@ -22,4 +18,8 @@ public class ShowerMonitorEntity : EntityCreateModel
|
|||||||
Name = Name
|
Name = Name
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string Domain { get; }
|
||||||
|
private string Identifier { get; }
|
||||||
|
private string Name { get; }
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user