Files
HomeAssistant/PowerMonitor.Manager/PowerSensorDiscoveryService.cs
T
gitea_admin 77458383d1 Add braces to single-statement guards and refactor NordPool price fetching
- Expand inline guard, return and logger blocks across the monitor services, init classes and tests
- Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton
- Record the NordPool and boiler service lifetimes in AGENTS.md
- Drop the unused persisted-state argument from the boiler test data helper
2026-12-01 11:59:31 +02:00

127 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 Regex[] _exclusionPatterns;
private readonly IHaContext _haContext;
private readonly ILogger<PowerSensorDiscoveryService> _logger;
private readonly PowerMonitorOptions _options;
private volatile IReadOnlyList<PowerSensorInfo> _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> CurrentDeviceSensors => _currentDeviceSensors;
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);
}
}