Files
HomeAssistant/PowerMonitor.Manager/PowerSensorDiscoveryService.cs
T
gitea_admin f0bbd4f10b Enable PowerMonitor limit enforcement and prune unused boiler/replay code
PowerMonitor now ships enabled with power-limit enforcement settings: watt limit, recovery and cooldown windows, and switch-off plus pause/restore entity lists.

Remove the unused BoilerRunTimeTracker, its DI registration and tests, the StatusCleanedUp constant, and the boiler replay runner; simplify BoilerConfigReader, control-service logging and entity parsing. Switch CostAccumulator to System.Threading.Lock, update the Shower exhaust fan service and tests, drop the legacy HistoryReplay/McpServer sources and reporting tooling, and expand AGENTS.md with the current project wiring and DI notes.
2026-11-29 13:58:08 +02:00

135 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));
}
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);
}
}