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 : IBatterySensorDiscoveryService { private readonly IHaContext _haContext; private readonly ILogger _logger; public BatterySensorDiscoveryService( IHaContext haContext, ILogger logger) { _haContext = haContext; _logger = logger; } 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(); _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") { _logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null"); return null; } if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel)) { _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 }; } internal static string? GetJsonStringProperty(JsonElement? element, string propertyName) { if (element is null) { return null; } return element.Value.TryGetProperty(propertyName, out var value) ? value.GetString() : null; } }