Files
HomeAssistant/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs
T
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00

112 lines
3.5 KiB
C#

#region
using System.Globalization;
using System.Text.Json;
using BatteryMonitor.Models;
using BatteryMonitorManager.Interface;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
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;
}
}