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

103 lines
3.3 KiB
C#

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