diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj
index 56f1320..3691f73 100644
--- a/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj
+++ b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj
@@ -1,34 +1,34 @@
-
- net10.0
- enable
- enable
- false
-
+
+ net10.0
+ enable
+ enable
+ false
+
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs
index 94b6ecb..35f90f7 100644
--- a/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs
+++ b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs
@@ -8,150 +8,17 @@ using NetDaemon.HassModel.Entities;
namespace BatteryMonitor.Manager.Tests;
///
-/// Shared, deterministic builders and datasets used by the BatteryMonitor tests.
-/// Keeping entity/state construction and generated inputs here means the test
-/// classes only describe the scenario under test.
+/// Shared, deterministic builders and datasets used by the BatteryMonitor tests.
+/// Keeping entity/state construction and generated inputs here means the test
+/// classes only describe the scenario under test.
///
internal static class BatteryMonitorTestData
{
private const string DefaultFriendlyName = "Battery Device";
///
- /// Describes one entity exposed through .
- ///
- public sealed record EntitySpec
- {
- public required string EntityId { get; init; }
-
- public string? State { get; init; } = "50";
-
- public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
-
- public string? FriendlyName { get; init; } = DefaultFriendlyName;
-
- /// When false the context returns no for the entity.
- public bool HasState { get; init; } = true;
- }
-
- /// A battery device-class sensor.
- public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
- {
- return new EntitySpec
- {
- EntityId = entityId,
- State = state,
- FriendlyName = friendlyName
- };
- }
-
- /// A sensor with an arbitrary (or missing) device class.
- public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, string? friendlyName = DefaultFriendlyName)
- {
- return new EntitySpec
- {
- EntityId = entityId,
- DeviceClass = deviceClass,
- State = state,
- FriendlyName = friendlyName
- };
- }
-
- public static EntityState CreateEntityState(EntitySpec spec)
- {
- var attributes = new Dictionary(StringComparer.Ordinal);
-
- if (spec.DeviceClass is not null)
- {
- attributes["device_class"] = spec.DeviceClass;
- }
-
- if (spec.FriendlyName is not null)
- {
- attributes["friendly_name"] = spec.FriendlyName;
- }
-
- return new EntityState
- {
- State = spec.State,
- AttributesJson = JsonSerializer.SerializeToElement(attributes)
- };
- }
-
- ///
- /// Wires and
- /// on the mock, exposing the entities in declaration order.
- ///
- public static void ConfigureHaContext(Mock haContextMock, params EntitySpec[] entities)
- {
- var entityList = new List(entities.Length);
-
- foreach (var spec in entities)
- {
- if (spec.HasState)
- {
- haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
- }
-
- entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
- }
-
- haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
- }
-
- public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
- {
- return new BatterySensorInfo
- {
- EntityId = entityId,
- FriendlyName = friendlyName ?? entityId,
- BatteryLevel = batteryLevel
- };
- }
-
- public static List CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
- {
- return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
- }
-
- public static List CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
- {
- return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
- }
-
- ///
- /// Generates battery sensors with every integer level in 0..count-1.
- ///
- public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
- {
- return
- [
- .. Enumerable.Range(0, count)
- .Select(i => Battery(
- $"sensor.generated_battery_{i:D3}",
- i.ToString(CultureInfo.InvariantCulture),
- $"Generated Battery {i:D3}"))
- ];
- }
-
- ///
- /// Generates notification devices with deterministic, non-monotonic levels so
- /// ordering behaviour is exercised over more than a handful of rows.
- ///
- public static IReadOnlyList CreateGeneratedSensorInfos(int count)
- {
- return
- [
- .. Enumerable.Range(0, count)
- .Select(i => CreateSensorInfo(
- $"sensor.generated_{i:D3}",
- i * 37 % 101,
- $"Generated Device {i:D3}"))
- ];
- }
-
- ///
- /// (threshold, state, expected) rows straddling the strict level < threshold
- /// boundary, including zero/negative thresholds and int min/max thresholds.
+ /// (threshold, state, expected) rows straddling the strict level < threshold
+ /// boundary, including zero/negative thresholds and int min/max thresholds.
///
public static TheoryData ThresholdBoundaryRows { get; } = new()
{
@@ -183,8 +50,8 @@ internal static class BatteryMonitorTestData
};
///
- /// States that must never produce a , including
- /// whitespace/malformed strings and a null state.
+ /// States that must never produce a , including
+ /// whitespace/malformed strings and a null state.
///
public static TheoryData UnusableStateRows { get; } =
[
@@ -203,9 +70,121 @@ internal static class BatteryMonitorTestData
null
];
+ /// Device counts used to exercise notification payload generation.
+ public static TheoryData NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
+
+ /// A battery device-class sensor.
+ public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
+ {
+ return new EntitySpec
+ {
+ EntityId = entityId,
+ State = state,
+ FriendlyName = friendlyName
+ };
+ }
+
+ /// A sensor with an arbitrary (or missing) device class.
+ public static EntitySpec Sensor(string entityId, string? deviceClass, string? state,
+ string? friendlyName = DefaultFriendlyName)
+ {
+ return new EntitySpec
+ {
+ EntityId = entityId,
+ DeviceClass = deviceClass,
+ State = state,
+ FriendlyName = friendlyName
+ };
+ }
+
+ public static EntityState CreateEntityState(EntitySpec spec)
+ {
+ var attributes = new Dictionary(StringComparer.Ordinal);
+
+ if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass;
+
+ if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName;
+
+ return new EntityState
+ {
+ State = spec.State,
+ AttributesJson = JsonSerializer.SerializeToElement(attributes)
+ };
+ }
+
///
- /// Cross-product of every excluded keyword (lower and upper case) plus
- /// non-excluded look-alikes that must not be filtered.
+ /// Wires and
+ /// on the mock, exposing the entities in declaration order.
+ ///
+ public static void ConfigureHaContext(Mock haContextMock, params EntitySpec[] entities)
+ {
+ var entityList = new List(entities.Length);
+
+ foreach (var spec in entities)
+ {
+ if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
+
+ entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
+ }
+
+ haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
+ }
+
+ public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
+ {
+ return new BatterySensorInfo
+ {
+ EntityId = entityId,
+ FriendlyName = friendlyName ?? entityId,
+ BatteryLevel = batteryLevel
+ };
+ }
+
+ public static List CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
+ {
+ return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
+ }
+
+ public static List CreateSensorInfos(
+ params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
+ {
+ return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
+ }
+
+ ///
+ /// Generates battery sensors with every integer level in 0..count-1.
+ ///
+ public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
+ {
+ return
+ [
+ .. Enumerable.Range(0, count)
+ .Select(i => Battery(
+ $"sensor.generated_battery_{i:D3}",
+ i.ToString(CultureInfo.InvariantCulture),
+ $"Generated Battery {i:D3}"))
+ ];
+ }
+
+ ///
+ /// Generates notification devices with deterministic, non-monotonic levels so
+ /// ordering behaviour is exercised over more than a handful of rows.
+ ///
+ public static IReadOnlyList CreateGeneratedSensorInfos(int count)
+ {
+ return
+ [
+ .. Enumerable.Range(0, count)
+ .Select(i => CreateSensorInfo(
+ $"sensor.generated_{i:D3}",
+ i * 37 % 101,
+ $"Generated Device {i:D3}"))
+ ];
+ }
+
+ ///
+ /// Cross-product of every excluded keyword (lower and upper case) plus
+ /// non-excluded look-alikes that must not be filtered.
///
public static TheoryData ExcludedEntityIdRows()
{
@@ -229,6 +208,20 @@ internal static class BatteryMonitorTestData
return data;
}
- /// Device counts used to exercise notification payload generation.
- public static TheoryData NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
-}
+ ///
+ /// Describes one entity exposed through .
+ ///
+ public sealed record EntitySpec
+ {
+ public required string EntityId { get; init; }
+
+ public string? State { get; init; } = "50";
+
+ public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
+
+ public string? FriendlyName { get; init; } = DefaultFriendlyName;
+
+ /// When false the context returns no for the entity.
+ public bool HasState { get; init; } = true;
+ }
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs
index 62b7a23..a27aa94 100644
--- a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs
+++ b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs
@@ -1,11 +1,11 @@
using System.Text.Json;
+using BatteryMonitor.Models;
+using BatteryMonitorManager;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
-using BatteryMonitor.Models;
-using BatteryMonitorManager;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
namespace BatteryMonitor.Manager.Tests;
@@ -36,10 +36,10 @@ public class BatteryNotificationServiceTests
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
{
var devices = CreateSensorInfos(
- [
- .. Enumerable.Range(0, deviceCount)
- .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
- ]);
+ [
+ .. Enumerable.Range(0, deviceCount)
+ .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
+ ]);
var sut = CreateSut();
sut.NotifyLowBattery(devices);
@@ -139,10 +139,7 @@ public class BatteryNotificationServiceTests
{
var sut = CreateSut();
- for (var i = 0; i < calls; i++)
- {
- sut.DismissNotification();
- }
+ for (var i = 0; i < calls; i++) sut.DismissNotification();
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
@@ -222,7 +219,8 @@ public class BatteryNotificationServiceTests
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
[InlineData("", 5, "- ****: 5%")]
[InlineData(" ", 4, "- ** **: 4%")]
- public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel, string expectedLine)
+ public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel,
+ string expectedLine)
{
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
@@ -279,4 +277,4 @@ public class BatteryNotificationServiceTests
}
#endregion
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs
index f434127..7b76a42 100644
--- a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs
+++ b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs
@@ -1,11 +1,11 @@
using System.Globalization;
+using BatteryMonitor.Models;
+using BatteryMonitorManager;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
-using BatteryMonitor.Models;
-using BatteryMonitorManager;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
namespace BatteryMonitor.Manager.Tests;
@@ -25,6 +25,17 @@ public class BatterySensorDiscoveryServiceTests
ConfigureHaContext(_haContextMock, entities);
}
+ #region IsExcludedDevice
+
+ [Theory]
+ [MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
+ public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
+ {
+ BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
+ }
+
+ #endregion
+
#region Discovery
[Fact]
@@ -77,7 +88,8 @@ public class BatterySensorDiscoveryServiceTests
[InlineData("sensor.no_device_class", null)]
[InlineData("sensorx.bathroom_battery", "battery")]
[InlineData("switch.bathroom_battery", "battery")]
- public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId, string? deviceClass)
+ public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId,
+ string? deviceClass)
{
SetupEntities(
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
@@ -111,7 +123,8 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
{
SetupEntities(
- new EntitySpec { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
+ new EntitySpec
+ { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
@@ -124,7 +137,8 @@ public class BatterySensorDiscoveryServiceTests
[Theory]
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
- public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state, bool expectedIncluded)
+ public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state,
+ bool expectedIncluded)
{
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
@@ -133,10 +147,7 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(expectedIncluded ? 1 : 0);
- if (!expectedIncluded)
- {
- return;
- }
+ if (!expectedIncluded) return;
result[0].EntityId.Should().Be("sensor.boundary_battery");
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
@@ -239,7 +250,8 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(7);
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
- result.Select(s => s.FriendlyName).Should().OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
+ result.Select(s => s.FriendlyName).Should()
+ .OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
}
#endregion
@@ -279,15 +291,4 @@ public class BatterySensorDiscoveryServiceTests
}
#endregion
-
- #region IsExcludedDevice
-
- [Theory]
- [MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
- public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
- {
- BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
- }
-
- #endregion
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj
index 851e118..e493f51 100644
--- a/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj
+++ b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj
@@ -8,20 +8,20 @@
-
- <_Parameter1>BatteryMonitor.Manager.Tests
-
+
+ <_Parameter1>BatteryMonitor.Manager.Tests
+
-
-
+
+
-
-
-
+
+
+
diff --git a/BatteryMonitor.Manager/BatteryMonitorInit.cs b/BatteryMonitor.Manager/BatteryMonitorInit.cs
index 7b0e386..a72d22b 100644
--- a/BatteryMonitor.Manager/BatteryMonitorInit.cs
+++ b/BatteryMonitor.Manager/BatteryMonitorInit.cs
@@ -1,21 +1,22 @@
using System.Reactive.Concurrency;
+using BatteryMonitor.Models;
+using BatteryMonitorManager.Interface;
+using BatteryMonitorManager.Models;
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
{
- private readonly ILogger _logger;
- private readonly IScheduler _scheduler;
private readonly IBatterySensorDiscoveryService _discoveryService;
+ private readonly ILogger _logger;
private readonly IBatteryNotificationService _notificationService;
private readonly BatteryMonitorOptions _options;
+ private readonly IScheduler _scheduler;
public BatteryMonitorInit(
ILogger logger,
@@ -55,9 +56,8 @@ public sealed class BatteryMonitorInit
CheckAndNotify();
if (_logger.IsEnabled(LogLevel.Information))
- {
- _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent);
- }
+ _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
+ _options.BatteryThresholdPercent);
}
catch (Exception ex)
{
@@ -68,7 +68,7 @@ public sealed class BatteryMonitorInit
private void ScheduleDailyCheck()
{
- _scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () =>
+ _scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () =>
{
try
{
@@ -98,4 +98,4 @@ public sealed class BatteryMonitorInit
_logger.LogDebug("No low battery devices found");
}
}
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs
index aa1e2d2..5608f34 100644
--- a/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs
+++ b/BatteryMonitor.Manager/BatteryMonitorServiceRegistration.cs
@@ -1,8 +1,8 @@
+using BatteryMonitorManager.Interface;
+using BatteryMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
-using BatteryMonitorManager.Interface;
-using BatteryMonitorManager.Models;
namespace BatteryMonitorManager;
@@ -14,10 +14,7 @@ public static class BatteryMonitorServiceRegistration
.GetSection(BatteryMonitorOptions.SectionName)
.Get() ?? new BatteryMonitorOptions();
- if (!options.Enabled)
- {
- return services;
- }
+ if (!options.Enabled) return services;
services
.AddNetDaemonApp()
@@ -26,4 +23,4 @@ public static class BatteryMonitorServiceRegistration
return services;
}
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager/BatteryNotificationService.cs b/BatteryMonitor.Manager/BatteryNotificationService.cs
index ca42119..45deb32 100644
--- a/BatteryMonitor.Manager/BatteryNotificationService.cs
+++ b/BatteryMonitor.Manager/BatteryNotificationService.cs
@@ -1,8 +1,8 @@
using System.Text;
-using Microsoft.Extensions.Logging;
-using NetDaemon.HassModel;
using BatteryMonitor.Models;
using BatteryMonitorManager.Interface;
+using Microsoft.Extensions.Logging;
+using NetDaemon.HassModel;
namespace BatteryMonitorManager;
@@ -12,10 +12,7 @@ public sealed class BatteryNotificationService(
{
public void NotifyLowBattery(IReadOnlyList lowBatteryDevices)
{
- if (lowBatteryDevices.Count == 0)
- {
- return;
- }
+ if (lowBatteryDevices.Count == 0) return;
var message = BuildNotificationMessage(lowBatteryDevices);
@@ -30,11 +27,9 @@ public sealed class BatteryNotificationService(
});
if (logger.IsEnabled(LogLevel.Information))
- {
logger.LogInformation(
"Sent low battery notification for {Count} device(s)",
lowBatteryDevices.Count);
- }
}
public void DismissNotification()
@@ -57,10 +52,8 @@ public sealed class BatteryNotificationService(
sb.AppendLine();
foreach (var device in devices.OrderBy(d => d.BatteryLevel))
- {
sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%");
- }
return sb.ToString().TrimEnd();
}
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs
index 8819e9a..0a6f644 100644
--- a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs
+++ b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs
@@ -1,10 +1,10 @@
using System.Globalization;
using System.Text.Json;
+using BatteryMonitor.Models;
+using BatteryMonitorManager.Interface;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
-using BatteryMonitor.Models;
-using BatteryMonitorManager.Interface;
namespace BatteryMonitorManager;
@@ -24,11 +24,9 @@ public sealed class BatterySensorDiscoveryService(
.ToList();
if (logger.IsEnabled(LogLevel.Information))
- {
logger.LogInformation(
"Battery check: found {Count} sensors below {Threshold}%",
lowBatterySensors.Count, thresholdPercent);
- }
return lowBatterySensors!;
}
@@ -36,9 +34,7 @@ public sealed class BatterySensorDiscoveryService(
internal static bool IsBatterySensor(Entity entity)
{
if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase))
- {
return false;
- }
var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class");
@@ -60,9 +56,8 @@ public sealed class BatterySensorDiscoveryService(
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");
- }
+ logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
+ state ?? "null");
return null;
}
@@ -70,17 +65,13 @@ public sealed class BatterySensorDiscoveryService(
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);
- }
+ logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
+ state);
return null;
}
- if (batteryLevel >= thresholdPercent)
- {
- return null;
- }
+ if (batteryLevel >= thresholdPercent) return null;
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
?? entity.EntityId;
@@ -95,13 +86,10 @@ public sealed class BatterySensorDiscoveryService(
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
{
- if (element is null)
- {
- return null;
- }
+ if (element is null) return null;
return element.Value.TryGetProperty(propertyName, out var value)
? value.GetString()
: null;
}
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs
index 0b6ff0d..54caf3b 100644
--- a/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs
+++ b/BatteryMonitor.Manager/Interface/IBatteryNotificationService.cs
@@ -7,4 +7,4 @@ public interface IBatteryNotificationService
void NotifyLowBattery(IReadOnlyList lowBatteryDevices);
void DismissNotification();
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs
index 66e1f60..af41652 100644
--- a/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs
+++ b/BatteryMonitor.Manager/Interface/IBatterySensorDiscoveryService.cs
@@ -5,4 +5,4 @@ namespace BatteryMonitorManager.Interface;
public interface IBatterySensorDiscoveryService
{
IReadOnlyList DiscoverLowBatterySensors(int thresholdPercent);
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs
index 3072422..34d00d4 100644
--- a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs
+++ b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs
@@ -9,4 +9,4 @@ public sealed class BatteryMonitorOptions
public bool Enabled { get; init; }
public int BatteryThresholdPercent { get; init; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Models/BatteryMonitorConsts.cs b/BatteryMonitor.Models/BatteryMonitorConsts.cs
index 0fb47e4..3eb4a65 100644
--- a/BatteryMonitor.Models/BatteryMonitorConsts.cs
+++ b/BatteryMonitor.Models/BatteryMonitorConsts.cs
@@ -32,4 +32,4 @@ public static class BatteryMonitorConsts
"oneplus",
"ipad"
];
-}
+}
\ No newline at end of file
diff --git a/BatteryMonitor.Models/BatterySensorInfo.cs b/BatteryMonitor.Models/BatterySensorInfo.cs
index fede27b..062f353 100644
--- a/BatteryMonitor.Models/BatterySensorInfo.cs
+++ b/BatteryMonitor.Models/BatterySensorInfo.cs
@@ -7,4 +7,4 @@ public sealed class BatterySensorInfo
public required string FriendlyName { get; init; }
public required double BatteryLevel { get; init; }
-}
+}
\ No newline at end of file
diff --git a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs
index ed12815..e20a70c 100644
--- a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs
+++ b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs
@@ -1,8 +1,8 @@
using BoilerMonitor.Models.Enums;
+using BoilerMonitorManager;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
-using BoilerMonitorManager;
namespace BoilerMonitor.Manager.Tests;
@@ -10,84 +10,11 @@ public class BoilerControlServiceTests
{
private readonly Mock> _loggerMock = new();
- private BoilerControlService CreateSut() => new(_loggerMock.Object);
-
- #region TurnOn scenarios
-
- [Theory]
- [InlineData("off")]
- [InlineData("OFF")]
- [InlineData("Off")]
- [InlineData(null)]
- [InlineData("")]
- [InlineData(" ")]
- [InlineData("off ")]
- [InlineData("unavailable")]
- [InlineData("unknown")]
- [InlineData("0")]
- public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
+ private BoilerControlService CreateSut()
{
- var result = CreateSut().DetermineAction(
- isNowCheap: true, waterReady: false, currentSwitchState: switchState,
- budgetExhausted: false, budgetOverride: false);
-
- result.Should().Be(BoilerAction.TurnOn);
+ return new BoilerControlService(_loggerMock.Object);
}
- [Theory]
- [InlineData("off", BoilerAction.TurnOn)]
- [InlineData(null, BoilerAction.TurnOn)]
- [InlineData("unavailable", BoilerAction.TurnOn)]
- [InlineData("on", BoilerAction.NoChange)]
- [InlineData("On", BoilerAction.NoChange)]
- [InlineData("ON", BoilerAction.NoChange)]
- public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn(
- string? switchState,
- BoilerAction expectedAction)
- {
- var result = CreateSut().DetermineAction(
- isNowCheap: true, waterReady: false, currentSwitchState: switchState,
- budgetExhausted: true, budgetOverride: true);
-
- result.Should().Be(expectedAction);
- }
-
- #endregion
-
- #region TurnOff scenarios
-
- [Theory]
- [InlineData("on")]
- [InlineData("ON")]
- [InlineData("On")]
- [InlineData("oN")]
- public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
- {
- var result = CreateSut().DetermineAction(
- isNowCheap: false, waterReady: false, currentSwitchState: switchState,
- budgetExhausted: false, budgetOverride: false);
-
- result.Should().Be(BoilerAction.TurnOff);
- }
-
- [Theory]
- [InlineData(true, false, false)] // water ready
- [InlineData(false, true, false)] // budget exhausted, no override
- [InlineData(true, true, true)] // water ready wins over the budget override
- public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff(
- bool waterReady,
- bool budgetExhausted,
- bool budgetOverride)
- {
- var result = CreateSut().DetermineAction(
- isNowCheap: true, waterReady: waterReady, currentSwitchState: "on",
- budgetExhausted: budgetExhausted, budgetOverride: budgetOverride);
-
- result.Should().Be(BoilerAction.TurnOff);
- }
-
- #endregion
-
#region NoChange scenarios
[Theory]
@@ -115,11 +42,87 @@ public class BoilerControlServiceTests
#endregion
+ #region TurnOn scenarios
+
+ [Theory]
+ [InlineData("off")]
+ [InlineData("OFF")]
+ [InlineData("Off")]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("off ")]
+ [InlineData("unavailable")]
+ [InlineData("unknown")]
+ [InlineData("0")]
+ public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
+ {
+ var result = CreateSut().DetermineAction(
+ true, false, switchState,
+ false, false);
+
+ result.Should().Be(BoilerAction.TurnOn);
+ }
+
+ [Theory]
+ [InlineData("off", BoilerAction.TurnOn)]
+ [InlineData(null, BoilerAction.TurnOn)]
+ [InlineData("unavailable", BoilerAction.TurnOn)]
+ [InlineData("on", BoilerAction.NoChange)]
+ [InlineData("On", BoilerAction.NoChange)]
+ [InlineData("ON", BoilerAction.NoChange)]
+ public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn(
+ string? switchState,
+ BoilerAction expectedAction)
+ {
+ var result = CreateSut().DetermineAction(
+ true, false, switchState,
+ true, true);
+
+ result.Should().Be(expectedAction);
+ }
+
+ #endregion
+
+ #region TurnOff scenarios
+
+ [Theory]
+ [InlineData("on")]
+ [InlineData("ON")]
+ [InlineData("On")]
+ [InlineData("oN")]
+ public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
+ {
+ var result = CreateSut().DetermineAction(
+ false, false, switchState,
+ false, false);
+
+ result.Should().Be(BoilerAction.TurnOff);
+ }
+
+ [Theory]
+ [InlineData(true, false, false)] // water ready
+ [InlineData(false, true, false)] // budget exhausted, no override
+ [InlineData(true, true, true)] // water ready wins over the budget override
+ public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff(
+ bool waterReady,
+ bool budgetExhausted,
+ bool budgetOverride)
+ {
+ var result = CreateSut().DetermineAction(
+ true, waterReady, "on",
+ budgetExhausted, budgetOverride);
+
+ result.Should().Be(BoilerAction.TurnOff);
+ }
+
+ #endregion
+
#region Comprehensive truth tables
///
- /// Complete truth table for a boiler that is currently ON: it may only stay on when
- /// it is cheap, water is not ready and the budget is available (or overridden).
+ /// Complete truth table for a boiler that is currently ON: it may only stay on when
+ /// it is cheap, water is not ready and the budget is available (or overridden).
///
public static TheoryData SwitchOnActionMatrix => new()
{
@@ -151,14 +154,14 @@ public class BoilerControlServiceTests
BoilerAction expectedAction)
{
var result = CreateSut().DetermineAction(
- isNowCheap, waterReady, currentSwitchState: "on", budgetExhausted, budgetOverride);
+ isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
}
///
- /// Complete truth table for a boiler that is currently OFF: it may only turn on when
- /// it is cheap, water is not ready and the budget is available (or overridden).
+ /// Complete truth table for a boiler that is currently OFF: it may only turn on when
+ /// it is cheap, water is not ready and the budget is available (or overridden).
///
public static TheoryData SwitchOffActionMatrix => new()
{
@@ -190,10 +193,10 @@ public class BoilerControlServiceTests
BoilerAction expectedAction)
{
var result = CreateSut().DetermineAction(
- isNowCheap, waterReady, currentSwitchState: "off", budgetExhausted, budgetOverride);
+ isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
}
#endregion
-}
+}
\ No newline at end of file
diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj
index 0d523c5..9a2365f 100644
--- a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj
+++ b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj
@@ -1,38 +1,38 @@
-
- net10.0
- enable
- enable
- false
-
+
+ net10.0
+ enable
+ enable
+ false
+
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
-
-
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs
index 45b4c9a..8982bf8 100644
--- a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs
+++ b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs
@@ -50,10 +50,10 @@ public class BoilerMonitorConfigTests
bool expected)
{
var config = BoilerMonitorTestData.CreateConfig(
- boilerPowerEntityId: powerEntityId,
- boilerSwitchEntityId: switchEntityId,
- pollIntervalSeconds: pollIntervalSeconds,
- heatingPowerThresholdWatts: heatingPowerThresholdWatts);
+ powerEntityId,
+ switchEntityId,
+ pollIntervalSeconds,
+ heatingPowerThresholdWatts);
config.IsFullyConfigured.Should().Be(expected, scenario);
}
@@ -62,9 +62,9 @@ public class BoilerMonitorConfigTests
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
{
var config = BoilerMonitorTestData.CreateConfig(
- boilerPowerEntityId: " sensor.sonoff_1002230e32_power ",
- boilerSwitchEntityId: "SWITCH.SONOFF_1002230E32");
+ " sensor.sonoff_1002230e32_power ",
+ "SWITCH.SONOFF_1002230E32");
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
}
-}
+}
\ No newline at end of file
diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs
index 4898af6..50635fd 100644
--- a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs
+++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs
@@ -47,10 +47,13 @@ public class BoilerMonitorEntityServiceTests
.Returns(Task.CompletedTask);
}
- private BoilerMonitorEntityService CreateSut() => new(
- _entityManagerMock.Object,
- _haContextMock.Object,
- _loggerMock.Object);
+ private BoilerMonitorEntityService CreateSut()
+ {
+ return new BoilerMonitorEntityService(
+ _entityManagerMock.Object,
+ _haContextMock.Object,
+ _loggerMock.Object);
+ }
#region ReadPersistedState
@@ -61,7 +64,7 @@ public class BoilerMonitorEntityServiceTests
TimeSpan? expectedRunTime)
{
_haContextMock.SetupEntityStates(
- BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: runtimeState, sessionCount: "2"));
+ BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
var result = CreateSut().ReadPersistedState();
@@ -83,7 +86,7 @@ public class BoilerMonitorEntityServiceTests
int? expectedSessionCount)
{
_haContextMock.SetupEntityStates(
- BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: "3600", sessionCount: sessionCountState));
+ BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
var result = CreateSut().ReadPersistedState();
@@ -102,7 +105,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
{
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
- todayRuntime: "7200", sessionCount: "3", skipPriceCap: "ON", budgetOverride: "OFF"));
+ "7200", "3", "ON", "OFF"));
var result = CreateSut().ReadPersistedState();
@@ -135,7 +138,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
{
_haContextMock.SetupEntityStates(
- BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: null, sessionCount: null));
+ BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
CreateSut().ReadPersistedState().Should().BeNull();
}
@@ -242,11 +245,11 @@ public class BoilerMonitorEntityServiceTests
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
{
var context = BoilerMonitorTestData.CreateUpdateContext(
- todayRunTime: TimeSpan.FromSeconds(3723.9),
- remainingTime: TimeSpan.FromSeconds(42.9),
- budgetPercentage: 150.0,
- budgetExhausted: true,
- sessionCount: 4,
+ TimeSpan.FromSeconds(3723.9),
+ TimeSpan.FromSeconds(42.9),
+ 150.0,
+ true,
+ 4,
waterReady: true);
await CreateSut().UpdateEntitiesAsync(context);
@@ -257,7 +260,8 @@ public class BoilerMonitorEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once);
- _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny