feat: add PowerSensorDiscoveryService with auto-discovery and exclusion patterns
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,242 @@
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock;
|
||||
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock;
|
||||
|
||||
public PowerSensorDiscoveryServiceTests()
|
||||
{
|
||||
_haContextMock = new Mock<IHaContext>();
|
||||
_loggerMock = new Mock<ILogger<PowerSensorDiscoveryService>>();
|
||||
}
|
||||
|
||||
private PowerSensorDiscoveryService CreateSut(
|
||||
string mainMeterEntityId = "sensor.p1_meter_power",
|
||||
string[]? excludedPatterns = null)
|
||||
{
|
||||
var options = Options.Create(new PowerMonitorOptions
|
||||
{
|
||||
MainMeterEntityId = mainMeterEntityId,
|
||||
ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"]
|
||||
});
|
||||
return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object);
|
||||
}
|
||||
|
||||
private void SetupEntities(params (string entityId, string? deviceClass, string? unit, string? friendlyName)[] entities)
|
||||
{
|
||||
var entityList = new List<Entity>();
|
||||
|
||||
foreach (var (entityId, deviceClass, unit, friendlyName) in entities)
|
||||
{
|
||||
var attributes = new Dictionary<string, object?>();
|
||||
if (deviceClass is not null) attributes["device_class"] = deviceClass;
|
||||
if (unit is not null) attributes["unit_of_measurement"] = unit;
|
||||
if (friendlyName is not null) attributes["friendly_name"] = friendlyName;
|
||||
|
||||
var attributesJson = JsonSerializer.SerializeToElement(attributes);
|
||||
var entityState = new EntityState { AttributesJson = attributesJson };
|
||||
|
||||
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||
|
||||
var entity = new Entity(_haContextMock.Object, entityId);
|
||||
entityList.Add(entity);
|
||||
}
|
||||
|
||||
_haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
|
||||
}
|
||||
|
||||
#region Discovery
|
||||
|
||||
[Fact]
|
||||
public void DiscoverDeviceSensors_ShouldFindPowerSensors()
|
||||
{
|
||||
SetupEntities(
|
||||
("sensor.p1_meter_power", "power", "W", "P1 Meter"),
|
||||
("sensor.sonoff_power", "power", "W", "Sonoff Power"),
|
||||
("sensor.zigbee_power", "power", "W", "Zigbee Power"),
|
||||
("sensor.temperature", "temperature", "°C", "Temperature")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverDeviceSensors();
|
||||
|
||||
result.Should().HaveCount(2);
|
||||
result.Should().Contain(s => s.EntityId == "sensor.sonoff_power");
|
||||
result.Should().Contain(s => s.EntityId == "sensor.zigbee_power");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoverDeviceSensors_ShouldExcludeMainMeter()
|
||||
{
|
||||
SetupEntities(
|
||||
("sensor.p1_meter_power", "power", "W", "P1 Meter"),
|
||||
("sensor.device_power", "power", "W", "Device")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverDeviceSensors();
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result.Should().NotContain(s => s.EntityId == "sensor.p1_meter_power");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoverDeviceSensors_ShouldApplyExclusionPatterns()
|
||||
{
|
||||
SetupEntities(
|
||||
("sensor.p1_meter_power", "power", "W", "P1"),
|
||||
("sensor.device_power", "power", "W", "Device"),
|
||||
("sensor.nordpool_some_power", "power", "W", "NordPool"),
|
||||
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverDeviceSensors();
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result.Should().Contain(s => s.EntityId == "sensor.device_power");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoverDeviceSensors_ShouldHandleKilowattUnit()
|
||||
{
|
||||
SetupEntities(
|
||||
("sensor.p1_meter_power", "power", "W", "P1"),
|
||||
("sensor.device_kw", "power", "kW", "Device kW")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverDeviceSensors();
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result.First().UnitOfMeasurement.Should().Be("kW");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoverDeviceSensors_WhenNoPowerSensors_ShouldReturnEmpty()
|
||||
{
|
||||
SetupEntities(
|
||||
("sensor.temperature", "temperature", "°C", "Temp"),
|
||||
("switch.some_switch", null, null, "Switch")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = sut.DiscoverDeviceSensors();
|
||||
|
||||
result.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoverDeviceSensors_ShouldUpdateCurrentDeviceSensors()
|
||||
{
|
||||
SetupEntities(
|
||||
("sensor.p1_meter_power", "power", "W", "P1"),
|
||||
("sensor.device_power", "power", "W", "Device")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.CurrentDeviceSensors.Should().BeEmpty();
|
||||
|
||||
sut.DiscoverDeviceSensors();
|
||||
|
||||
sut.CurrentDeviceSensors.Should().HaveCount(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscoverDeviceSensors_ReDiscovery_ShouldReplacePreviousList()
|
||||
{
|
||||
SetupEntities(
|
||||
("sensor.p1_meter_power", "power", "W", "P1"),
|
||||
("sensor.device_a_power", "power", "W", "Device A")
|
||||
);
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.DiscoverDeviceSensors();
|
||||
sut.CurrentDeviceSensors.Should().HaveCount(1);
|
||||
|
||||
SetupEntities(
|
||||
("sensor.p1_meter_power", "power", "W", "P1"),
|
||||
("sensor.device_a_power", "power", "W", "Device A"),
|
||||
("sensor.device_b_power", "power", "W", "Device B")
|
||||
);
|
||||
|
||||
sut.DiscoverDeviceSensors();
|
||||
sut.CurrentDeviceSensors.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ExtractDeviceName
|
||||
|
||||
[Theory]
|
||||
[InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")]
|
||||
[InlineData("sensor.zigbee_device_power", "zigbee_device")]
|
||||
[InlineData("sensor.some_sensor", "some_sensor")]
|
||||
[InlineData("sensor.power", "power")]
|
||||
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.device_power", false)]
|
||||
[InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)]
|
||||
[InlineData("*_power", "sensor.sonoff_power", 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
|
||||
|
||||
[Fact]
|
||||
public void IsPowerSensor_WithPowerDeviceClassAndWattUnit_ShouldReturnTrue()
|
||||
{
|
||||
SetupEntities(("sensor.test_power", "power", "W", "Test"));
|
||||
var entity = new Entity(_haContextMock.Object, "sensor.test_power");
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.IsPowerSensor(entity).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsPowerSensor_WithNonSensorDomain_ShouldReturnFalse()
|
||||
{
|
||||
SetupEntities(("switch.test_power", "power", "W", "Test"));
|
||||
var entity = new Entity(_haContextMock.Object, "switch.test_power");
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.IsPowerSensor(entity).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsPowerSensor_WithTemperatureDeviceClass_ShouldReturnFalse()
|
||||
{
|
||||
SetupEntities(("sensor.test_temp", "temperature", "°C", "Test"));
|
||||
var entity = new Entity(_haContextMock.Object, "sensor.test_temp");
|
||||
|
||||
var sut = CreateSut();
|
||||
sut.IsPowerSensor(entity).Should().BeFalse();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using PowerMonitor.Models;
|
||||
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerSensorDiscoveryService
|
||||
{
|
||||
IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors();
|
||||
IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors { get; }
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.2" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
{
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly PowerMonitorOptions _options;
|
||||
private readonly ILogger<PowerSensorDiscoveryService> _logger;
|
||||
private readonly Regex[] _exclusionPatterns;
|
||||
|
||||
private volatile IReadOnlyList<PowerSensorInfo> _currentDeviceSensors = [];
|
||||
|
||||
public IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors => _currentDeviceSensors;
|
||||
|
||||
public PowerSensorDiscoveryService(
|
||||
IHaContext haContext,
|
||||
IOptions<PowerMonitorOptions> options,
|
||||
ILogger<PowerSensorDiscoveryService> logger)
|
||||
{
|
||||
_haContext = haContext;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_exclusionPatterns = _options.ExcludedSensorPatterns
|
||||
.Select(GlobToRegex)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
public IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors()
|
||||
{
|
||||
var allEntities = _haContext.GetAllEntities();
|
||||
|
||||
var powerSensors = allEntities
|
||||
.Where(IsPowerSensor)
|
||||
.Where(e => !IsMainMeter(e.EntityId))
|
||||
.Where(e => !IsExcluded(e.EntityId))
|
||||
.Select(e => new PowerSensorInfo
|
||||
{
|
||||
EntityId = e.EntityId,
|
||||
FriendlyName = GetFriendlyName(e),
|
||||
DeviceName = ExtractDeviceName(e.EntityId),
|
||||
UnitOfMeasurement = GetUnitOfMeasurement(e)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
_currentDeviceSensors = powerSensors;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
||||
|
||||
return powerSensors;
|
||||
}
|
||||
|
||||
internal bool IsPowerSensor(Entity entity)
|
||||
{
|
||||
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var attributes = entity.EntityState?.AttributesJson;
|
||||
if (attributes is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var deviceClass = GetJsonStringProperty(attributes.Value, "device_class");
|
||||
var unit = GetJsonStringProperty(attributes.Value, "unit_of_measurement");
|
||||
|
||||
return string.Equals(deviceClass, PowerMonitorConsts.PowerDeviceClass, StringComparison.OrdinalIgnoreCase) &&
|
||||
(string.Equals(unit, PowerMonitorConsts.WattUnit, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(unit, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
internal bool IsMainMeter(string entityId)
|
||||
{
|
||||
return string.Equals(entityId, _options.MainMeterEntityId, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
internal bool IsExcluded(string entityId)
|
||||
{
|
||||
return _exclusionPatterns.Any(pattern => pattern.IsMatch(entityId));
|
||||
}
|
||||
|
||||
internal static string ExtractDeviceName(string entityId)
|
||||
{
|
||||
var withoutDomain = entityId.Contains('.')
|
||||
? entityId[(entityId.IndexOf('.') + 1)..]
|
||||
: entityId;
|
||||
|
||||
return withoutDomain.EndsWith("_power", StringComparison.OrdinalIgnoreCase)
|
||||
? withoutDomain[..^"_power".Length]
|
||||
: withoutDomain;
|
||||
}
|
||||
|
||||
private static string GetFriendlyName(Entity entity)
|
||||
{
|
||||
var name = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name");
|
||||
return name ?? entity.EntityId;
|
||||
}
|
||||
|
||||
private static string GetUnitOfMeasurement(Entity entity)
|
||||
{
|
||||
var unit = GetJsonStringProperty(entity.EntityState?.AttributesJson, "unit_of_measurement");
|
||||
return unit ?? PowerMonitorConsts.WattUnit;
|
||||
}
|
||||
|
||||
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||
{
|
||||
if (element is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return element.Value.TryGetProperty(propertyName, out var value)
|
||||
? value.GetString()
|
||||
: null;
|
||||
}
|
||||
|
||||
internal static Regex GlobToRegex(string globPattern)
|
||||
{
|
||||
var regexPattern = "^" + Regex.Escape(globPattern).Replace("\\*", ".*") + "$";
|
||||
return new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user