feat: add BatteryMonitor implementation with discovery, notification, and scheduling services
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>BatteryMonitorManager</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>BatteryMonitor.Manager.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Reactive.Concurrency;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NetDaemon.AppModel;
|
||||
using NetDaemon.Extensions.Scheduler;
|
||||
using BatteryMonitorManager.Interface;
|
||||
using BatteryMonitorManager.Models;
|
||||
|
||||
namespace BatteryMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
||||
{
|
||||
private readonly ILogger<BatteryMonitorInit> _logger;
|
||||
private readonly IScheduler _scheduler;
|
||||
private readonly IBatterySensorDiscoveryService _discoveryService;
|
||||
private readonly IBatteryNotificationService _notificationService;
|
||||
private readonly BatteryMonitorOptions _options;
|
||||
|
||||
public BatteryMonitorInit(
|
||||
ILogger<BatteryMonitorInit> logger,
|
||||
IScheduler scheduler,
|
||||
IBatterySensorDiscoveryService discoveryService,
|
||||
IBatteryNotificationService notificationService,
|
||||
IOptions<BatteryMonitorOptions> options)
|
||||
{
|
||||
_logger = logger;
|
||||
_scheduler = scheduler;
|
||||
_discoveryService = discoveryService;
|
||||
_notificationService = notificationService;
|
||||
_options = options.Value;
|
||||
|
||||
_ = InitializeAndScheduleAsync();
|
||||
}
|
||||
|
||||
private async Task InitializeAndScheduleAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await InitializeAsync();
|
||||
ScheduleDailyCheck();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during BatteryMonitor initialization and scheduling");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
CheckAndNotify();
|
||||
|
||||
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing BatteryMonitor");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void ScheduleDailyCheck()
|
||||
{
|
||||
_scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Running scheduled daily battery check");
|
||||
CheckAndNotify();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during scheduled battery check");
|
||||
}
|
||||
});
|
||||
|
||||
_logger.LogInformation("Scheduled daily battery check at 08:00");
|
||||
}
|
||||
|
||||
internal void CheckAndNotify()
|
||||
{
|
||||
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
|
||||
|
||||
if (lowBatteryDevices.Count > 0)
|
||||
{
|
||||
_notificationService.NotifyLowBattery(lowBatteryDevices);
|
||||
}
|
||||
else
|
||||
{
|
||||
_notificationService.DismissNotification();
|
||||
_logger.LogDebug("No low battery devices found");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
using BatteryMonitorManager.Interface;
|
||||
using BatteryMonitorManager.Models;
|
||||
|
||||
namespace BatteryMonitorManager;
|
||||
|
||||
public static class BatteryMonitorServiceRegistration
|
||||
{
|
||||
public static IServiceCollection AddBatteryMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var options = configuration
|
||||
.GetSection(BatteryMonitorOptions.SectionName)
|
||||
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
|
||||
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
}
|
||||
|
||||
services
|
||||
.AddNetDaemonApp<BatteryMonitorInit>()
|
||||
.AddScoped<IBatterySensorDiscoveryService, BatterySensorDiscoveryService>()
|
||||
.AddScoped<IBatteryNotificationService, BatteryNotificationService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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<BatteryNotificationService> _logger;
|
||||
|
||||
public BatteryNotificationService(
|
||||
IHaContext haContext,
|
||||
ILogger<BatteryNotificationService> logger)
|
||||
{
|
||||
_haContext = haContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> 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<BatterySensorInfo> 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
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<BatterySensorDiscoveryService> _logger;
|
||||
|
||||
public BatterySensorDiscoveryService(
|
||||
IHaContext haContext,
|
||||
ILogger<BatterySensorDiscoveryService> logger)
|
||||
{
|
||||
_haContext = haContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
_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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace BatteryMonitorManager.Interface;
|
||||
|
||||
public interface IBatteryMonitorInit
|
||||
{
|
||||
Task InitializeAsync();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using BatteryMonitor.Models;
|
||||
|
||||
namespace BatteryMonitorManager.Interface;
|
||||
|
||||
public interface IBatteryNotificationService
|
||||
{
|
||||
void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices);
|
||||
|
||||
void DismissNotification();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using BatteryMonitor.Models;
|
||||
|
||||
namespace BatteryMonitorManager.Interface;
|
||||
|
||||
public interface IBatterySensorDiscoveryService
|
||||
{
|
||||
IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using BatteryMonitor.Models;
|
||||
|
||||
namespace BatteryMonitorManager.Models;
|
||||
|
||||
public sealed class BatteryMonitorOptions
|
||||
{
|
||||
public const string SectionName = "BatteryMonitor";
|
||||
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
public int BatteryThresholdPercent { get; set; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
|
||||
}
|
||||
Reference in New Issue
Block a user