Files
HomeAssistant/PowerMonitor.Manager/PowerSensorDiscoveryService.cs
T
gitea_admin 41ac93733e Clear Qodana findings in monitor runtime code
- Guard logger calls with IsEnabled so value-type arguments are not boxed
  when the level is disabled
- Make helper members static, narrow write-only properties to init or
  private get, and delete members no call site reaches
- Flatten nested conditionals and convert if/else chains into switch and
  ternary form
- Drop the unused *MonitorInit interfaces; NetDaemon instantiates the
  concrete app classes
- Drop the unused IConfiguration parameter from AddNordPool and
  AddPowerMonitor, and the unused IEntityManager.CreateEntitiesAsync
- Remove the ignored parameters of the boiler run-time tracker stub
- Pin the NordPool DTO price mapping explicitly so the getter use is
  visible to static analysis
- Fail Qodana on any finding and record the registration changes in
  AGENTS.md
2026-11-29 21:42:47 +02:00

136 lines
4.6 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)];
}
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;
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);
}
}