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 Regex[] _exclusionPatterns; private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly PowerMonitorOptions _options; private volatile IReadOnlyList _currentDeviceSensors = []; public PowerSensorDiscoveryService( IHaContext haContext, IOptions options, ILogger logger) { _haContext = haContext; _options = options.Value; _logger = logger; _exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)]; } public IReadOnlyList CurrentDeviceSensors => _currentDeviceSensors; public IReadOnlyList 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; if (_logger.IsEnabled(LogLevel.Information)) _logger.LogInformation( "Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); return powerSensors; } internal static 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)); } private bool IsMainMeter(string entityId) { return string.Equals(entityId, _options.MainMeterEntityId, StringComparison.OrdinalIgnoreCase); } private 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); } }