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 logger) : IBatterySensorDiscoveryService { public IReadOnlyList 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; } }