Files
HomeAssistant/BatteryMonitor.Manager/BatterySensorDiscoveryService.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

108 lines
3.3 KiB
C#

using System.Globalization;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using BatteryMonitor.Models;
using BatteryMonitorManager.Interface;
namespace BatteryMonitorManager;
public sealed class BatterySensorDiscoveryService(
IHaContext haContext,
ILogger<BatterySensorDiscoveryService> logger) : IBatterySensorDiscoveryService
{
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
{
var allEntities = haContext.GetAllEntities();
var lowBatterySensors = allEntities
.Where(IsBatterySensor)
.Where(e => !IsExcludedDevice(e.EntityId))
.Select(e => TryCreateSensorInfo(e, thresholdPercent))
.Where(info => info is not null)
.ToList();
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Battery check: found {Count} sensors below {Threshold}%",
lowBatterySensors.Count, thresholdPercent);
}
return lowBatterySensors!;
}
internal static bool IsBatterySensor(Entity entity)
{
if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class");
return string.Equals(deviceClass, BatteryMonitorConsts.BatteryDeviceClass, StringComparison.OrdinalIgnoreCase);
}
internal static bool IsExcludedDevice(string entityId)
{
var lowerEntityId = entityId.ToLowerInvariant();
return BatteryMonitorConsts.ExcludedKeywords
.Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase));
}
private BatterySensorInfo? TryCreateSensorInfo(Entity entity, int thresholdPercent)
{
var state = entity.EntityState?.State;
if (state is null or "unavailable" or "unknown")
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null");
}
return null;
}
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state);
}
return null;
}
if (batteryLevel >= thresholdPercent)
{
return null;
}
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
?? entity.EntityId;
return new BatterySensorInfo
{
EntityId = entity.EntityId,
FriendlyName = friendlyName,
BatteryLevel = batteryLevel
};
}
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;
}
}