b0fd790ba6
Made-with: Cursor
136 lines
4.5 KiB
C#
136 lines
4.5 KiB
C#
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);
|
|
}
|
|
}
|