using System.Text; using Microsoft.Extensions.Logging; using NetDaemon.HassModel; using BatteryMonitor.Models; using BatteryMonitorManager.Interface; namespace BatteryMonitorManager; public sealed class BatteryNotificationService( IHaContext haContext, ILogger logger) : IBatteryNotificationService { public void NotifyLowBattery(IReadOnlyList lowBatteryDevices) { if (lowBatteryDevices.Count == 0) { return; } var message = BuildNotificationMessage(lowBatteryDevices); haContext.CallService( BatteryMonitorConsts.PersistentNotificationDomain, BatteryMonitorConsts.PersistentNotificationCreateService, data: new { title = BatteryMonitorConsts.NotificationTitle, message, notification_id = BatteryMonitorConsts.NotificationId }); if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation( "Sent low battery notification for {Count} device(s)", lowBatteryDevices.Count); } } public void DismissNotification() { haContext.CallService( BatteryMonitorConsts.PersistentNotificationDomain, BatteryMonitorConsts.PersistentNotificationDismissService, data: new { notification_id = BatteryMonitorConsts.NotificationId }); logger.LogDebug("Dismissed low battery notification"); } internal static string BuildNotificationMessage(IReadOnlyList devices) { var sb = new StringBuilder(); sb.AppendLine("The following devices have low battery:"); sb.AppendLine(); foreach (var device in devices.OrderBy(d => d.BatteryLevel)) { sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%"); } return sb.ToString().TrimEnd(); } }