using System.Text; using Microsoft.Extensions.Logging; using NetDaemon.HassModel; using BatteryMonitor.Models; using BatteryMonitorManager.Interface; namespace BatteryMonitorManager; public sealed class BatteryNotificationService : IBatteryNotificationService { private readonly IHaContext _haContext; private readonly ILogger _logger; public BatteryNotificationService( IHaContext haContext, ILogger logger) { _haContext = haContext; _logger = logger; } 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 }); _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(); } }