feat: add BatteryMonitor implementation with discovery, notification, and scheduling services

This commit is contained in:
Marius
2026-04-01 10:55:33 +03:00
parent 11c2574235
commit 6e4d684359
114 changed files with 22820 additions and 527 deletions
+3
View File
@@ -108,3 +108,6 @@ ServiceFabricBackup/
# Sensitive / local config (uncomment if you use appsettings.local.json etc.)
# appsettings.*.local.json
# *.local.json
# Cursor MCP config (contains secrets)
.cursor/mcp.json
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,143 @@
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using BatteryMonitor.Models;
using BatteryMonitorManager;
namespace BatteryMonitor.Manager.Tests;
public class BatteryNotificationServiceTests
{
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock;
public BatteryNotificationServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BatteryNotificationService>>();
}
private BatteryNotificationService CreateSut()
{
return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object);
}
#region NotifyLowBattery
[Fact]
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate()
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", BatteryLevel = 3 },
new() { EntityId = "sensor.bedroom_battery", FriendlyName = "Bedroom Battery", BatteryLevel = 1 }
};
var sut = CreateSut();
sut.NotifyLowBattery(devices);
_haContextMock.Verify(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationCreateService,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Once);
}
[Fact]
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService()
{
var devices = new List<BatterySensorInfo>();
var sut = CreateSut();
sut.NotifyLowBattery(devices);
_haContextMock.Verify(h => h.CallService(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Never);
}
#endregion
#region DismissNotification
[Fact]
public void DismissNotification_ShouldCallPersistentNotificationDismiss()
{
var sut = CreateSut();
sut.DismissNotification();
_haContextMock.Verify(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationDismissService,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Once);
}
#endregion
#region BuildNotificationMessage
[Fact]
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 4 },
new() { EntityId = "sensor.b", FriendlyName = "Device B", BatteryLevel = 1 },
new() { EntityId = "sensor.c", FriendlyName = "Device C", BatteryLevel = 3 }
};
var message = BatteryNotificationService.BuildNotificationMessage(devices);
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines[1].Should().Contain("Device B");
lines[2].Should().Contain("Device C");
lines[3].Should().Contain("Device A");
}
[Fact]
public void BuildNotificationMessage_ShouldContainTitle()
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 2 }
};
var message = BatteryNotificationService.BuildNotificationMessage(devices);
message.Should().Contain("low battery");
}
[Fact]
public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel()
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Bathroom Battery", BatteryLevel = 3 }
};
var message = BatteryNotificationService.BuildNotificationMessage(devices);
message.Should().Contain("Bathroom Battery");
message.Should().Contain("3%");
}
[Fact]
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Test Device", BatteryLevel = 1 }
};
var message = BatteryNotificationService.BuildNotificationMessage(devices);
message.Should().Contain("- **Test Device**: 1%");
}
#endregion
}
@@ -0,0 +1,322 @@
using System.Text.Json;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using BatteryMonitorManager;
using BatteryMonitor.Models;
namespace BatteryMonitor.Manager.Tests;
public class BatterySensorDiscoveryServiceTests
{
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock;
public BatterySensorDiscoveryServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
}
private BatterySensorDiscoveryService CreateSut()
{
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
}
private void SetupEntities(params (string entityId, string? deviceClass, string? state, string? friendlyName)[] entities)
{
var entityList = new List<Entity>();
foreach (var (entityId, deviceClass, state, friendlyName) in entities)
{
var attributes = new Dictionary<string, object?>();
if (deviceClass is not null)
{
attributes["device_class"] = deviceClass;
}
if (friendlyName is not null)
{
attributes["friendly_name"] = friendlyName;
}
var attributesJson = JsonSerializer.SerializeToElement(attributes);
var entityState = new EntityState { AttributesJson = attributesJson, State = state };
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
var entity = new Entity(_haContextMock.Object, entityId);
entityList.Add(entity);
}
_haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
}
#region Discovery
[Fact]
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "3", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery"),
("sensor.boiler_temp_battery", "battery", "2", "Boiler Temp Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(2);
result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery");
result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldExcludePhoneDevices()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.erikas_iphone_battery_level", "battery", "1", "Erika's iPhone Battery"),
("sensor.home_phone_battery_state", "battery", "3", "Home Phone Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldExcludeWatchDevices()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.marius_watch_battery_level", "battery", "1", "Marius Watch Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldExcludeGalaxyDevices()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.sm_s936b_battery_level", "battery", "1", "Galaxy S24 Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldIgnoreNonSensorDomain()
{
SetupEntities(
("binary_sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldIgnoreNonBatteryDeviceClass()
{
SetupEntities(
("sensor.bathroom_temperature", "temperature", "2", "Bathroom Temperature"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldSkipUnavailableState()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "unavailable", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldSkipUnknownState()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "unknown", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
}
[Fact]
public void DiscoverLowBatterySensors_ShouldSkipNonParsableState()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "not_a_number", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
{
SetupEntities(
("sensor.temperature", "temperature", "22", "Temperature"),
("switch.some_switch", null, "on", "Switch")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().BeEmpty();
}
[Fact]
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().BeEmpty();
}
[Fact]
public void DiscoverLowBatterySensors_ShouldRespectCustomThreshold()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "15", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "25", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(20);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldPopulateFriendlyName()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().FriendlyName.Should().Be("Bathroom Battery");
result.First().BatteryLevel.Should().Be(2);
}
[Fact]
public void DiscoverLowBatterySensors_ShouldUseEntityIdWhenNoFriendlyName()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", null)
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().FriendlyName.Should().Be("sensor.bathroom_battery");
}
#endregion
#region IsBatterySensor
[Fact]
public void IsBatterySensor_WithBatteryDeviceClass_ShouldReturnTrue()
{
SetupEntities(("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"));
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery");
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeTrue();
}
[Fact]
public void IsBatterySensor_WithNonSensorDomain_ShouldReturnFalse()
{
SetupEntities(("binary_sensor.bathroom_battery", "battery", "50", "Bathroom Battery"));
var entity = new Entity(_haContextMock.Object, "binary_sensor.bathroom_battery");
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
}
[Fact]
public void IsBatterySensor_WithNonBatteryDeviceClass_ShouldReturnFalse()
{
SetupEntities(("sensor.bathroom_temperature", "temperature", "22", "Bathroom Temperature"));
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_temperature");
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
}
#endregion
#region IsExcludedDevice
[Theory]
[InlineData("sensor.erikas_iphone_battery_level", true)]
[InlineData("sensor.home_phone_battery_state", true)]
[InlineData("sensor.marius_watch_battery_level", true)]
[InlineData("sensor.sm_s936b_battery_level", true)]
[InlineData("sensor.sm_a536b_battery_level", true)]
[InlineData("sensor.pixel_8_battery_level", true)]
[InlineData("sensor.oneplus_battery_level", true)]
[InlineData("sensor.ipad_battery_level", true)]
[InlineData("sensor.galaxy_s24_battery", true)]
[InlineData("sensor.bathroom_battery", false)]
[InlineData("sensor.boiler_temp_battery", false)]
[InlineData("sensor.aquarium_leak_sensor_battery", false)]
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
{
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
}
#endregion
}
@@ -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;
}
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>BatteryMonitor.Models</RootNamespace>
</PropertyGroup>
</Project>
@@ -0,0 +1,35 @@
namespace BatteryMonitor.Models;
public static class BatteryMonitorConsts
{
public const int DefaultBatteryThresholdPercent = 5;
public const string BatteryDeviceClass = "battery";
public const string SensorDomainPrefix = "sensor.";
public const string NotificationId = "battery_monitor_low_battery";
public const string NotificationTitle = "Low Battery Alert";
public const string PersistentNotificationDomain = "persistent_notification";
public const string PersistentNotificationCreateService = "create";
public const string PersistentNotificationDismissService = "dismiss";
public const string DailyCheckCron = "0 8 * * *";
public static readonly string[] ExcludedKeywords =
[
"iphone",
"phone",
"watch",
"galaxy",
"sm_s",
"sm_a",
"pixel",
"oneplus",
"ipad"
];
}
@@ -0,0 +1,10 @@
namespace BatteryMonitor.Models;
public sealed class BatterySensorInfo
{
public required string EntityId { get; init; }
public required string FriendlyName { get; init; }
public required double BatteryLevel { get; init; }
}
@@ -10,8 +10,8 @@ public class BoilerMonitorConfigTests
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.power",
BoilerSwitchEntityId = "switch.boiler",
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
@@ -25,7 +25,7 @@ public class BoilerMonitorConfigTests
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = null,
BoilerSwitchEntityId = "switch.boiler",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
@@ -38,7 +38,7 @@ public class BoilerMonitorConfigTests
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.power",
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = null,
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
@@ -52,8 +52,8 @@ public class BoilerMonitorConfigTests
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.power",
BoilerSwitchEntityId = "switch.boiler",
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = null,
HeatingPowerThresholdWatts = 5.0
};
@@ -66,8 +66,8 @@ public class BoilerMonitorConfigTests
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.power",
BoilerSwitchEntityId = "switch.boiler",
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = null
};
@@ -81,7 +81,7 @@ public class BoilerMonitorConfigTests
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = " ",
BoilerSwitchEntityId = "switch.boiler",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
@@ -94,8 +94,8 @@ public class BoilerMonitorConfigTests
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.power",
BoilerSwitchEntityId = "switch.boiler",
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 0,
HeatingPowerThresholdWatts = 5.0
};
@@ -108,8 +108,8 @@ public class BoilerMonitorConfigTests
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.power",
BoilerSwitchEntityId = "switch.boiler",
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 0.0
};
@@ -122,8 +122,8 @@ public class BoilerMonitorConfigTests
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.power",
BoilerSwitchEntityId = "switch.boiler",
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = -1,
HeatingPowerThresholdWatts = 5.0
};
@@ -48,8 +48,8 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "5");
SetupEntityState(TodayRuntimeEntityId, "7200");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SkipPriceCapEntityId, "ON");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -58,8 +58,8 @@ public class BoilerMonitorEntityServiceTests
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(3600));
result.SessionCount.Should().Be(5);
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200));
result.SessionCount.Should().Be(3);
result.SkipPriceCapState.Should().Be("ON");
result.BudgetOverrideState.Should().Be("OFF");
}
@@ -87,7 +87,7 @@ public class BoilerMonitorEntityServiceTests
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "unavailable");
SetupEntityState(SessionCountEntityId, "5");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -103,7 +103,7 @@ public class BoilerMonitorEntityServiceTests
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "unknown");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -118,7 +118,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "1800");
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "unavailable");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -135,7 +135,7 @@ public class BoilerMonitorEntityServiceTests
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, null);
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -150,7 +150,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "1800");
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, null);
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -167,7 +167,7 @@ public class BoilerMonitorEntityServiceTests
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "not_a_number");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -182,7 +182,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "1800");
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "abc");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -199,7 +199,7 @@ public class BoilerMonitorEntityServiceTests
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "-100");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -214,7 +214,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "1800");
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "-1");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -230,8 +230,8 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "900");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(TodayRuntimeEntityId, "1800");
SetupEntityState(SessionCountEntityId, "1");
SetupEntityState(SkipPriceCapEntityId, null);
SetupEntityState(BudgetOverrideEntityId, null);
@@ -240,8 +240,8 @@ public class BoilerMonitorEntityServiceTests
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(900));
result.SessionCount.Should().Be(2);
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800));
result.SessionCount.Should().Be(1);
result.SkipPriceCapState.Should().BeNull();
result.BudgetOverrideState.Should().BeNull();
}
@@ -253,7 +253,7 @@ public class BoilerMonitorEntityServiceTests
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, state);
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -268,8 +268,8 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "1800.5");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(TodayRuntimeEntityId, "134.66");
SetupEntityState(SessionCountEntityId, "1");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
@@ -278,7 +278,8 @@ public class BoilerMonitorEntityServiceTests
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800.5));
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66));
result.SessionCount.Should().Be(1);
}
#endregion
@@ -71,7 +71,7 @@ public class WaterReadyServiceTests
var sut = CreateSut();
// Act
var result = sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
@@ -202,7 +202,7 @@ public class WaterReadyServiceTests
sut.NotifyTurnedOn();
// Act — high power during grace period is still "not ready" (heating)
var result = sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
@@ -420,7 +420,7 @@ public class WaterReadyServiceTests
var sut = CreateSut();
// Act — water is not ready (high power), no cooldown should be triggered
sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
sut.IsInCooldown.Should().BeFalse();
@@ -20,8 +20,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.2" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
</ItemGroup>
</Project>
@@ -12,7 +12,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
</ItemGroup>
</Project>
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
@@ -7,14 +7,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
<PackageReference Include="NetDaemon.Runtime" Version="26.3.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
<PackageReference Include="NetDaemon.Client" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.3.0" />
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,69 @@
using BoilerMonitor.Models;
using LightMonitor.Models;
using NordPool.Models;
using ShowerMonitor.Models;
namespace HomeAssistant.HistoryReplay.Configuration;
public static class ReplayEntityMap
{
public static IReadOnlyList<string> GetNordPoolEntities() =>
[
"sensor.nordpool_kwh_lt_eur_3_10_0",
NordPoolConsts.CurrentPriceEntityId,
BoilerMonitorConsts.BoilerDailyHoursEntityId,
BoilerMonitorConsts.BoilerPriceCapEntityId,
BoilerMonitorConsts.BoilerReadyByEntityId,
BoilerMonitorConsts.SkipPriceCapEntityId
];
public static IReadOnlyList<string> GetBoilerEntities(string boilerPowerEntityId, string boilerSwitchEntityId) =>
[
boilerPowerEntityId,
boilerSwitchEntityId,
"sensor.nordpool_cheapest_intervals",
BoilerMonitorConsts.SkipPriceCapEntityId,
BoilerMonitorConsts.BudgetOverrideEntityId,
BoilerMonitorConsts.BoilerDailyHoursEntityId
];
public static IReadOnlyList<string> GetShowerEntities(string bathroomHumidityEntityId, string mainHomeHumidityEntityId) =>
[
bathroomHumidityEntityId,
mainHomeHumidityEntityId
];
public static IReadOnlyList<string> GetPowerEntities(string mainMeterEntityId) =>
[
mainMeterEntityId,
NordPoolConsts.CurrentPriceEntityId
];
public static IReadOnlyList<string> GetLightEntities(string sunEntityId, string lightEntityId, string[] personEntityIds)
{
var entities = new List<string> { sunEntityId, lightEntityId };
entities.AddRange(personEntityIds);
return entities;
}
public static IReadOnlyList<string> GetAllEntities(
string boilerPowerEntityId,
string boilerSwitchEntityId,
string bathroomHumidityEntityId,
string mainHomeHumidityEntityId,
string mainMeterEntityId,
string sunEntityId,
string lightEntityId,
string[] personEntityIds)
{
var all = new HashSet<string>();
foreach (var e in GetNordPoolEntities()) all.Add(e);
foreach (var e in GetBoilerEntities(boilerPowerEntityId, boilerSwitchEntityId)) all.Add(e);
foreach (var e in GetShowerEntities(bathroomHumidityEntityId, mainHomeHumidityEntityId)) all.Add(e);
foreach (var e in GetPowerEntities(mainMeterEntityId)) all.Add(e);
foreach (var e in GetLightEntities(sunEntityId, lightEntityId, personEntityIds)) all.Add(e);
return [.. all];
}
}
@@ -0,0 +1,19 @@
namespace HomeAssistant.HistoryReplay.Configuration;
public sealed class ReplayOptions
{
public const string SectionName = "Replay";
public DateTimeOffset StartTime { get; set; } = DateTimeOffset.UtcNow.AddDays(-1);
public DateTimeOffset EndTime { get; set; } = DateTimeOffset.UtcNow;
public ReplayMonitorFlags Monitors { get; set; } = new();
}
public sealed class ReplayMonitorFlags
{
public bool NordPool { get; set; } = true;
public bool Boiler { get; set; } = true;
public bool Shower { get; set; } = true;
public bool Power { get; set; } = true;
public bool Light { get; set; } = true;
}
@@ -0,0 +1,9 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HistoryStateEntry
{
public required string EntityId { get; init; }
public required string? State { get; init; }
public required DateTimeOffset LastChanged { get; init; }
public IReadOnlyDictionary<string, object>? Attributes { get; init; }
}
@@ -0,0 +1,65 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HistoryTimeline
{
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
{
if (!_entityTimelines.TryGetValue(entityId, out var list))
{
list = [];
_entityTimelines[entityId] = list;
}
list.AddRange(entries);
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
}
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
{
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
{
return null;
}
HistoryStateEntry? best = null;
foreach (var entry in entries)
{
if (entry.LastChanged <= timestamp)
{
best = entry;
}
else
{
break;
}
}
return best;
}
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
{
var timestamps = new SortedSet<DateTimeOffset>();
foreach (var entries in _entityTimelines.Values)
{
foreach (var entry in entries)
{
timestamps.Add(entry.LastChanged);
}
}
return [.. timestamps];
}
public IReadOnlyList<string> GetEntityIds() => [.. _entityTimelines.Keys];
public IReadOnlyList<HistoryStateEntry> GetEntityHistory(string entityId)
{
return _entityTimelines.TryGetValue(entityId, out var entries) ? entries : [];
}
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
}
@@ -0,0 +1,168 @@
using System.Globalization;
using System.Text.Json;
using HomeAssistant.HistoryReplay.HomeAssistantClient;
using Microsoft.Extensions.Logging;
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HomeAssistantHistoryProvider(
IHomeAssistantApiClient client,
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
{
private const int MaxEntitiesPerRequest = 10;
public async Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default)
{
var timeline = new HistoryTimeline();
var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest);
var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var batchTimeline in results)
{
foreach (var entityId in batchTimeline.GetEntityIds())
{
timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId));
}
}
logger.LogInformation(
"Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})",
entityIds.Count, timeline.TotalEntryCount, startTime, endTime);
return timeline;
}
private async Task<HistoryTimeline> FetchBatchAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken)
{
var timeline = new HistoryTimeline();
var entityIdsString = string.Join(",", entityIds);
logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString);
try
{
var result = await client.GetHistoryAsync(
entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken)
.ConfigureAwait(false);
ParseHistoryResponse(result, timeline);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString);
}
return timeline;
}
private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline)
{
if (response.ValueKind != JsonValueKind.Array)
{
return;
}
foreach (var entityArray in response.EnumerateArray())
{
if (entityArray.ValueKind != JsonValueKind.Array)
{
continue;
}
foreach (var stateObj in entityArray.EnumerateArray())
{
var entry = ParseStateEntry(stateObj);
if (entry is not null)
{
timeline.AddEntries(entry.EntityId, [entry]);
}
}
}
}
private HistoryStateEntry? ParseStateEntry(JsonElement stateObj)
{
if (!stateObj.TryGetProperty("entity_id", out var entityIdProp))
{
return null;
}
var entityId = entityIdProp.GetString();
if (string.IsNullOrEmpty(entityId))
{
return null;
}
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
DateTimeOffset lastChanged;
if (stateObj.TryGetProperty("last_changed", out var lastChangedProp))
{
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out lastChanged))
{
return null;
}
}
else
{
return null;
}
Dictionary<string, object>? attributes = null;
if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object)
{
attributes = ParseAttributes(attrProp);
}
return new HistoryStateEntry
{
EntityId = entityId,
State = state,
LastChanged = lastChanged,
Attributes = attributes
};
}
private static Dictionary<string, object> ParseAttributes(JsonElement attrElement)
{
var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var prop in attrElement.EnumerateObject())
{
attributes[prop.Name] = prop.Value.ValueKind switch
{
JsonValueKind.String => prop.Value.GetString() ?? string.Empty,
JsonValueKind.Number => prop.Value.GetDouble(),
JsonValueKind.True => true,
JsonValueKind.False => false,
_ => prop.Value.GetRawText()
};
}
return attributes;
}
private static IReadOnlyList<IReadOnlyList<string>> ChunkEntities(IReadOnlyList<string> entities, int chunkSize)
{
var chunks = new List<IReadOnlyList<string>>();
for (var i = 0; i < entities.Count; i += chunkSize)
{
var chunk = entities.Skip(i).Take(chunkSize).ToList();
chunks.Add(chunk);
}
return chunks;
}
}
@@ -0,0 +1,10 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public interface IHistoryDataProvider
{
Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default);
}
@@ -0,0 +1,45 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HomeAssistant.HistoryReplay</RootNamespace>
</PropertyGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,50 @@
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.Extensions.Options;
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
{
private readonly HttpClient _httpClient;
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
{
_httpClient = httpClient;
_httpClient.BaseAddress = settings.Value.BaseUrl;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
}
public async Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
if (endTime.HasValue)
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
if (minimalResponse)
path += "&minimal_response";
return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false);
}
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return doc.RootElement.Clone();
}
}
@@ -0,0 +1,15 @@
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public sealed class HomeAssistantSettings
{
public const string SectionName = "HomeAssistant";
public const int DefaultPort = 8123;
public const int DefaultTimeoutSeconds = 30;
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = DefaultPort;
public string Token { get; set; } = string.Empty;
public bool Ssl { get; set; }
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
}
@@ -0,0 +1,13 @@
using System.Text.Json;
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public interface IHomeAssistantApiClient
{
Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default);
}
+191
View File
@@ -0,0 +1,191 @@
using BoilerMonitorManager;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using HomeAssistant.HistoryReplay.Runners;
using HomeAssistant.HistoryReplay.HomeAssistantClient;
using LightMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPoolManager;
using NordPoolManager.Interface;
using PowerMonitorManager;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using Serilog;
using ShowerMonitorManager;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
try
{
Log.Information("Starting Home Assistant History Replay");
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
var services = new ServiceCollection();
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.AddSerilog(dispose: true);
});
services.Configure<HomeAssistantSettings>(configuration.GetSection(HomeAssistantSettings.SectionName));
services.Configure<ReplayOptions>(configuration.GetSection(ReplayOptions.SectionName));
services.Configure<BoilerMonitorOptions>(configuration.GetSection(BoilerMonitorOptions.SectionName));
services.Configure<ShowerMonitorOptions>(configuration.GetSection(ShowerMonitorOptions.SectionName));
services.Configure<PowerMonitorOptions>(configuration.GetSection(PowerMonitorOptions.SectionName));
services.Configure<LightMonitorOptions>(configuration.GetSection(LightMonitorOptions.SectionName));
services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get<ReplayOptions>() ?? new ReplayOptions();
var replayTimeline = new ReplayTimeline();
var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime);
services.AddSingleton(replayTimeline);
services.AddSingleton(replayTimeProvider);
services.AddSingleton<TimeProvider>(replayTimeProvider);
services.AddSingleton<IEntityManager, NoOpEntityManager>();
services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
services.AddSingleton<IBoilerControlService, BoilerControlService>();
services.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
services.AddSingleton<IWaterReadyService, WaterReadyService>();
services.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>();
services.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>();
var showerOptions = configuration.GetSection(ShowerMonitorOptions.SectionName).Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOptions.RateWindowSize));
services.AddSingleton<IShowerDetectionService, ShowerDetectionService>();
services.AddSingleton<ConsoleReportRenderer>();
var provider = services.BuildServiceProvider();
var historyProvider = provider.GetRequiredService<IHistoryDataProvider>();
var logger = provider.GetRequiredService<ILogger<Program>>();
var boilerOpts = provider.GetRequiredService<IOptions<BoilerMonitorOptions>>().Value;
var showerOpts = provider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
var powerOpts = provider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
var lightOpts = provider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
logger.LogInformation("Replay period: {Start} to {End}", replayOptions.StartTime, replayOptions.EndTime);
var allEntityIds = ReplayEntityMap.GetAllEntities(
boilerPowerEntityId: "sensor.boiler_power",
boilerSwitchEntityId: "switch.boiler",
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
mainMeterEntityId: powerOpts.MainMeterEntityId,
sunEntityId: lightOpts.SunEntityId,
lightEntityId: lightOpts.LightEntityId,
personEntityIds: lightOpts.PersonEntityIds);
logger.LogInformation("Fetching history for {Count} entities...", allEntityIds.Count);
var timeline = await historyProvider.FetchHistoryAsync(
allEntityIds, replayOptions.StartTime, replayOptions.EndTime);
var replayHaContext = new ReplayHaContext(
timeline,
replayTimeProvider,
replayTimeline,
provider.GetRequiredService<ILogger<ReplayHaContext>>());
var fanControlService = new ExhaustFanControlService(
replayHaContext,
provider.GetRequiredService<ILogger<ExhaustFanControlService>>(),
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>());
var runners = new List<IMonitorReplayRunner>();
if (replayOptions.Monitors.NordPool)
{
runners.Add(new NordPoolReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<ICheapestIntervalsFinder>(),
provider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>()));
}
if (replayOptions.Monitors.Boiler)
{
runners.Add(new BoilerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IBoilerControlService>(),
provider.GetRequiredService<IBoilerRunTimeTracker>(),
provider.GetRequiredService<IWaterReadyService>(),
provider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<BoilerMonitorOptions>>()));
}
if (replayOptions.Monitors.Shower)
{
runners.Add(new ShowerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IShowerDetectionService>(),
fanControlService,
provider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>()));
}
if (replayOptions.Monitors.Power)
{
runners.Add(new PowerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IOtherPowerCalculationService>(),
provider.GetRequiredService<IPowerCostCalculationService>(),
provider.GetRequiredService<ILogger<PowerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
}
if (replayOptions.Monitors.Light)
{
runners.Add(new LightReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<ILogger<LightReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<LightMonitorOptions>>()));
}
logger.LogInformation("Running {Count} monitor replay(s) in parallel...", runners.Count);
var replayTasks = runners.Select(r => Task.Run(() => r.RunAsync()));
await Task.WhenAll(replayTasks);
var renderer = provider.GetRequiredService<ConsoleReportRenderer>();
renderer.Render(replayTimeline, replayOptions);
}
catch (Exception ex)
{
Log.Fatal(ex, "History replay failed");
}
finally
{
await Log.CloseAndFlushAsync();
}
@@ -0,0 +1,38 @@
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using Microsoft.Extensions.Logging;
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class NoOpEntityManager(ILogger<NoOpEntityManager> logger) : IEntityManager
{
public Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
{
logger.LogDebug("[REPLAY] Would create {Count} entities", entities.Count);
return Task.CompletedTask;
}
public Task CreateEntityAsync(EntityCreateModel createModel)
{
logger.LogDebug("[REPLAY] Would create entity: {EntityId}", createModel.EntityId);
return Task.CompletedTask;
}
public Task SetEntityState(string entityId, string state)
{
logger.LogDebug("[REPLAY] Would set state for {EntityId}: {State}", entityId, state);
return Task.CompletedTask;
}
public Task SetEntityAttributes(string entityId, object attributes)
{
logger.LogDebug("[REPLAY] Would set attributes for {EntityId}", entityId);
return Task.CompletedTask;
}
public Task RemoveEntity(string entityId)
{
logger.LogDebug("[REPLAY] Would remove entity: {EntityId}", entityId);
return Task.CompletedTask;
}
}
@@ -0,0 +1,98 @@
using System.Reactive.Linq;
using System.Text.Json;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class ReplayHaContext : IHaContext
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ILogger<ReplayHaContext> _logger;
public ReplayHaContext(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ILogger<ReplayHaContext> logger)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_logger = logger;
}
public EntityState? GetState(string entityId)
{
var currentTime = _timeProvider.GetUtcNow();
var entry = _timeline.GetStateAt(entityId, currentTime);
if (entry is null)
{
return null;
}
JsonElement? attributesJson = null;
if (entry.Attributes is { Count: > 0 })
{
attributesJson = JsonSerializer.SerializeToElement(entry.Attributes);
}
return new EntityState
{
State = entry.State,
AttributesJson = attributesJson
};
}
public IReadOnlyList<Entity> GetAllEntities()
{
return _timeline.GetEntityIds()
.Select(id => new Entity(this, id))
.ToList();
}
public void CallService(string domain, string service, ServiceTarget? target = null, object? data = null)
{
var currentTime = _timeProvider.GetUtcNow();
var targetDescription = target?.EntityIds is not null
? string.Join(", ", target.EntityIds)
: "no target";
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = "ServiceCall",
EventType = ReplayEventType.ServiceCall,
Message = $"Would call {domain}.{service} on {targetDescription}",
Details = data is not null ? JsonSerializer.Serialize(data) : null
});
_logger.LogDebug("[REPLAY] {Domain}.{Service} → {Target}", domain, service, targetDescription);
}
public void SendEvent(string eventType, object? data = null)
{
_logger.LogDebug("[REPLAY] Would send event: {EventType}", eventType);
}
public IObservable<StateChange> StateAllChanges() => Observable.Empty<StateChange>();
public IObservable<Event> Events => Observable.Empty<Event>();
public Task<JsonElement?> CallServiceWithResponseAsync(
string domain, string service, ServiceTarget? target = null, object? data = null)
{
CallService(domain, service, target, data);
return Task.FromResult<JsonElement?>(null);
}
public Area? GetAreaFromEntityId(string entityId) => null;
public EntityRegistration? GetEntityRegistration(string entityId) => null;
}
@@ -0,0 +1,40 @@
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class ReplayTimeProvider : TimeProvider
{
private readonly Lock _lock = new();
private DateTimeOffset _currentUtcTime;
private readonly TimeZoneInfo _localTimeZone;
public ReplayTimeProvider(DateTimeOffset initialTime)
{
_currentUtcTime = initialTime.ToUniversalTime();
_localTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
}
public override DateTimeOffset GetUtcNow()
{
lock (_lock)
{
return _currentUtcTime;
}
}
public override TimeZoneInfo LocalTimeZone => _localTimeZone;
public void AdvanceTo(DateTimeOffset utcTime)
{
lock (_lock)
{
_currentUtcTime = utcTime.ToUniversalTime();
}
}
public void AdvanceBy(TimeSpan duration)
{
lock (_lock)
{
_currentUtcTime += duration;
}
}
}
@@ -0,0 +1,146 @@
using HomeAssistant.HistoryReplay.Configuration;
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ConsoleReportRenderer
{
private const string Separator = "═══════════════════════════════════════════════════════════";
private const string SectionSeparator = "── {0} ──────────────────────────────────────────────";
private const string TimeFormat = "HH:mm:ss";
public void Render(ReplayTimeline timeline, ReplayOptions options)
{
Console.WriteLine();
WriteColored(Separator, ConsoleColor.DarkCyan);
WriteColored($" REPLAY: {options.StartTime:yyyy-MM-dd HH:mm} → {options.EndTime:yyyy-MM-dd HH:mm}", ConsoleColor.White);
WriteColored(Separator, ConsoleColor.DarkCyan);
Console.WriteLine();
var monitors = timeline.GetMonitors()
.Where(m => !string.Equals(m, "ServiceCall", StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var monitor in monitors)
{
RenderMonitorSection(monitor, timeline.GetEventsByMonitor(monitor));
}
RenderServiceCallSection(timeline.GetEventsByMonitor("ServiceCall"));
RenderSummary(timeline);
}
private static void RenderMonitorSection(string monitor, IReadOnlyList<ReplayEvent> events)
{
Console.WriteLine();
WriteColored(string.Format(SectionSeparator, monitor), ConsoleColor.Yellow);
if (events.Count == 0)
{
WriteColored(" No events recorded", ConsoleColor.DarkGray);
return;
}
foreach (var evt in events)
{
var color = GetEventColor(evt.EventType);
var prefix = GetEventPrefix(evt.EventType);
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
WriteColored($" {timestamp} {prefix}{evt.Message}", color);
if (!string.IsNullOrEmpty(evt.Details))
{
WriteColored($" {evt.Details}", ConsoleColor.DarkGray);
}
}
WriteSectionSummary(events);
}
private static void RenderServiceCallSection(IReadOnlyList<ReplayEvent> events)
{
if (events.Count == 0)
{
return;
}
Console.WriteLine();
WriteColored(string.Format(SectionSeparator, "Service Calls"), ConsoleColor.Magenta);
foreach (var evt in events)
{
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
WriteColored($" {timestamp} → {evt.Message}", ConsoleColor.DarkMagenta);
}
WriteColored($"\n Total: {events.Count} service call(s) would have been made", ConsoleColor.DarkGray);
}
private static void RenderSummary(ReplayTimeline timeline)
{
var allEvents = timeline.GetAllEvents();
Console.WriteLine();
WriteColored(Separator, ConsoleColor.DarkCyan);
WriteColored(" REPLAY SUMMARY", ConsoleColor.White);
WriteColored(Separator, ConsoleColor.DarkCyan);
var decisions = allEvents.Count(e => e.EventType == ReplayEventType.Decision);
var serviceCalls = allEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
var warnings = allEvents.Count(e => e.EventType == ReplayEventType.Warning);
var anomalies = allEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
WriteColored($" Total events: {allEvents.Count}", ConsoleColor.Gray);
WriteColored($" Decisions: {decisions}", ConsoleColor.Cyan);
WriteColored($" Service calls: {serviceCalls}", ConsoleColor.Magenta);
WriteColored($" Warnings: {warnings}", ConsoleColor.DarkYellow);
WriteColored($" Anomalies: {anomalies}", ConsoleColor.Red);
Console.WriteLine();
}
private static void WriteSectionSummary(IReadOnlyList<ReplayEvent> events)
{
var decisions = events.Count(e => e.EventType == ReplayEventType.Decision);
var warnings = events.Count(e => e.EventType == ReplayEventType.Warning);
var stateChanges = events.Count(e => e.EventType == ReplayEventType.StateChange);
var parts = new List<string>();
if (decisions > 0) parts.Add($"{decisions} decision(s)");
if (stateChanges > 0) parts.Add($"{stateChanges} state change(s)");
if (warnings > 0) parts.Add($"{warnings} warning(s)");
if (parts.Count > 0)
{
WriteColored($"\n Summary: {string.Join(", ", parts)}", ConsoleColor.DarkGray);
}
}
private static ConsoleColor GetEventColor(ReplayEventType eventType) =>
eventType switch
{
ReplayEventType.Decision => ConsoleColor.Green,
ReplayEventType.StateChange => ConsoleColor.Cyan,
ReplayEventType.Warning => ConsoleColor.DarkYellow,
ReplayEventType.ServiceCall => ConsoleColor.Magenta,
ReplayEventType.Anomaly => ConsoleColor.Red,
_ => ConsoleColor.Gray
};
private static string GetEventPrefix(ReplayEventType eventType) =>
eventType switch
{
ReplayEventType.Decision => "→ ",
ReplayEventType.Warning => "⚠ ",
ReplayEventType.Anomaly => "⚠ ANOMALY: ",
ReplayEventType.ServiceCall => "⤷ ",
_ => ""
};
private static void WriteColored(string text, ConsoleColor color)
{
var previousColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ForegroundColor = previousColor;
}
}
@@ -0,0 +1,20 @@
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayEvent
{
public required DateTimeOffset Timestamp { get; init; }
public required string Monitor { get; init; }
public required ReplayEventType EventType { get; init; }
public required string Message { get; init; }
public string? Details { get; init; }
}
public enum ReplayEventType
{
Info,
Decision,
StateChange,
Warning,
ServiceCall,
Anomaly
}
@@ -0,0 +1,25 @@
using System.Collections.Concurrent;
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayTimeline
{
private readonly ConcurrentBag<ReplayEvent> _events = [];
public void AddEvent(ReplayEvent replayEvent)
{
_events.Add(replayEvent);
}
public IReadOnlyList<ReplayEvent> GetEventsByMonitor(string monitor) =>
_events
.Where(e => string.Equals(e.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
.OrderBy(e => e.Timestamp)
.ToList();
public IReadOnlyList<ReplayEvent> GetAllEvents() =>
_events.OrderBy(e => e.Timestamp).ToList();
public IReadOnlyList<string> GetMonitors() =>
_events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList();
}
@@ -0,0 +1,210 @@
using System.Globalization;
using BoilerMonitor.Models;
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using BoilerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class BoilerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IBoilerControlService _boilerControlService;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IWaterReadyService _waterReadyService;
private readonly ILogger<BoilerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly BoilerMonitorOptions _boilerOptions;
public string MonitorName => "Boiler";
public BoilerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IBoilerControlService boilerControlService,
IBoilerRunTimeTracker tracker,
IWaterReadyService waterReadyService,
ILogger<BoilerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<BoilerMonitorOptions> boilerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_boilerControlService = boilerControlService;
_tracker = tracker;
_waterReadyService = waterReadyService;
_logger = logger;
_replayOptions = replayOptions.Value;
_boilerOptions = boilerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Boiler replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultPollIntervalSeconds);
var heatingThreshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
BoilerAction? lastAction = null;
var lastWaterReady = false;
var boilerPowerEntityId = ReadConfigEntityState(
BoilerMonitorConsts.ConfigPowerEntityId, _replayOptions.StartTime);
var boilerSwitchEntityId = ReadConfigEntityState(
BoilerMonitorConsts.ConfigSwitchEntityId, _replayOptions.StartTime);
if (string.IsNullOrEmpty(boilerPowerEntityId) || string.IsNullOrEmpty(boilerSwitchEntityId))
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Warning,
Message = "Boiler not configured (missing power/switch entity IDs), skipping replay"
});
return Task.CompletedTask;
}
var configThresholdState = ReadConfigEntityState(
BoilerMonitorConsts.ConfigHeatingThresholdEntityId, _replayOptions.StartTime);
if (!string.IsNullOrEmpty(configThresholdState) &&
double.TryParse(configThresholdState, CultureInfo.InvariantCulture, out var configuredThreshold))
{
heatingThreshold = configuredThreshold;
}
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var powerEntry = _timeline.GetStateAt(boilerPowerEntityId, currentTime);
var switchEntry = _timeline.GetStateAt(boilerSwitchEntityId, currentTime);
var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime);
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime);
var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime);
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime);
var boilerPowerWatts = ParseDouble(powerEntry?.State);
var boilerSwitchState = switchEntry?.State;
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= heatingThreshold;
_tracker.RecordPollResult(isHeating, pollInterval);
var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap");
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0;
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold);
if (!lastWaterReady && waterReady)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.StateChange,
Message = $"Water ready detected (power: {boilerPowerWatts:F1}W, threshold: {heatingThreshold}W)"
});
}
lastWaterReady = waterReady;
var snapshot = _tracker.GetSnapshot();
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
: 0.0;
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
var action = _boilerControlService.DetermineAction(
effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
if (action != BoilerAction.NoChange && action != lastAction)
{
var actionMessage = action switch
{
BoilerAction.TurnOn => $"TURN ON (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
BoilerAction.TurnOff => $"TURN OFF (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
_ => action.ToString()
};
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = actionMessage,
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
});
if (action == BoilerAction.TurnOn)
{
_waterReadyService.NotifyTurnedOn();
}
}
lastAction = action;
currentTime = currentTime.Add(pollInterval);
}
var finalSnapshot = _tracker.GetSnapshot();
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: {finalSnapshot.AccumulatedRunTime:hh\\:mm\\:ss} total runtime, {finalSnapshot.SessionCount} session(s)"
});
_logger.LogInformation("Boiler replay complete");
return Task.CompletedTask;
}
private string? ReadConfigEntityState(string entityId, DateTimeOffset timestamp)
{
var entry = _timeline.GetStateAt(entityId, timestamp);
return entry?.State;
}
private static bool ReadAttributeBool(HistoryStateEntry? entry, string attributeName)
{
if (entry?.Attributes is null)
{
return false;
}
if (!entry.Attributes.TryGetValue(attributeName, out var value))
{
return false;
}
return value switch
{
bool b => b,
string s => bool.TryParse(s, out var parsed) && parsed,
double d => d != 0,
_ => false
};
}
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -0,0 +1,7 @@
namespace HomeAssistant.HistoryReplay.Runners;
public interface IMonitorReplayRunner
{
string MonitorName { get; }
Task RunAsync(CancellationToken cancellationToken = default);
}
@@ -0,0 +1,175 @@
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using LightMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class LightReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ILogger<LightReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly LightMonitorOptions _lightOptions;
public string MonitorName => "Light";
public LightReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ILogger<LightReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<LightMonitorOptions> lightOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_logger = logger;
_replayOptions = replayOptions.Value;
_lightOptions = lightOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Light replay");
ReplaySunEvents(cancellationToken);
ReplayPersonArrivals(cancellationToken);
_logger.LogInformation("Light replay complete");
return Task.CompletedTask;
}
private void ReplaySunEvents(CancellationToken cancellationToken)
{
var sunHistory = _timeline.GetEntityHistory(_lightOptions.SunEntityId);
string? previousSunState = null;
foreach (var entry in sunHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
var anyoneHome = IsAnyoneHome(entry.LastChanged);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (anyoneHome && !lightAlreadyOn)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = "TURN ON light (sun below horizon + someone home)"
});
}
else if (!anyoneHome)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but nobody home — light stays off"
});
}
else
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but light already on"
});
}
}
previousSunState = entry.State;
}
}
private void ReplayPersonArrivals(CancellationToken cancellationToken)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var personHistory = _timeline.GetEntityHistory(personEntityId);
string? previousState = null;
foreach (var entry in personHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(previousState, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
var sunEntry = _timeline.GetStateAt(_lightOptions.SunEntityId, entry.LastChanged);
var isDark = string.Equals(sunEntry?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (isDark && !lightAlreadyOn)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = $"TURN ON light ({personEntityId} arrived home + dark outside)"
});
}
else if (isDark)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"{personEntityId} arrived home (dark) but light already on"
});
}
}
previousState = entry.State;
}
}
}
private bool IsAnyoneHome(DateTimeOffset timestamp)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var entry = _timeline.GetStateAt(personEntityId, timestamp);
if (string.Equals(entry?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
@@ -0,0 +1,171 @@
using System.Globalization;
using BoilerMonitor.Models;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPool.Models;
using NordPoolManager.Interface;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class NordPoolReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly ILogger<NordPoolReplayRunner> _logger;
private readonly ReplayOptions _options;
public string MonitorName => "NordPool";
public NordPoolReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ICheapestIntervalsFinder cheapestIntervalsFinder,
ILogger<NordPoolReplayRunner> logger,
IOptions<ReplayOptions> options)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_logger = logger;
_options = options.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting NordPool replay");
var currentTime = _options.StartTime;
var interval = TimeSpan.FromMinutes(NordPoolConsts.MinutesPerInterval);
double? lastReportedPrice = null;
while (currentTime <= _options.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var priceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
if (priceEntry?.State is not null &&
double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice))
{
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.001)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Price: {currentPrice:F2} ct/kWh"
});
lastReportedPrice = currentPrice;
}
}
var boilerConfig = ReadBoilerConfig(currentTime);
if (boilerConfig is not null)
{
var prices = BuildNordPoolPriceFromHistory(currentTime);
if (prices.Prices is { Count: > 0 })
{
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
var effectiveIntervalCount = boilerConfig.SkipPriceCap
? NordPoolConsts.MaxDailyIntervals
: boilerConfig.IntervalCount;
var cheapest = _cheapestIntervalsFinder.FindCheapestIntervals(
prices, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline);
var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap(
cheapest, currentTime.LocalDateTime);
if (isNowCheap)
{
var currentInterval = cheapest.FirstOrDefault(i =>
currentTime.LocalDateTime >= i.Start && currentTime.LocalDateTime < i.End);
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = $"CHEAP interval active (rank #{currentInterval?.Rank}, price: {currentInterval?.Price:F2} ct/kWh)",
Details = $"Total cheap intervals: {cheapest.Count}"
});
}
}
}
currentTime = currentTime.Add(interval);
}
_logger.LogInformation("NordPool replay complete");
return Task.CompletedTask;
}
private BoilerConfig? ReadBoilerConfig(DateTimeOffset timestamp)
{
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, timestamp);
var priceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerPriceCapEntityId, timestamp);
var readyByEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerReadyByEntityId, timestamp);
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, timestamp);
if (dailyHoursEntry?.State is null || priceCapEntry?.State is null || readyByEntry?.State is null)
{
return null;
}
if (!double.TryParse(dailyHoursEntry.State, CultureInfo.InvariantCulture, out var dailyHours) ||
!double.TryParse(priceCapEntry.State, CultureInfo.InvariantCulture, out var priceCap))
{
return null;
}
var intervalCount = (int)(dailyHours * NordPoolConsts.IntervalsPerHour);
if (!TimeSpan.TryParse(readyByEntry.State, CultureInfo.InvariantCulture, out var readyByTime))
{
return null;
}
var deadline = timestamp.LocalDateTime.Date.Add(readyByTime);
if (deadline < timestamp.LocalDateTime)
{
deadline = deadline.AddDays(1);
}
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
return new BoilerConfig
{
IntervalCount = intervalCount,
PriceCap = priceCap,
Deadline = deadline,
SkipPriceCap = skipPriceCap
};
}
private NordPoolPrice BuildNordPoolPriceFromHistory(DateTimeOffset timestamp)
{
var nordPoolSensorEntries = _timeline.GetEntityHistory("sensor.nordpool_kwh_lt_eur_3_10_0");
var todayDate = timestamp.LocalDateTime.Date;
var todayPrices = nordPoolSensorEntries
.Where(e => e.LastChanged.LocalDateTime.Date == todayDate)
.Where(e => e.State is not null && double.TryParse(e.State, CultureInfo.InvariantCulture, out _))
.Select(e => new NordPoolDayPrice
{
Start = e.LastChanged.LocalDateTime,
End = e.LastChanged.LocalDateTime.AddMinutes(NordPoolConsts.MinutesPerInterval),
Price = double.Parse(e.State!, CultureInfo.InvariantCulture)
})
.ToList();
return new NordPoolPrice { Prices = todayPrices };
}
}
@@ -0,0 +1,158 @@
using System.Globalization;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPool.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class PowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IOtherPowerCalculationService _calculationService;
private readonly IPowerCostCalculationService _costService;
private readonly ILogger<PowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly PowerMonitorOptions _powerOptions;
public string MonitorName => "Power";
public PowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IOtherPowerCalculationService calculationService,
IPowerCostCalculationService costService,
ILogger<PowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<PowerMonitorOptions> powerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_calculationService = calculationService;
_costService = costService;
_logger = logger;
_replayOptions = replayOptions.Value;
_powerOptions = powerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Power replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(_powerOptions.PollIntervalSeconds);
DateTime? anomalyStartTime = null;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var mainMeterEntry = _timeline.GetStateAt(_powerOptions.MainMeterEntityId, currentTime);
var totalPower = ParseDouble(mainMeterEntry?.State);
if (!totalPower.HasValue)
{
currentTime = currentTime.Add(pollInterval);
continue;
}
var deviceReadings = DiscoverAndReadDevicePower(currentTime);
var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings);
var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0;
_costService.RecordCosts(calculation, nordPoolPrice, _powerOptions.PollIntervalSeconds, currentTime.LocalDateTime);
var isAnomaly = calculation.SmoothedOtherPowerWatts > _powerOptions.AnomalyThresholdWatts;
if (isAnomaly && anomalyStartTime is null)
{
anomalyStartTime = currentTime.LocalDateTime;
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Anomaly,
Message = $"Other power {calculation.SmoothedOtherPowerWatts:F0}W exceeds threshold {_powerOptions.AnomalyThresholdWatts}W",
Details = $"Total: {calculation.TotalPowerWatts:F0}W, Known: {calculation.KnownDevicesSumWatts:F0}W"
});
}
else if (!isAnomaly && anomalyStartTime is not null)
{
var duration = currentTime.LocalDateTime - anomalyStartTime.Value;
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Anomaly resolved after {duration:mm\\:ss}"
});
anomalyStartTime = null;
}
currentTime = currentTime.Add(pollInterval);
}
var totalCost = _costService.GetTotalCostSnapshot();
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: Total daily cost {totalCost.CostDaily:F4} EUR"
});
_logger.LogInformation("Power replay complete");
return Task.CompletedTask;
}
private IReadOnlyDictionary<string, double> DiscoverAndReadDevicePower(DateTimeOffset timestamp)
{
var readings = new Dictionary<string, double>();
var allEntities = _timeline.GetEntityIds();
foreach (var entityId in allEntities)
{
if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) ||
!entityId.EndsWith("_power", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (string.Equals(entityId, _powerOptions.MainMeterEntityId, StringComparison.OrdinalIgnoreCase))
{
continue;
}
var entry = _timeline.GetStateAt(entityId, timestamp);
var value = ParseDouble(entry?.State);
if (value.HasValue)
{
readings[entityId] = value.Value;
}
}
return readings;
}
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -0,0 +1,126 @@
using System.Globalization;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class ShowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IShowerDetectionService _detectionService;
private readonly IExhaustFanControlService _fanControlService;
private readonly ILogger<ShowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly ShowerMonitorOptions _showerOptions;
public string MonitorName => "Shower";
public ShowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IShowerDetectionService detectionService,
IExhaustFanControlService fanControlService,
ILogger<ShowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<ShowerMonitorOptions> showerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_detectionService = detectionService;
_fanControlService = fanControlService;
_logger = logger;
_replayOptions = replayOptions.Value;
_showerOptions = showerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Shower replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(_showerOptions.PollIntervalSeconds);
var previousState = ShowerState.Idle;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var bathroomEntry = _timeline.GetStateAt(_showerOptions.BathroomHumidityEntityId, currentTime);
var homeEntry = _timeline.GetStateAt(_showerOptions.MainHomeHumidityEntityId, currentTime);
var bathroomHumidity = ParseDouble(bathroomEntry?.State);
var homeHumidity = ParseDouble(homeEntry?.State);
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
{
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
var differential = bathroomHumidity.Value - homeHumidity.Value;
_fanControlService.Evaluate(state, currentTime);
if (state != previousState)
{
var eventType = state switch
{
ShowerState.Active => ReplayEventType.Decision,
ShowerState.Completed => ReplayEventType.StateChange,
_ => ReplayEventType.Info
};
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = eventType,
Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
Details = GetStateChangeDetails(state)
});
previousState = state;
}
}
currentTime = currentTime.Add(pollInterval);
}
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: {_detectionService.TodaySessionCount} session(s) detected"
});
_logger.LogInformation("Shower replay complete");
return Task.CompletedTask;
}
private string? GetStateChangeDetails(ShowerState state) =>
state switch
{
ShowerState.Completed when _detectionService.LastCompletedSession is not null =>
$"Duration: {_detectionService.LastCompletedSession.Duration:mm\\:ss}, Peak humidity: {_detectionService.LastCompletedSession.PeakHumidity:F1}%",
_ => null
};
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -0,0 +1,57 @@
{
"HomeAssistant": {
"Host": "homeassistant.local",
"Port": 8123,
"Token": "<your-long-lived-access-token>",
"Ssl": false
},
"Replay": {
"StartTime": "2026-03-30T00:00:00+02:00",
"EndTime": "2026-03-31T00:00:00+02:00",
"Monitors": {
"NordPool": true,
"Boiler": true,
"Shower": true,
"Power": false,
"Light": true
}
},
"BoilerMonitor": {
"Enabled": true,
"CleanupEntitiesOnStartup": false
},
"ShowerMonitor": {
"Enabled": true,
"CleanupEntitiesOnStartup": false,
"BathroomHumidityEntityId": "sensor.bathroom_humidity",
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
"ExhaustFanEntityId": "switch.exhaust_fan",
"PollIntervalSeconds": 30,
"SpikeRateThreshold": 4.0,
"MinDifferentialHumidity": 8.0,
"PeakHumidityThreshold": 58.0,
"ConfirmationWindowMinutes": 2,
"RecoveryDifferentialThreshold": 5.0,
"MaxShowerDurationMinutes": 60,
"FanRunAfterShowerMinutes": 10,
"RateWindowSize": 5
},
"LightMonitor": {
"Enabled": true,
"LightEntityId": "light.sonoff_1002214d40",
"SunEntityId": "sun.sun",
"PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"]
},
"PowerMonitor": {
"Enabled": false,
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
"PollIntervalSeconds": 1,
"SmoothingWindowSize": 10,
"AnomalyThresholdWatts": 500,
"ExcludedSensorPatterns": [
"sensor.nordpool_*",
"sensor.powermonitor_*"
]
}
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HomeAssistant.McpServer</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
</ItemGroup>
</Project>
+25
View File
@@ -0,0 +1,25 @@
using HomeAssistant.McpServer.Services;
using HomeAssistant.McpServer.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options =>
{
options.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.Configure<HomeAssistantSettings>(
builder.Configuration.GetSection(HomeAssistantSettings.SectionName))
.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
@@ -0,0 +1,107 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HomeAssistant.McpServer.Settings;
using Microsoft.Extensions.Options;
namespace HomeAssistant.McpServer.Services;
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
{
private readonly HttpClient _httpClient;
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
{
_httpClient = httpClient;
_httpClient.BaseAddress = settings.Value.BaseUrl;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
}
public Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/", cancellationToken);
public Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/config", cancellationToken);
public Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/states", cancellationToken);
public Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default) =>
GetJsonAsync($"/api/states/{Uri.EscapeDataString(entityId)}", cancellationToken);
public Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/services", cancellationToken);
public Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
if (endTime.HasValue)
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
if (minimalResponse)
path += "&minimal_response";
return GetJsonAsync(path, cancellationToken);
}
public Task<JsonElement> GetLogbookAsync(
string? entityId = null,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
var path = $"/api/logbook/{start:O}";
var queryParts = new List<string>();
if (!string.IsNullOrWhiteSpace(entityId))
queryParts.Add($"entity={Uri.EscapeDataString(entityId)}");
if (endTime.HasValue)
queryParts.Add($"end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}");
if (queryParts.Count > 0)
path += "?" + string.Join("&", queryParts);
return GetJsonAsync(path, cancellationToken);
}
public async Task<JsonElement> CallServiceAsync(
string domain,
string service,
JsonElement? serviceData = null,
CancellationToken cancellationToken = default)
{
var url = $"/api/services/{Uri.EscapeDataString(domain)}/{Uri.EscapeDataString(service)}";
var content = serviceData.HasValue
? JsonContent.Create(serviceData.Value)
: JsonContent.Create(new { });
var response = await _httpClient.PostAsync(url, content, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return doc.RootElement.Clone();
}
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return doc.RootElement.Clone();
}
}
@@ -0,0 +1,31 @@
using System.Text.Json;
namespace HomeAssistant.McpServer.Services;
public interface IHomeAssistantApiClient
{
Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default);
Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default);
Task<JsonElement> GetLogbookAsync(
string? entityId = null,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
CancellationToken cancellationToken = default);
Task<JsonElement> CallServiceAsync(
string domain,
string service,
JsonElement? serviceData = null,
CancellationToken cancellationToken = default);
}
@@ -0,0 +1,15 @@
namespace HomeAssistant.McpServer.Settings;
public sealed class HomeAssistantSettings
{
public const string SectionName = "HomeAssistant";
public const int DefaultPort = 8123;
public const int DefaultTimeoutSeconds = 30;
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = DefaultPort;
public string Token { get; set; } = string.Empty;
public bool Ssl { get; set; }
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
}
@@ -0,0 +1,98 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class EntityStateTools
{
private readonly IHomeAssistantApiClient _client;
public EntityStateTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get the current state and attributes of a single Home Assistant entity. " +
"Provide the full entity_id, e.g. 'sensor.nordpool_kwh_lt_eur_3_10_0' or 'switch.boiler'.")]
public async Task<string> GetEntityState(
[Description("Full entity ID, e.g. 'sensor.temperature' or 'light.living_room'")] string entityId,
CancellationToken cancellationToken = default)
{
var result = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
return FormatJson(result);
}
[McpServerTool, Description(
"Get the current states of all Home Assistant entities. " +
"Optionally filter by domain (e.g. 'sensor', 'switch', 'climate', 'light'). " +
"Returns entity_id, state, and key attributes for each entity.")]
public async Task<string> GetAllStates(
[Description("Optional domain filter, e.g. 'sensor', 'switch', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
return FormatJson(allStates);
var filtered = allStates.EnumerateArray()
.Where(e => e.TryGetProperty("entity_id", out var eid) &&
eid.GetString()?.StartsWith(domain + ".", StringComparison.OrdinalIgnoreCase) == true)
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Search Home Assistant entities by partial match on entity_id or friendly_name. " +
"Useful for discovering entities related to a topic (e.g. 'nordpool', 'boiler', 'temperature').")]
public async Task<string> SearchEntities(
[Description("Search term to match against entity_id or friendly_name")] string query,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
var matches = allStates.EnumerateArray()
.Where(e => MatchesQuery(e, query))
.Select(e => new
{
entity_id = e.GetProperty("entity_id").GetString(),
state = e.GetProperty("state").GetString(),
friendly_name = e.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn)
? fn.GetString()
: null
})
.ToList();
return JsonSerializer.Serialize(matches, SerializerOptions);
}
private static bool MatchesQuery(JsonElement entity, string query)
{
var q = query.ToUpperInvariant();
if (entity.TryGetProperty("entity_id", out var eid) &&
(eid.GetString()?.ToUpperInvariant().Contains(q) ?? false))
return true;
if (entity.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn) &&
(fn.GetString()?.ToUpperInvariant().Contains(q) ?? false))
return true;
return false;
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -0,0 +1,46 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class HistoryTools
{
private readonly IHomeAssistantApiClient _client;
public HistoryTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get state history for one or more Home Assistant entities over a time period. " +
"Returns timestamped state changes. Useful for debugging sensor readings, switch toggling, price changes, etc.")]
public async Task<string> GetEntityHistory(
[Description("Comma-separated entity IDs, e.g. 'sensor.temperature,sensor.humidity'")] string entityIds,
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago. Example: '2026-03-30T00:00:00'")] string? startTime = null,
[Description("End time in ISO 8601 format. Defaults to now. Example: '2026-03-31T00:00:00'")] string? endTime = null,
[Description("If true, returns minimal data (state + last_changed only). Defaults to true.")] bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
? null
: DateTimeOffset.Parse(startTime);
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
? null
: DateTimeOffset.Parse(endTime);
var result = await _client.GetHistoryAsync(entityIds, start, end, minimalResponse, cancellationToken)
.ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -0,0 +1,45 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class LogbookTools
{
private readonly IHomeAssistantApiClient _client;
public LogbookTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get Home Assistant logbook entries. Shows state changes and events for entities. " +
"Useful for understanding what happened and when. Filter by entity and/or time range.")]
public async Task<string> GetLogbook(
[Description("Optional entity ID to filter, e.g. 'switch.boiler'. Leave empty for all.")] string? entityId = null,
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago.")] string? startTime = null,
[Description("End time in ISO 8601 format. Defaults to now.")] string? endTime = null,
CancellationToken cancellationToken = default)
{
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
? null
: DateTimeOffset.Parse(startTime);
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
? null
: DateTimeOffset.Parse(endTime);
var result = await _client.GetLogbookAsync(entityId, start, end, cancellationToken)
.ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -0,0 +1,75 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class ServiceTools
{
private readonly IHomeAssistantApiClient _client;
public ServiceTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"List available Home Assistant services. Optionally filter by domain (e.g. 'light', 'climate', 'switch'). " +
"Each service shows its domain and available service names.")]
public async Task<string> ListServices(
[Description("Optional domain filter, e.g. 'light', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allServices = await _client.GetServicesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
return FormatJson(allServices);
var filtered = allServices.EnumerateArray()
.Where(s => s.TryGetProperty("domain", out var d) &&
string.Equals(d.GetString(), domain, StringComparison.OrdinalIgnoreCase))
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Call a Home Assistant service. Examples: domain='light', service='turn_on', entityId='light.living_room'. " +
"For services requiring extra data, pass it as a JSON string in serviceData.")]
public async Task<string> CallService(
[Description("Service domain, e.g. 'light', 'climate', 'switch', 'input_boolean'")] string domain,
[Description("Service name, e.g. 'turn_on', 'turn_off', 'set_temperature'")] string service,
[Description("Optional target entity ID, e.g. 'light.living_room'")] string? entityId = null,
[Description("Optional JSON service data, e.g. '{\"brightness\": 255}' or '{\"temperature\": 22}'")] string? serviceData = null,
CancellationToken cancellationToken = default)
{
JsonElement? data = null;
if (!string.IsNullOrWhiteSpace(serviceData) || !string.IsNullOrWhiteSpace(entityId))
{
var dataDict = string.IsNullOrWhiteSpace(serviceData)
? new Dictionary<string, object>()
: JsonSerializer.Deserialize<Dictionary<string, object>>(serviceData) ?? [];
if (!string.IsNullOrWhiteSpace(entityId))
dataDict["entity_id"] = entityId;
data = JsonSerializer.SerializeToElement(dataDict);
}
var result = await _client.CallServiceAsync(domain, service, data, cancellationToken)
.ConfigureAwait(false);
return FormatJson(result);
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -0,0 +1,52 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class SystemTools
{
private readonly IHomeAssistantApiClient _client;
public SystemTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get Home Assistant configuration including version, location, components, and unit system. " +
"Useful for understanding the HA environment.")]
public async Task<string> GetHaConfig(CancellationToken cancellationToken = default)
{
var result = await _client.GetConfigAsync(cancellationToken).ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
[McpServerTool, Description(
"Check if the Home Assistant API is reachable and responding. " +
"Returns the API status message or an error description.")]
public async Task<string> CheckApi(CancellationToken cancellationToken = default)
{
try
{
var result = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
catch (HttpRequestException ex)
{
return JsonSerializer.Serialize(new { status = "error", message = ex.Message }, SerializerOptions);
}
catch (TaskCanceledException)
{
return JsonSerializer.Serialize(
new { status = "error", message = "Request timed out - HA may be unreachable" }, SerializerOptions);
}
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
@@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
</ItemGroup>
</Project>
@@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"netdaemon.hassmodel.codegen": {
"version": "26.3.0",
"version": "26.11.0",
"commands": [
"nd-codegen"
],
@@ -34,13 +34,13 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
<PackageReference Include="NetDaemon.Runtime" Version="26.3.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
<PackageReference Include="NetDaemon.Client" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.3.0" />
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
</ItemGroup>
<ItemGroup>
@@ -52,5 +52,11 @@
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
</ItemGroup>
</Project>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+31 -1
View File
@@ -6,7 +6,10 @@
"System.Net.Http.HttpClient": "Warning",
"NordPoolManager": "Information",
"PowerMonitorManager": "Information",
"BoilerMonitorManager": "Information"
"BoilerMonitorManager": "Information",
"ShowerMonitorManager": "Information",
"LightMonitorManager": "Information",
"BatteryMonitorManager": "Information"
}
},
"WriteTo": [
@@ -34,6 +37,33 @@
"Enabled": true,
"CleanupEntitiesOnStartup": false
},
"ShowerMonitor": {
"Enabled": true,
"CleanupEntitiesOnStartup": false,
"BathroomHumidityEntityId": "sensor.bathroom_humidity",
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
"ExhaustFanEntityId": "switch.exhaust_fan",
"PollIntervalSeconds": 30,
"SpikeRateThreshold": 4.0,
"MinDifferentialHumidity": 8.0,
"PeakHumidityThreshold": 58.0,
"ConfirmationWindowMinutes": 2,
"RecoveryDifferentialThreshold": 5.0,
"MaxShowerDurationMinutes": 60,
"FanRunAfterShowerMinutes": 10,
"RateWindowSize": 5
},
"LightMonitor": {
"Enabled": true,
"LightEntityId": "light.sonoff_1002214d40",
"SunEntityId": "sun.sun",
"PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"]
},
"BatteryMonitor": {
"Enabled": true,
"BatteryThresholdPercent": 5
},
"PowerMonitor": {
"Enabled": false,
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
+12
View File
@@ -19,6 +19,12 @@ using NordPoolManager.Interface;
using NordPoolManager.Models;
using PowerMonitorManager;
using PowerMonitorManager.Models;
using ShowerMonitorManager;
using ShowerMonitorManager.Models;
using LightMonitorManager;
using LightMonitorManager.Models;
using BatteryMonitorManager;
using BatteryMonitorManager.Models;
#pragma warning disable CA1812
@@ -53,6 +59,12 @@ try
.AddPowerMonitor(context.Configuration)
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
.AddBoilerMonitor(context.Configuration)
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
.AddShowerMonitor(context.Configuration)
.Configure<LightMonitorOptions>(context.Configuration.GetSection(LightMonitorOptions.SectionName))
.AddLightMonitor(context.Configuration)
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
.AddBatteryMonitor(context.Configuration)
)
.Build()
.RunAsync()
+160 -4
View File
@@ -30,6 +30,28 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E9
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.McpServer", "HomeAssistant.McpServer\HomeAssistant.McpServer.csproj", "{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Models", "ShowerMonitor.Models\ShowerMonitor.Models.csproj", "{DAD0BDF9-2A6D-48AD-B714-38D237E97285}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager", "ShowerMonitor.Manager\ShowerMonitor.Manager.csproj", "{8D05B406-B94B-4D6B-8221-831485AF6702}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager.Tests", "ShowerMonitor.Manager.Tests\ShowerMonitor.Manager.Tests.csproj", "{A9DFB47D-7736-428C-9459-22AFC5CF3A38}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Models", "LightMonitor.Models\LightMonitor.Models.csproj", "{B14E51EB-7D5C-44FA-8674-4B4796459978}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager", "LightMonitor.Manager\LightMonitor.Manager.csproj", "{9165EDEF-2FE2-4578-849B-B4D4089416DA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.HistoryReplay", "HomeAssistant.HistoryReplay\HomeAssistant.HistoryReplay.csproj", "{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Models", "BatteryMonitor.Models\BatteryMonitor.Models.csproj", "{2D27B621-7B92-4014-8FDF-6AD376C97612}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "BatteryMonitor.Manager\BatteryMonitor.Manager.csproj", "{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager.Tests", "BatteryMonitor.Manager.Tests\BatteryMonitor.Manager.Tests.csproj", "{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -196,17 +218,151 @@ Global
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.Build.0 = Release|Any CPU
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.ActiveCfg = Release|Any CPU
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.Build.0 = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x64.ActiveCfg = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x64.Build.0 = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x86.ActiveCfg = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x86.Build.0 = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|Any CPU.Build.0 = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x64.ActiveCfg = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x64.Build.0 = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x86.ActiveCfg = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x86.Build.0 = Release|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.ActiveCfg = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.Build.0 = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x86.ActiveCfg = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x86.Build.0 = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|Any CPU.Build.0 = Release|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x64.ActiveCfg = Release|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x64.Build.0 = Release|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x86.ActiveCfg = Release|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x86.Build.0 = Release|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x64.ActiveCfg = Debug|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x64.Build.0 = Debug|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x86.ActiveCfg = Debug|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x86.Build.0 = Debug|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|Any CPU.Build.0 = Release|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x64.ActiveCfg = Release|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x64.Build.0 = Release|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x86.ActiveCfg = Release|Any CPU
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x86.Build.0 = Release|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x64.ActiveCfg = Debug|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x64.Build.0 = Debug|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x86.ActiveCfg = Debug|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x86.Build.0 = Debug|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|Any CPU.Build.0 = Release|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x64.ActiveCfg = Release|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x64.Build.0 = Release|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x86.ActiveCfg = Release|Any CPU
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x86.Build.0 = Release|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x64.ActiveCfg = Debug|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x64.Build.0 = Debug|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x86.ActiveCfg = Debug|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x86.Build.0 = Debug|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|Any CPU.Build.0 = Release|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x64.ActiveCfg = Release|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x64.Build.0 = Release|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x86.ActiveCfg = Release|Any CPU
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x86.Build.0 = Release|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x64.ActiveCfg = Debug|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x64.Build.0 = Debug|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x86.ActiveCfg = Debug|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x86.Build.0 = Debug|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|Any CPU.Build.0 = Release|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x64.ActiveCfg = Release|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x64.Build.0 = Release|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x86.ActiveCfg = Release|Any CPU
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x86.Build.0 = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x64.ActiveCfg = Debug|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x64.Build.0 = Debug|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x86.ActiveCfg = Debug|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x86.Build.0 = Debug|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|Any CPU.Build.0 = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.ActiveCfg = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.Build.0 = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.ActiveCfg = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.Build.0 = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.ActiveCfg = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.Build.0 = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.ActiveCfg = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.Build.0 = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.Build.0 = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.ActiveCfg = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.Build.0 = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.ActiveCfg = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.Build.0 = Release|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.Build.0 = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x86.ActiveCfg = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x86.Build.0 = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|Any CPU.Build.0 = Release|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x64.ActiveCfg = Release|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x64.Build.0 = Release|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x86.ActiveCfg = Release|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x86.Build.0 = Release|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x64.ActiveCfg = Debug|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x64.Build.0 = Debug|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x86.ActiveCfg = Debug|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x86.Build.0 = Debug|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|Any CPU.Build.0 = Release|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x64.ActiveCfg = Release|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x64.Build.0 = Release|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x86.ActiveCfg = Release|Any CPU
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x86.Build.0 = Release|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x64.ActiveCfg = Debug|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x64.Build.0 = Debug|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x86.ActiveCfg = Debug|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x86.Build.0 = Debug|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|Any CPU.Build.0 = Release|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x64.ActiveCfg = Release|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x64.Build.0 = Release|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x86.ActiveCfg = Release|Any CPU
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F}
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C} = {95E98121-7DA4-4085-A8E3-B0430628452F}
{1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F}
{D1FDF2F0-E8D2-4F00-95CA-1759047EA205} = {48492269-2B47-43FE-BC14-A901054EE5AE}
{D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E} = {48492269-2B47-43FE-BC14-A901054EE5AE}
{D1FDF2F0-E8D2-4F00-95CA-1759047EA205} = {48492269-2B47-43FE-BC14-A901054EE5AE}
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C} = {95E98121-7DA4-4085-A8E3-B0430628452F}
{2C0E9D45-3E34-4A60-A6B5-1E89B935419D} = {48492269-2B47-43FE-BC14-A901054EE5AE}
{1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F}
{72331F53-884D-42A1-8EEA-8CC83FFAB623} = {48492269-2B47-43FE-BC14-A901054EE5AE}
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F}
{B14E51EB-7D5C-44FA-8674-4B4796459978} = {48492269-2B47-43FE-BC14-A901054EE5AE}
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92} = {95E98121-7DA4-4085-A8E3-B0430628452F}
EndGlobalSection
EndGlobal
@@ -0,0 +1,117 @@
using FluentAssertions;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using LightMonitorManager;
using LightMonitorManager.Models;
namespace LightMonitor.Manager.Tests;
public class LightControlServiceTests
{
private const string LightEntityId = "light.sonoff_1002214d40";
private const string SunEntityId = "sun.sun";
private readonly LightMonitorOptions _defaultOptions = new()
{
LightEntityId = LightEntityId,
SunEntityId = SunEntityId
};
private readonly Mock<IHaContext> _haContextMock = new();
private LightControlService CreateService(LightMonitorOptions? options = null)
{
return new LightControlService(
_haContextMock.Object,
Mock.Of<ILogger<LightControlService>>(),
Options.Create(options ?? _defaultOptions));
}
[Fact]
public void TurnOnLight_WhenDarkAndLightIsOff_ShouldTurnOnLight()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon });
_haContextMock.Setup(x => x.GetState(LightEntityId))
.Returns(new EntityState { State = "off" });
var service = CreateService();
service.TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
}
[Fact]
public void TurnOnLight_WhenDarkAndLightIsAlreadyOn_ShouldNotCallService()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon });
_haContextMock.Setup(x => x.GetState(LightEntityId))
.Returns(new EntityState { State = "on" });
var service = CreateService();
service.TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
[Fact]
public void TurnOnLight_WhenSunIsAboveHorizon_ShouldNotTurnOnLight()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunAboveHorizon });
var service = CreateService();
service.TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
[Fact]
public void TurnOnLight_WhenSunStateIsNull_ShouldNotTurnOnLight()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns((EntityState?)null);
var service = CreateService();
service.TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
[Fact]
public void TurnOnLight_WhenSunStateIsUnavailable_ShouldNotTurnOnLight()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = "unavailable" });
var service = CreateService();
service.TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
[Fact]
public void TurnOnLight_WhenLightStateIsNull_ShouldTurnOnLight()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon });
_haContextMock.Setup(x => x.GetState(LightEntityId))
.Returns((EntityState?)null);
var service = CreateService();
service.TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
}
}
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,146 @@
using FluentAssertions;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using LightMonitorManager;
using LightMonitorManager.Models;
namespace LightMonitor.Manager.Tests;
public class PresenceServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly LightMonitorOptions _defaultOptions = new()
{
PersonEntityIds = ["person.marius", "person.erika", "person.home_phone"]
};
private PresenceService CreateService(LightMonitorOptions? options = null)
{
return new PresenceService(
_haContextMock.Object,
Mock.Of<ILogger<PresenceService>>(),
Options.Create(options ?? _defaultOptions));
}
[Fact]
public void IsAnyoneHome_WhenOnePersonIsHome_ShouldReturnTrue()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "not_home" });
var service = CreateService();
service.IsAnyoneHome().Should().BeTrue();
}
[Fact]
public void IsAnyoneHome_WhenAllPersonsAreHome_ShouldReturnTrue()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "home" });
var service = CreateService();
service.IsAnyoneHome().Should().BeTrue();
}
[Fact]
public void IsAnyoneHome_WhenNoPersonIsHome_ShouldReturnFalse()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "not_home" });
var service = CreateService();
service.IsAnyoneHome().Should().BeFalse();
}
[Fact]
public void IsAnyoneHome_WhenStateIsUnavailable_ShouldSkipAndReturnFalse()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "unavailable" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "unknown" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns((EntityState?)null);
var service = CreateService();
service.IsAnyoneHome().Should().BeFalse();
}
[Fact]
public void IsAnyoneHome_WhenStateIsNull_ShouldSkipAndReturnFalse()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns((EntityState?)null);
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns((EntityState?)null);
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns((EntityState?)null);
var service = CreateService();
service.IsAnyoneHome().Should().BeFalse();
}
[Fact]
public void IsAnyoneHome_WhenMixedStatesWithOneHome_ShouldReturnTrue()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "unavailable" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns((EntityState?)null);
var service = CreateService();
service.IsAnyoneHome().Should().BeTrue();
}
[Theory]
[InlineData("HOME")]
[InlineData("Home")]
[InlineData("home")]
public void IsAnyoneHome_CaseInsensitiveHomeState_ShouldReturnTrue(string homeState)
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = homeState });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "not_home" });
var service = CreateService();
service.IsAnyoneHome().Should().BeTrue();
}
[Fact]
public void IsAnyoneHome_WithEmptyPersonList_ShouldReturnFalse()
{
var options = new LightMonitorOptions { PersonEntityIds = [] };
var service = CreateService(options);
service.IsAnyoneHome().Should().BeFalse();
}
}
@@ -0,0 +1,6 @@
namespace LightMonitorManager.Interface;
public interface ILightControlService
{
void TurnOnLight();
}
@@ -0,0 +1,6 @@
namespace LightMonitorManager.Interface;
public interface ILightMonitorInit
{
Task InitializeAsync();
}
@@ -0,0 +1,6 @@
namespace LightMonitorManager.Interface;
public interface IPresenceService
{
bool IsAnyoneHome();
}
@@ -0,0 +1,48 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using LightMonitor.Models;
using LightMonitorManager.Interface;
using LightMonitorManager.Models;
namespace LightMonitorManager;
public sealed class LightControlService : ILightControlService
{
private readonly IHaContext _haContext;
private readonly ILogger<LightControlService> _logger;
private readonly LightMonitorOptions _options;
public LightControlService(
IHaContext haContext,
ILogger<LightControlService> logger,
IOptions<LightMonitorOptions> options)
{
_haContext = haContext;
_logger = logger;
_options = options.Value;
}
public void TurnOnLight()
{
var sunState = _haContext.GetState(_options.SunEntityId)?.State;
if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{
_logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState);
return;
}
var lightState = _haContext.GetState(_options.LightEntityId)?.State;
if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase))
{
_logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId);
return;
}
_haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId));
_logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId);
}
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>LightMonitorManager</RootNamespace>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>LightMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
</ItemGroup>
</Project>
+105
View File
@@ -0,0 +1,105 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.AppModel;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using LightMonitor.Models;
using LightMonitorManager.Interface;
using LightMonitorManager.Models;
namespace LightMonitorManager;
[NetDaemonApp]
public sealed class LightMonitorInit : ILightMonitorInit
{
private readonly IHaContext _haContext;
private readonly ILogger<LightMonitorInit> _logger;
private readonly IPresenceService _presenceService;
private readonly ILightControlService _lightControlService;
private readonly LightMonitorOptions _options;
public LightMonitorInit(
IHaContext haContext,
ILogger<LightMonitorInit> logger,
IPresenceService presenceService,
ILightControlService lightControlService,
IOptions<LightMonitorOptions> options)
{
_haContext = haContext;
_logger = logger;
_presenceService = presenceService;
_lightControlService = lightControlService;
_options = options.Value;
_ = InitializeAsync();
}
public Task InitializeAsync()
{
try
{
SubscribeToSunStateChanges();
SubscribeToPersonStateChanges();
_logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", _options.PersonEntityIds.Length);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during LightMonitor initialization");
}
return Task.CompletedTask;
}
private void SubscribeToSunStateChanges()
{
var sunEntity = new Entity(_haContext, _options.SunEntityId);
sunEntity.StateChanges()
.Subscribe(e =>
{
try
{
if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{
return;
}
_logger.LogInformation("Sun went below horizon, checking if anyone is home");
if (_presenceService.IsAnyoneHome())
{
_lightControlService.TurnOnLight();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling sun state change");
}
});
}
private void SubscribeToPersonStateChanges()
{
foreach (var personEntityId in _options.PersonEntityIds)
{
var personEntity = new Entity(_haContext, personEntityId);
personEntity.StateChanges()
.Subscribe(e =>
{
try
{
if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
return;
}
_logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId);
_lightControlService.TurnOnLight();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId);
}
});
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
using LightMonitorManager.Interface;
using LightMonitorManager.Models;
namespace LightMonitorManager;
public static class LightMonitorServiceRegistration
{
public static IServiceCollection AddLightMonitor(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration
.GetSection(LightMonitorOptions.SectionName)
.Get<LightMonitorOptions>() ?? new LightMonitorOptions();
if (!options.Enabled)
{
return services;
}
services
.AddNetDaemonApp<LightMonitorInit>()
.AddScoped<IPresenceService, PresenceService>()
.AddScoped<ILightControlService, LightControlService>();
return services;
}
}
@@ -0,0 +1,13 @@
using static LightMonitor.Models.LightMonitorConsts;
namespace LightMonitorManager.Models;
public sealed class LightMonitorOptions
{
public const string SectionName = "LightMonitor";
public bool Enabled { get; set; }
public string LightEntityId { get; set; } = DefaultLightEntityId;
public string SunEntityId { get; set; } = DefaultSunEntityId;
public string[] PersonEntityIds { get; set; } = DefaultPersonEntityIds;
}
+48
View File
@@ -0,0 +1,48 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using LightMonitor.Models;
using LightMonitorManager.Interface;
using LightMonitorManager.Models;
namespace LightMonitorManager;
public sealed class PresenceService : IPresenceService
{
private readonly IHaContext _haContext;
private readonly ILogger<PresenceService> _logger;
private readonly LightMonitorOptions _options;
public PresenceService(
IHaContext haContext,
ILogger<PresenceService> logger,
IOptions<LightMonitorOptions> options)
{
_haContext = haContext;
_logger = logger;
_options = options.Value;
}
public bool IsAnyoneHome()
{
foreach (var personEntityId in _options.PersonEntityIds)
{
var state = _haContext.GetState(personEntityId);
if (state?.State is null or "unavailable" or "unknown")
{
_logger.LogDebug("Person entity {EntityId} state unavailable", personEntityId);
continue;
}
if (string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
_logger.LogDebug("Person {EntityId} is home", personEntityId);
return true;
}
}
_logger.LogDebug("No person is currently home");
return false;
}
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>LightMonitor.Models</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
</ItemGroup>
</Project>
+19
View File
@@ -0,0 +1,19 @@
namespace LightMonitor.Models;
public static class LightMonitorConsts
{
public const string DefaultLightEntityId = "light.sonoff_1002214d40";
public const string DefaultSunEntityId = "sun.sun";
public static readonly string[] DefaultPersonEntityIds =
[
"person.marius",
"person.erika",
"person.home_phone"
];
public const string SunBelowHorizon = "below_horizon";
public const string SunAboveHorizon = "above_horizon";
public const string PersonHomeState = "home";
public const string LightOnState = "on";
}
@@ -30,7 +30,7 @@ public class CheapestIntervalsFinderTests
{
Start = start,
End = start.AddMinutes(15),
Price = 5.0 + i * 0.5
Price = 4.93 + i * 0.22
});
}
@@ -61,7 +61,7 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesForDay(dayStart);
var deadline = dayStart.AddDays(1);
@@ -77,8 +77,8 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 15.0, 2.0, 8.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92, 5.63, 13.26);
var deadline = dayStart.AddDays(1);
// Act
@@ -87,9 +87,9 @@ public class CheapestIntervalsFinderTests
// Assert
result.Should().HaveCount(3);
var sortedByRank = result.OrderBy(r => r.Rank).ToList();
sortedByRank[0].Price.Should().Be(1.0);
sortedByRank[1].Price.Should().Be(2.0);
sortedByRank[2].Price.Should().Be(3.0);
sortedByRank[0].Price.Should().Be(4.93);
sortedByRank[1].Price.Should().Be(5.63);
sortedByRank[2].Price.Should().Be(6.20);
}
[Fact]
@@ -97,17 +97,17 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 5.0, 1.0, 8.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 8.96, 4.93, 13.26);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
// Assert
var cheapest = result.Single(r => r.Price == 1.0);
var cheapest = result.Single(r => r.Price == 4.93);
cheapest.Rank.Should().Be(1);
var secondCheapest = result.Single(r => r.Price == 5.0);
var secondCheapest = result.Single(r => r.Price == 8.96);
secondCheapest.Rank.Should().Be(2);
}
@@ -116,8 +116,8 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96);
var deadline = dayStart.AddDays(1);
// Act
@@ -132,8 +132,8 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 0.5, 0.1, 0.2);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50, 1.80, 3.20);
var deadline = dayStart.AddMinutes(75); // 1h15m = covers intervals 0-4 (end of interval 4 = 75min)
// Act
@@ -149,33 +149,33 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 15.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 10, 6.0, deadline);
var result = sut.FindCheapestIntervals(prices, 10, 10.0, deadline);
// Assert
result.Should().HaveCount(3);
result.Should().OnlyContain(r => r.Price <= 6.0);
result.Should().OnlyContain(r => r.Price <= 10.0);
}
[Fact]
public void FindCheapestIntervals_WithMaxPriceCap_ShouldIncludeAllIntervalsBeforeDeadline()
{
// Arrange: prices 10, 3, 7, 1, 5, 15 - with cap 6.0 only 3 would qualify; with double.MaxValue all qualify
// Arrange: realistic ct/kWh samples — with double.MaxValue all six intervals qualify
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 15.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
// Assert: all 6 intervals are eligible, we take 4 cheapest: 1, 3, 5, 7
// Assert: all 6 intervals are eligible, we take 4 cheapest by price
result.Should().HaveCount(4);
result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(1.0, 3.0, 5.0, 7.0);
result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(4.93, 6.20, 8.96, 12.50);
}
[Fact]
@@ -183,16 +183,16 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 0.5);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50);
var deadline = dayStart.AddMinutes(75);
// Act
var result = sut.FindCheapestIntervals(prices, 10, 6.0, deadline);
var result = sut.FindCheapestIntervals(prices, 2, 10.0, deadline);
// Assert
result.Should().HaveCount(3);
result.Should().OnlyContain(r => r.End <= deadline && r.Price <= 6.0);
result.Should().HaveCount(2);
result.Should().OnlyContain(r => r.End <= deadline && r.Price <= 10.0);
}
[Fact]
@@ -230,7 +230,7 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesForDay(dayStart);
var deadline = dayStart.AddDays(1);
@@ -246,7 +246,7 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesForDay(dayStart);
var deadline = dayStart.AddDays(1);
@@ -262,8 +262,8 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 3.0, 5.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 6.20, 8.96);
var deadline = dayStart.AddDays(1);
// Act
@@ -278,12 +278,12 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 20.0, 15.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 24.92, 22.44);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, 5.0, deadline);
var result = sut.FindCheapestIntervals(prices, 4, 10.0, deadline);
// Assert
result.Should().BeEmpty();
@@ -294,9 +294,9 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 12, 0, 0);
var prices = CreatePricesWithValues(dayStart, 1.0, 2.0, 3.0);
var deadline = new DateTime(2026, 2, 26, 10, 0, 0);
var dayStart = new DateTime(2026, 3, 31, 12, 0, 0);
var prices = CreatePricesWithValues(dayStart, 4.93, 5.63, 6.20);
var deadline = new DateTime(2026, 3, 31, 10, 0, 0);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
@@ -310,8 +310,8 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 5.0, 5.0, 5.0, 5.0, 5.0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 12.50, 12.50, 12.50, 12.50, 12.50);
var deadline = dayStart.AddDays(1);
// Act
@@ -319,7 +319,7 @@ public class CheapestIntervalsFinderTests
// Assert
result.Should().HaveCount(3);
result.Should().OnlyContain(r => r.Price == 5.0);
result.Should().OnlyContain(r => r.Price == 12.50);
}
[Fact]
@@ -327,16 +327,16 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = dayStart, End = dayStart.AddMinutes(15), Price = 5.0 },
new() { Start = dayStart, End = dayStart.AddMinutes(15), Price = 8.96 },
new() { Start = dayStart.AddMinutes(15), End = dayStart.AddMinutes(30), Price = null },
new() { Start = dayStart.AddMinutes(30), End = dayStart.AddMinutes(45), Price = 3.0 },
new() { Start = null, End = dayStart.AddMinutes(60), Price = 1.0 },
new() { Start = dayStart.AddMinutes(60), End = null, Price = 2.0 }
new() { Start = dayStart.AddMinutes(30), End = dayStart.AddMinutes(45), Price = 6.20 },
new() { Start = null, End = dayStart.AddMinutes(60), Price = 4.93 },
new() { Start = dayStart.AddMinutes(60), End = null, Price = 5.63 }
}
};
var deadline = dayStart.AddDays(1);
@@ -357,10 +357,10 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var now = new DateTime(2026, 2, 26, 10, 7, 0);
var now = new DateTime(2026, 3, 31, 10, 7, 0);
var intervals = new List<CheapestIntervalResult>
{
new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 }
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }
};
// Act
@@ -375,10 +375,10 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var now = new DateTime(2026, 2, 26, 10, 0, 0);
var now = new DateTime(2026, 3, 31, 10, 0, 0);
var intervals = new List<CheapestIntervalResult>
{
new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 }
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }
};
// Act
@@ -393,10 +393,10 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var now = new DateTime(2026, 2, 26, 10, 15, 0);
var now = new DateTime(2026, 3, 31, 10, 15, 0);
var intervals = new List<CheapestIntervalResult>
{
new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 }
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }
};
// Act
@@ -411,11 +411,11 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var now = new DateTime(2026, 2, 26, 12, 0, 0);
var now = new DateTime(2026, 3, 31, 12, 0, 0);
var intervals = new List<CheapestIntervalResult>
{
new() { Start = new DateTime(2026, 2, 26, 10, 0, 0), End = new DateTime(2026, 2, 26, 10, 15, 0), Price = 5.0, Rank = 1 },
new() { Start = new DateTime(2026, 2, 26, 14, 0, 0), End = new DateTime(2026, 2, 26, 14, 15, 0), Price = 3.0, Rank = 2 }
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 },
new() { Start = new DateTime(2026, 3, 31, 14, 0, 0), End = new DateTime(2026, 3, 31, 14, 15, 0), Price = 6.20, Rank = 2 }
};
// Act
@@ -9,7 +9,7 @@ public class CompactNordPoolDayPriceTests
{
private const int IntervalDurationSeconds = MinutesPerInterval * 60;
private static readonly DateTime TestStart = new(2026, 3, 19, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestStart = new(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval);
private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds();
private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds();
@@ -17,19 +17,19 @@ public class CompactNordPoolDayPriceTests
[Fact]
public void FromDayPrice_ShouldConvertDateTimesToUnixEpochSeconds()
{
var dayPrice = new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.35 };
var dayPrice = new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 17.91 };
var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice);
result.Start.Should().Be(TestStartEpoch);
result.End.Should().Be(TestEndEpoch);
result.Price.Should().Be(12.35);
result.Price.Should().Be(17.91);
}
[Fact]
public void FromDayPrice_WhenStartIsNull_ShouldUseZeroEpoch()
{
var dayPrice = new NordPoolDayPrice { Start = null, End = TestEnd, Price = 5.0 };
var dayPrice = new NordPoolDayPrice { Start = null, End = TestEnd, Price = 8.96 };
var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice);
@@ -40,7 +40,7 @@ public class CompactNordPoolDayPriceTests
[Fact]
public void FromDayPrice_WhenEndIsNull_ShouldUseZeroEpoch()
{
var dayPrice = new NordPoolDayPrice { Start = TestStart, End = null, Price = 5.0 };
var dayPrice = new NordPoolDayPrice { Start = TestStart, End = null, Price = 8.96 };
var result = CompactNordPoolDayPrice.FromDayPrice(dayPrice);
@@ -51,9 +51,9 @@ public class CompactNordPoolDayPriceTests
[Fact]
public void FromDayPrice_WhenDateTimeKindIsLocal_ShouldConvertToUtcWithoutThrowing()
{
var localStart = new DateTime(2026, 3, 19, 12, 0, 0, DateTimeKind.Local);
var localEnd = new DateTime(2026, 3, 19, 12, 15, 0, DateTimeKind.Local);
var dayPrice = new NordPoolDayPrice { Start = localStart, End = localEnd, Price = 10.0 };
var localStart = new DateTime(2026, 3, 31, 12, 0, 0, DateTimeKind.Local);
var localEnd = new DateTime(2026, 3, 31, 12, 15, 0, DateTimeKind.Local);
var dayPrice = new NordPoolDayPrice { Start = localStart, End = localEnd, Price = 12.50 };
var act = () => CompactNordPoolDayPrice.FromDayPrice(dayPrice);
@@ -66,9 +66,9 @@ public class CompactNordPoolDayPriceTests
[Fact]
public void FromDayPrice_WhenDateTimeKindIsUnspecified_ShouldConvertWithoutThrowing()
{
var unspecifiedStart = new DateTime(2026, 3, 19, 12, 0, 0, DateTimeKind.Unspecified);
var unspecifiedEnd = new DateTime(2026, 3, 19, 12, 15, 0, DateTimeKind.Unspecified);
var dayPrice = new NordPoolDayPrice { Start = unspecifiedStart, End = unspecifiedEnd, Price = 10.0 };
var unspecifiedStart = new DateTime(2026, 3, 31, 12, 0, 0, DateTimeKind.Unspecified);
var unspecifiedEnd = new DateTime(2026, 3, 31, 12, 15, 0, DateTimeKind.Unspecified);
var dayPrice = new NordPoolDayPrice { Start = unspecifiedStart, End = unspecifiedEnd, Price = 12.50 };
var act = () => CompactNordPoolDayPrice.FromDayPrice(dayPrice);
@@ -92,12 +92,12 @@ public class CompactNordPoolDayPriceTests
{
Start = TestStartEpoch,
End = TestEndEpoch,
Price = 12.35
Price = 17.91
};
var json = JsonSerializer.Serialize(compact);
json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},12.35]");
json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},17.91]");
}
[Fact]
@@ -122,7 +122,7 @@ public class CompactNordPoolDayPriceTests
{
Start = TestStartEpoch,
End = TestEndEpoch,
Price = 12.35
Price = 17.91
};
var json = JsonSerializer.Serialize(original);
@@ -138,13 +138,13 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<CompactNordPoolDayPrice>
{
new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 10.0 },
new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 11.0 }
new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
};
var json = JsonSerializer.Serialize(prices);
json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},10],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},11]]");
json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]");
}
[Fact]
@@ -184,16 +184,16 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<NordPoolDayPrice>
{
new() { Start = TestStart, End = TestEnd, Price = 10.0 },
new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 11.0 }
new() { Start = TestStart, End = TestEnd, Price = 12.50 },
new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
};
var result = prices.ToCompact();
result.Should().HaveCount(2);
result[0].Start.Should().Be(TestStartEpoch);
result[0].Price.Should().Be(10.0);
result[1].Price.Should().Be(11.0);
result[0].Price.Should().Be(12.50);
result[1].Price.Should().Be(13.26);
}
[Fact]
@@ -220,7 +220,7 @@ public class CompactNordPoolDayPriceTests
public void SerializedSize_WithMaxEntries_ShouldBeUnderHaAttributeLimit()
{
const int haAttributeByteLimitBytes = 16_384;
var dayStart = new DateTime(2026, 3, 19, 0, 0, 0, DateTimeKind.Utc);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < MaxExpectedPriceEntries; i++)
@@ -230,7 +230,7 @@ public class CompactNordPoolDayPriceTests
{
Start = start,
End = start.AddMinutes(MinutesPerInterval),
Price = 10.0 + i * 0.01
Price = 4.93 + i * 0.22
});
}
@@ -318,7 +318,7 @@ public class NordPoolEntityServiceTests
#region UpdateEntitiesAsync
private static EntityUpdateContext CreateDefaultContext(
double currentPrice = 12.5,
double currentPrice = 17.91,
NordPoolPrice? todayPrice = null,
NordPoolPrice? tomorrowPrice = null)
{
@@ -331,18 +331,18 @@ public class NordPoolEntityServiceTests
UsingCachedData = false,
TodayNordPoolPrice = todayPrice ?? new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 10.0 } }
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
},
TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 20.0 } }
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
},
CheapestIntervals = [],
ConfiguredHours = 1.0,
ConfiguredHours = 2.0,
ConfiguredIntervalCount = 4,
ConfiguredPriceCap = 100.0,
ConfiguredPriceCap = 25.0,
SkipPriceCap = false,
ConfiguredReadyBy = "06:00",
ConfiguredReadyBy = "18:00",
IsNowCheap = false,
NextCheapIntervalStart = null
};
@@ -364,7 +364,7 @@ public class NordPoolEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "12.50"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
@@ -421,21 +421,21 @@ public class NordPoolEntityServiceTests
public async Task UpdateEntitiesAsync_WithTodayAndTomorrowPrices_ShouldUpdateCombinedSensor()
{
// Arrange
var todayStart = new DateTime(2025, 3, 16, 6, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2025, 3, 17, 6, 0, 0, DateTimeKind.Utc);
var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc);
var todayPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 15.0 },
new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 10.0 }
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 12.50 }
]
};
var tomorrowPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 20.0 }
new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
@@ -467,7 +467,7 @@ public class NordPoolEntityServiceTests
// Arrange
var todayPrice = new NordPoolPrice
{
Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddMinutes(15), Price = 12.0 }]
Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddMinutes(15), Price = 17.91 }]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
@@ -496,7 +496,7 @@ public class NordPoolEntityServiceTests
// Arrange
var tomorrowPrice = new NordPoolPrice
{
Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow.AddDays(1), End = DateTime.UtcNow.AddDays(1).AddMinutes(15), Price = 18.0 }]
Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow.AddDays(1), End = DateTime.UtcNow.AddDays(1).AddMinutes(15), Price = 18.71 }]
};
var context = CreateDefaultContext(todayPrice: new NordPoolPrice { Prices = [] }, tomorrowPrice: tomorrowPrice);
@@ -527,9 +527,9 @@ public class NordPoolEntityServiceTests
{
Prices = [new NordPoolDayPrice
{
Start = new DateTime(2026, 3, 19, 10, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 19, 10, 15, 0, DateTimeKind.Utc),
Price = 12.0
Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc),
Price = 17.91
}]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
@@ -555,21 +555,21 @@ public class NordPoolEntityServiceTests
// Arrange
const int intervalsPerDay = 96;
const int haAttributeByteLimitBytes = 16_384;
var todayStart = new DateTime(2026, 3, 19, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 3, 20, 0, 0, 0, DateTimeKind.Utc);
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
{
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 5.0 + i * 0.1
Price = 4.93 + i * 0.22
}).ToList();
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
{
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 8.0 + i * 0.1
Price = 5.50 + i * 0.22
}).ToList();
object? capturedAttributes = null;
@@ -40,7 +40,7 @@ public class NordPoolPriceServiceTests
public void GetTimeQuarterIndex_ShouldReturnCorrectIndex(int hour, int minute, int expectedIndex)
{
// Arrange
var testDate = new DateTime(2026, 2, 3, hour, minute, 0, DateTimeKind.Utc);
var testDate = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
// Act
var result = NordPoolPriceService.GetTimeQuarterIndex(testDate);
@@ -58,7 +58,7 @@ public class NordPoolPriceServiceTests
public void GetTimeQuarterIndex_ShouldHandleAllHoursCorrectly(int hour, int minute, int expectedIndex)
{
// Arrange
var testDate = new DateTime(2026, 2, 3, hour, minute, 0, DateTimeKind.Utc);
var testDate = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
// Act
var result = NordPoolPriceService.GetTimeQuarterIndex(testDate);
@@ -71,7 +71,7 @@ public class NordPoolPriceServiceTests
public void GetTimeQuarterIndex_AtExactMidnight_ShouldReturnIndex4()
{
// Arrange
var testDate = new DateTime(2026, 2, 3, 0, 0, 0, DateTimeKind.Utc);
var testDate = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
// Act
var result = NordPoolPriceService.GetTimeQuarterIndex(testDate);
@@ -84,7 +84,7 @@ public class NordPoolPriceServiceTests
public void GetTimeQuarterIndex_AtEndOfDay_ShouldReturnIndex95()
{
// Arrange
var testDate = new DateTime(2026, 2, 3, 22, 45, 0, DateTimeKind.Utc);
var testDate = new DateTime(2026, 3, 31, 22, 45, 0, DateTimeKind.Utc);
// Act
var result = NordPoolPriceService.GetTimeQuarterIndex(testDate);
@@ -97,8 +97,8 @@ public class NordPoolPriceServiceTests
public void GetTimeQuarterIndex_WithSeconds_ShouldIgnoreSeconds()
{
// Arrange
var withoutSeconds = new DateTime(2026, 2, 3, 12, 0, 0, DateTimeKind.Utc);
var withSeconds = new DateTime(2026, 2, 3, 12, 0, 59, DateTimeKind.Utc);
var withoutSeconds = new DateTime(2026, 3, 31, 12, 0, 0, DateTimeKind.Utc);
var withSeconds = new DateTime(2026, 3, 31, 12, 0, 59, DateTimeKind.Utc);
// Act
var result1 = NordPoolPriceService.GetTimeQuarterIndex(withoutSeconds);
@@ -117,7 +117,7 @@ public class NordPoolPriceServiceTests
{
for (var minute = 0; minute < 60; minute += 15)
{
var date = new DateTime(2026, 2, 3, hour, minute, 0, DateTimeKind.Utc);
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
var index = NordPoolPriceService.GetTimeQuarterIndex(date);
indices.Add(index);
}
@@ -285,9 +285,9 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 100.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 200.0 },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 150.0 }
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
}
};
@@ -297,9 +297,9 @@ public class NordPoolPriceServiceTests
// Assert
result.Should().NotBeNull();
result.Prices.Should().HaveCount(3);
result.Prices![0].Price.Should().BeApproximately(12.1, 0.01);
result.Prices![1].Price.Should().BeApproximately(24.2, 0.01);
result.Prices![2].Price.Should().BeApproximately(18.15, 0.01);
result.Prices![0].Price.Should().BeApproximately(9.80, 0.01);
result.Prices![1].Price.Should().BeApproximately(17.91, 0.01);
result.Prices![2].Price.Should().BeApproximately(26.02, 0.01);
}
[Fact]
@@ -310,9 +310,9 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 100.0 },
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 150.0 }
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
}
};
@@ -344,14 +344,14 @@ public class NordPoolPriceServiceTests
public void AdjustedNordPoolPrice_ShouldPreserveDateTimes()
{
// Arrange
var startTime = new DateTime(2026, 2, 3, 10, 0, 0, DateTimeKind.Utc);
var endTime = new DateTime(2026, 2, 3, 11, 0, 0, DateTimeKind.Utc);
var startTime = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
var endTime = new DateTime(2026, 3, 31, 11, 0, 0, DateTimeKind.Utc);
var inputPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = startTime, End = endTime, Price = 100.0 }
new() { Start = startTime, End = endTime, Price = 81.0 }
}
};
@@ -408,7 +408,7 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 100.0 }
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }
}
};
@@ -416,7 +416,7 @@ public class NordPoolPriceServiceTests
var result = _sut.AdjustedNordPoolPrice(inputPrice);
// Assert
inputPrice.Prices[0].Price.Should().Be(100.0);
inputPrice.Prices[0].Price.Should().Be(81.0);
result.Prices.Should().NotBeSameAs(inputPrice.Prices);
}
@@ -437,7 +437,7 @@ public class NordPoolPriceServiceTests
{
Start = now.AddMinutes(i * 15),
End = now.AddMinutes((i + 1) * 15),
Price = 10.0 + i
Price = 5.0 + i * 0.22
});
}
@@ -494,17 +494,17 @@ public class NordPoolPriceServiceTests
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
prices.Add(new NordPoolDayPrice { Price = 42.0 + i });
prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 });
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = expectedIndex;
_sut.CurrentPrice = 99.99;
_sut.CurrentPrice = 17.91;
// Act
var result = _sut.UpdateCurrentPrice();
// Assert
result.Should().Be(99.99);
result.Should().Be(17.91);
}
[Fact]
@@ -516,14 +516,14 @@ public class NordPoolPriceServiceTests
prices.Add(new NordPoolDayPrice { Price = null });
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 55.0;
_sut.CurrentPrice = 17.91;
_sut.DayQuartersIndex = -1;
// Act
var result = _sut.UpdateCurrentPrice();
// Assert
result.Should().Be(55.0);
result.Should().Be(17.91);
}
[Fact]
@@ -532,7 +532,7 @@ public class NordPoolPriceServiceTests
// Arrange
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
prices.Add(new NordPoolDayPrice { Price = 10.0 + i });
prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 });
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = -1;
@@ -566,7 +566,7 @@ public class NordPoolPriceServiceTests
_sut.LastFetchedDate = today.AddDays(-1);
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 10.0 } }
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
// Act
@@ -585,7 +585,7 @@ public class NordPoolPriceServiceTests
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = null };
_sut.TomorrowNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 10.0 } }
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
// Act
@@ -604,7 +604,7 @@ public class NordPoolPriceServiceTests
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
_sut.TomorrowNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 10.0 } }
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
// Act
@@ -622,11 +622,11 @@ public class NordPoolPriceServiceTests
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 10.0 } }
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 20.0 } }
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
};
// Act
+2 -2
View File
@@ -21,8 +21,8 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.2" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.5" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
</ItemGroup>
</Project>
+2 -2
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
@@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
</ItemGroup>
<ItemGroup>
@@ -24,15 +24,15 @@ public class OtherPowerCalculationServiceTests
var sut = CreateSut(smoothingWindowSize: 1);
var devices = new Dictionary<string, double>
{
["sensor.device_a_power"] = 500,
["sensor.device_b_power"] = 300
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93
};
var result = sut.Calculate(1000, devices);
var result = sut.Calculate(341.97, devices);
result.TotalPowerWatts.Should().Be(1000);
result.KnownDevicesSumWatts.Should().Be(800);
result.RawOtherPowerWatts.Should().Be(200);
result.TotalPowerWatts.Should().Be(341.97);
result.KnownDevicesSumWatts.Should().BeApproximately(45.48, 0.01);
result.RawOtherPowerWatts.Should().BeApproximately(296.49, 0.01);
result.DataQuality.Should().Be("ok");
}
@@ -42,11 +42,11 @@ public class OtherPowerCalculationServiceTests
var sut = CreateSut(smoothingWindowSize: 1);
var devices = new Dictionary<string, double>
{
["sensor.device_a_power"] = 800,
["sensor.device_b_power"] = 500
["sensor.sonoff_100215c534_power"] = 200.0,
["sensor.sonoff_10018909cb_power"] = 180.0
};
var result = sut.Calculate(1000, devices);
var result = sut.Calculate(341.97, devices);
result.RawOtherPowerWatts.Should().Be(0);
result.SmoothedOtherPowerWatts.Should().Be(0);
@@ -59,9 +59,9 @@ public class OtherPowerCalculationServiceTests
var sut = CreateSut(smoothingWindowSize: 1);
var devices = new Dictionary<string, double>();
var result = sut.Calculate(1500, devices);
var result = sut.Calculate(341.97, devices);
result.RawOtherPowerWatts.Should().Be(1500);
result.RawOtherPowerWatts.Should().Be(341.97);
result.KnownDevicesSumWatts.Should().Be(0);
}
@@ -71,15 +71,15 @@ public class OtherPowerCalculationServiceTests
var sut = CreateSut(smoothingWindowSize: 1);
var devices = new Dictionary<string, double>
{
["sensor.a"] = 100,
["sensor.b"] = 200
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93
};
var result = sut.Calculate(500, devices);
var result = sut.Calculate(341.97, devices);
result.DevicePowerReadings.Should().HaveCount(2);
result.DevicePowerReadings["sensor.a"].Should().Be(100);
result.DevicePowerReadings["sensor.b"].Should().Be(200);
result.DevicePowerReadings["sensor.sonoff_100215c534_power"].Should().Be(8.55);
result.DevicePowerReadings["sensor.sonoff_10018909cb_power"].Should().Be(36.93);
}
#endregion
@@ -92,12 +92,12 @@ public class OtherPowerCalculationServiceTests
var sut = CreateSut(smoothingWindowSize: 4);
var devices = new Dictionary<string, double>();
var result1 = sut.Calculate(1000, devices);
result1.SmoothedOtherPowerWatts.Should().BeApproximately(1000, 0.1);
var result1 = sut.Calculate(341.97, devices);
result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1);
var result2 = sut.Calculate(500, devices);
result2.SmoothedOtherPowerWatts.Should().BeLessThan(1000);
result2.SmoothedOtherPowerWatts.Should().BeGreaterThan(500);
var result2 = sut.Calculate(115.0, devices);
result2.SmoothedOtherPowerWatts.Should().BeLessThan(341.97);
result2.SmoothedOtherPowerWatts.Should().BeGreaterThan(115.0);
}
[Fact]
@@ -109,10 +109,10 @@ public class OtherPowerCalculationServiceTests
PowerCalculationResult? result = null;
for (var i = 0; i < 50; i++)
{
result = sut.Calculate(300, devices);
result = sut.Calculate(200.0, devices);
}
result!.SmoothedOtherPowerWatts.Should().BeApproximately(300, 0.1);
result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1);
}
#endregion
@@ -124,13 +124,13 @@ public class OtherPowerCalculationServiceTests
{
var sut = CreateSut(smoothingWindowSize: 10);
var devices = new Dictionary<string, double>();
sut.Calculate(1000, devices);
sut.Calculate(1000, devices);
sut.Calculate(341.97, devices);
sut.Calculate(341.97, devices);
sut.Reset();
var result = sut.Calculate(100, devices);
var result = sut.Calculate(115.0, devices);
result.SmoothedOtherPowerWatts.Should().BeApproximately(100, 0.1);
result.SmoothedOtherPowerWatts.Should().BeApproximately(115.0, 0.1);
}
#endregion
@@ -9,15 +9,19 @@ public class PowerCostCalculationServiceTests
{
private readonly PowerCostCalculationService _sut = new();
private const double DefaultTotalWatts = 341.97;
private const double DefaultSmoothedOtherWatts = 131.04;
private const double DefaultPricePerKwh = 0.1791;
private static PowerCalculationResult CreateResult(
double totalWatts = 1000,
double smoothedOtherWatts = 200,
double totalWatts = DefaultTotalWatts,
double smoothedOtherWatts = DefaultSmoothedOtherWatts,
Dictionary<string, double>? deviceReadings = null)
{
var readings = deviceReadings ?? new Dictionary<string, double>
{
["sensor.device_a_power"] = 500,
["sensor.device_b_power"] = 300
["sensor.sonoff_100215c534_power"] = 101.0,
["sensor.sonoff_10018909cb_power"] = 109.93
};
return new PowerCalculationResult
@@ -37,12 +41,12 @@ public class PowerCostCalculationServiceTests
public void CalculateCostIncrement_ShouldComputeCorrectCost()
{
var cost = PowerCostCalculationService.CalculateCostIncrement(
powerWatts: 1000,
pricePerKwh: 0.10,
powerWatts: 341.97,
pricePerKwh: 0.1791,
pollIntervalSeconds: PowerMonitorConsts.DefaultPollIntervalSeconds);
var expected = (1000.0 / PowerMonitorConsts.WattsPerKilowatt)
* 0.10
var expected = (341.97 / PowerMonitorConsts.WattsPerKilowatt)
* 0.1791
* ((double)PowerMonitorConsts.DefaultPollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
cost.Should().BeApproximately(expected, 0.000001);
}
@@ -50,14 +54,14 @@ public class PowerCostCalculationServiceTests
[Fact]
public void CalculateCostIncrement_WithZeroPower_ShouldReturnZero()
{
var cost = PowerCostCalculationService.CalculateCostIncrement(0, 0.10, 15);
var cost = PowerCostCalculationService.CalculateCostIncrement(0, DefaultPricePerKwh, 15);
cost.Should().Be(0);
}
[Fact]
public void CalculateCostIncrement_WithZeroPrice_ShouldReturnZero()
{
var cost = PowerCostCalculationService.CalculateCostIncrement(1000, 0, 15);
var cost = PowerCostCalculationService.CalculateCostIncrement(341.97, 0, 15);
cost.Should().Be(0);
}
@@ -71,7 +75,7 @@ public class PowerCostCalculationServiceTests
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
_sut.RecordCosts(result, 0.10, 15, now);
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
var totalSnapshot = _sut.GetTotalCostSnapshot();
totalSnapshot.CostDaily.Should().BeGreaterThan(0);
@@ -86,22 +90,22 @@ public class PowerCostCalculationServiceTests
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
_sut.RecordCosts(result, 0.10, 15, now);
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
var deviceA = _sut.GetDeviceCostSnapshot("sensor.device_a_power");
deviceA.CostDaily.Should().BeGreaterThan(0);
var ac = _sut.GetDeviceCostSnapshot("sensor.sonoff_100215c534_power");
ac.CostDaily.Should().BeGreaterThan(0);
var deviceB = _sut.GetDeviceCostSnapshot("sensor.device_b_power");
deviceB.CostDaily.Should().BeGreaterThan(0);
var induction = _sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power");
induction.CostDaily.Should().BeGreaterThan(0);
}
[Fact]
public void RecordCosts_TotalCostShouldBeHigherThanOtherCost()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult(totalWatts: 1000, smoothedOtherWatts: 200);
var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts);
_sut.RecordCosts(result, 0.10, 15, now);
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
var total = _sut.GetTotalCostSnapshot();
var other = _sut.GetOtherCostSnapshot();
@@ -114,10 +118,10 @@ public class PowerCostCalculationServiceTests
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
_sut.RecordCosts(result, 0.10, 15, now);
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
var firstCost = _sut.GetTotalCostSnapshot().CostDaily;
_sut.RecordCosts(result, 0.10, 15, now.AddSeconds(15));
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(15));
var secondCost = _sut.GetTotalCostSnapshot().CostDaily;
secondCost.Should().BeApproximately(firstCost * 2, 0.000001);
@@ -129,19 +133,19 @@ public class PowerCostCalculationServiceTests
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result1 = CreateResult(deviceReadings: new Dictionary<string, double>
{
["sensor.device_a_power"] = 500
["sensor.sonoff_100215c534_power"] = 101.0
});
_sut.RecordCosts(result1, 0.10, 15, now);
_sut.RecordCosts(result1, DefaultPricePerKwh, 15, now);
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
var result2 = CreateResult(deviceReadings: new Dictionary<string, double>
{
["sensor.device_a_power"] = 500,
["sensor.device_b_power"] = 300
["sensor.sonoff_100215c534_power"] = 101.0,
["sensor.sonoff_10018909cb_power"] = 109.93
});
_sut.RecordCosts(result2, 0.10, 15, now.AddSeconds(15));
_sut.RecordCosts(result2, DefaultPricePerKwh, 15, now.AddSeconds(15));
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
}
@@ -155,9 +159,9 @@ public class PowerCostCalculationServiceTests
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
_sut.RecordCosts(result, 0.15, 15, now);
_sut.RecordCosts(result, 0.2492, 15, now);
_sut.LastKnownPrice.Should().Be(0.15);
_sut.LastKnownPrice.Should().Be(0.2492);
_sut.PriceSource.Should().Be("live");
}
@@ -167,19 +171,19 @@ public class PowerCostCalculationServiceTests
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
_sut.RecordCosts(result, 0.10, 15, now);
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
_sut.RecordCosts(result, 0, 15, now.AddSeconds(15));
_sut.LastKnownPrice.Should().Be(0.10);
_sut.LastKnownPrice.Should().Be(DefaultPricePerKwh);
_sut.PriceSource.Should().Be("live");
}
[Fact]
public void SetPrice_ShouldUpdatePriceAndMarkAsStale()
{
_sut.SetPrice(0.20);
_sut.SetPrice(0.1891);
_sut.LastKnownPrice.Should().Be(0.20);
_sut.LastKnownPrice.Should().Be(0.1891);
_sut.PriceSource.Should().Be("stale");
}
@@ -229,7 +233,7 @@ public class PowerCostCalculationServiceTests
public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult(totalWatts: 1000, smoothedOtherWatts: 200);
var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts);
const int callsPerThread = 100;
const int threadCount = 10;
@@ -238,7 +242,7 @@ public class PowerCostCalculationServiceTests
{
for (var i = 0; i < callsPerThread; i++)
{
_sut.RecordCosts(result, 0.10, 15, now.AddSeconds(1));
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(1));
}
}))
.ToArray();
@@ -146,8 +146,8 @@ public class PowerMonitorEntityServiceTests
var sensors = new List<PowerSensorInfo>
{
new() { EntityId = "sensor.device_a_power", FriendlyName = "Device A", DeviceName = "device_a" },
new() { EntityId = "sensor.device_b_power", FriendlyName = "Device B", DeviceName = "device_b" }
new() { EntityId = "sensor.sonoff_100215c534_power", FriendlyName = "AC Power", DeviceName = "sonoff_100215c534" },
new() { EntityId = "sensor.sonoff_10018909cb_power", FriendlyName = "Induction Power", DeviceName = "sonoff_10018909cb" }
};
await _sut.CreateDeviceEntitiesAsync(sensors);
@@ -238,10 +238,10 @@ public class PowerMonitorEntityServiceTests
await _sut.UpdateEntitiesAsync(context);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_15min", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_1h", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_daily", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_monthly", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_15min", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_1h", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_daily", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_monthly", It.IsAny<string>()), Times.Once);
}
[Fact]
@@ -293,31 +293,41 @@ public class PowerMonitorEntityServiceTests
{
Calculation = new PowerCalculationResult
{
TotalPowerWatts = 1000,
KnownDevicesSumWatts = 800,
RawOtherPowerWatts = 200,
SmoothedOtherPowerWatts = 195,
TotalPowerWatts = 341.97,
KnownDevicesSumWatts = 210.93,
RawOtherPowerWatts = 131.04,
SmoothedOtherPowerWatts = 128.5,
DataQuality = "ok",
DevicePowerReadings = new Dictionary<string, double>
{
["sensor.device_a_power"] = 500,
["sensor.device_b_power"] = 300
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93,
["sensor.tv_power"] = 101.0,
["sensor.akvariumas_power"] = 21.0,
["sensor.sonoff_1002230a48_power"] = 20.06,
["sensor.temp_power"] = 14.0,
["sensor.balkony_laps_power"] = 9.39
}
},
CurrentNordPoolPrice = 0.10,
CurrentNordPoolPrice = 0.1791,
PriceUnit = "EUR/kWh",
PriceSource = "live",
DeviceCosts = new Dictionary<string, CostSnapshot>
{
["sensor.device_a_power"] = new() { Cost15Min = 0.01, Cost1Hour = 0.04, CostDaily = 0.50, CostMonthly = 15.0 },
["sensor.device_b_power"] = new() { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.30, CostMonthly = 9.0 }
["sensor.sonoff_100215c534_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.004, CostDaily = 0.03, CostMonthly = 0.9 },
["sensor.sonoff_10018909cb_power"] = new() { Cost15Min = 0.002, Cost1Hour = 0.009, CostDaily = 0.11, CostMonthly = 3.3 },
["sensor.tv_power"] = new() { Cost15Min = 0.006, Cost1Hour = 0.024, CostDaily = 0.30, CostMonthly = 9.0 },
["sensor.akvariumas_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 },
["sensor.sonoff_1002230a48_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 },
["sensor.temp_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.003, CostDaily = 0.04, CostMonthly = 1.2 },
["sensor.balkony_laps_power"] = new() { Cost15Min = 0.0005, Cost1Hour = 0.002, CostDaily = 0.03, CostMonthly = 0.9 }
},
TotalCost = new CostSnapshot { Cost15Min = 0.02, Cost1Hour = 0.08, CostDaily = 1.00, CostMonthly = 30.0 },
OtherCost = new CostSnapshot { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.20, CostMonthly = 6.0 },
OtherCost = new CostSnapshot { Cost15Min = 0.008, Cost1Hour = 0.031, CostDaily = 0.38, CostMonthly = 11.4 },
IsAnomaly = isAnomaly,
AnomalyDuration = TimeSpan.Zero,
AnomalyThresholdWatts = 500,
TrackedSensorCount = 2,
AnomalyThresholdWatts = 1000,
TrackedSensorCount = 7,
DegradedSensors = [],
SystemStatus = "ok"
};
@@ -22,7 +22,7 @@ public class PowerSensorDiscoveryServiceTests
}
private PowerSensorDiscoveryService CreateSut(
string mainMeterEntityId = "sensor.p1_meter_power",
string mainMeterEntityId = "sensor.sonoff_100267d63f_power",
string[]? excludedPatterns = null)
{
var options = Options.Create(new PowerMonitorOptions
@@ -73,9 +73,9 @@ public class PowerSensorDiscoveryServiceTests
public void DiscoverDeviceSensors_ShouldFindPowerSensors()
{
SetupEntities(
("sensor.p1_meter_power", "power", "W", "P1 Meter"),
("sensor.sonoff_power", "power", "W", "Sonoff Power"),
("sensor.zigbee_power", "power", "W", "Zigbee Power"),
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"),
("sensor.temperature", "temperature", "°C", "Temperature")
);
@@ -83,31 +83,31 @@ public class PowerSensorDiscoveryServiceTests
var result = sut.DiscoverDeviceSensors();
result.Should().HaveCount(2);
result.Should().Contain(s => s.EntityId == "sensor.sonoff_power");
result.Should().Contain(s => s.EntityId == "sensor.zigbee_power");
result.Should().Contain(s => s.EntityId == "sensor.sonoff_100215c534_power");
result.Should().Contain(s => s.EntityId == "sensor.sonoff_10018909cb_power");
}
[Fact]
public void DiscoverDeviceSensors_ShouldExcludeMainMeter()
{
SetupEntities(
("sensor.p1_meter_power", "power", "W", "P1 Meter"),
("sensor.device_power", "power", "W", "Device")
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.tv_power", "power", "W", "TV Power")
);
var sut = CreateSut();
var result = sut.DiscoverDeviceSensors();
result.Should().HaveCount(1);
result.Should().NotContain(s => s.EntityId == "sensor.p1_meter_power");
result.Should().NotContain(s => s.EntityId == "sensor.sonoff_100267d63f_power");
}
[Fact]
public void DiscoverDeviceSensors_ShouldApplyExclusionPatterns()
{
SetupEntities(
("sensor.p1_meter_power", "power", "W", "P1"),
("sensor.device_power", "power", "W", "Device"),
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.tv_power", "power", "W", "TV Power"),
("sensor.nordpool_some_power", "power", "W", "NordPool"),
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")
);
@@ -116,21 +116,22 @@ public class PowerSensorDiscoveryServiceTests
var result = sut.DiscoverDeviceSensors();
result.Should().HaveCount(1);
result.Should().Contain(s => s.EntityId == "sensor.device_power");
result.Should().Contain(s => s.EntityId == "sensor.tv_power");
}
[Fact]
public void DiscoverDeviceSensors_ShouldHandleKilowattUnit()
{
SetupEntities(
("sensor.p1_meter_power", "power", "W", "P1"),
("sensor.device_kw", "power", "kW", "Device kW")
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.sonoff_1002230e32_power", "power", "kW", "Boiler Power")
);
var sut = CreateSut();
var result = sut.DiscoverDeviceSensors();
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.sonoff_1002230e32_power");
result.First().UnitOfMeasurement.Should().Be("kW");
}
@@ -152,8 +153,8 @@ public class PowerSensorDiscoveryServiceTests
public void DiscoverDeviceSensors_ShouldUpdateCurrentDeviceSensors()
{
SetupEntities(
("sensor.p1_meter_power", "power", "W", "P1"),
("sensor.device_power", "power", "W", "Device")
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.akvariumas_power", "power", "W", "Akvariumas Power")
);
var sut = CreateSut();
@@ -168,8 +169,8 @@ public class PowerSensorDiscoveryServiceTests
public void DiscoverDeviceSensors_ReDiscovery_ShouldReplacePreviousList()
{
SetupEntities(
("sensor.p1_meter_power", "power", "W", "P1"),
("sensor.device_a_power", "power", "W", "Device A")
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.sonoff_100215c534_power", "power", "W", "AC Power")
);
var sut = CreateSut();
@@ -177,9 +178,9 @@ public class PowerSensorDiscoveryServiceTests
sut.CurrentDeviceSensors.Should().HaveCount(1);
SetupEntities(
("sensor.p1_meter_power", "power", "W", "P1"),
("sensor.device_a_power", "power", "W", "Device A"),
("sensor.device_b_power", "power", "W", "Device B")
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power")
);
sut.DiscoverDeviceSensors();
@@ -192,8 +193,9 @@ public class PowerSensorDiscoveryServiceTests
[Theory]
[InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")]
[InlineData("sensor.zigbee_device_power", "zigbee_device")]
[InlineData("sensor.some_sensor", "some_sensor")]
[InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")]
[InlineData("sensor.tv_power", "tv")]
[InlineData("sensor.temp_power", "temp")]
[InlineData("sensor.power", "power")]
public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected)
{
@@ -206,9 +208,9 @@ public class PowerSensorDiscoveryServiceTests
[Theory]
[InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)]
[InlineData("sensor.nordpool_*", "sensor.device_power", false)]
[InlineData("sensor.nordpool_*", "sensor.tv_power", false)]
[InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)]
[InlineData("*_power", "sensor.sonoff_power", true)]
[InlineData("*_power", "sensor.sonoff_100215c534_power", true)]
public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected)
{
var regex = PowerSensorDiscoveryService.GlobToRegex(glob);
@@ -222,8 +224,8 @@ public class PowerSensorDiscoveryServiceTests
[Fact]
public void IsPowerSensor_WithPowerDeviceClassAndWattUnit_ShouldReturnTrue()
{
SetupEntities(("sensor.test_power", "power", "W", "Test"));
var entity = new Entity(_haContextMock.Object, "sensor.test_power");
SetupEntities(("sensor.sonoff_100215c534_power", "power", "W", "AC Power"));
var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_power");
var sut = CreateSut();
sut.IsPowerSensor(entity).Should().BeTrue();
@@ -232,8 +234,8 @@ public class PowerSensorDiscoveryServiceTests
[Fact]
public void IsPowerSensor_WithNonSensorDomain_ShouldReturnFalse()
{
SetupEntities(("switch.test_power", "power", "W", "Test"));
var entity = new Entity(_haContextMock.Object, "switch.test_power");
SetupEntities(("switch.sonoff_100215c534_power", "power", "W", "AC Power"));
var entity = new Entity(_haContextMock.Object, "switch.sonoff_100215c534_power");
var sut = CreateSut();
sut.IsPowerSensor(entity).Should().BeFalse();
@@ -242,8 +244,8 @@ public class PowerSensorDiscoveryServiceTests
[Fact]
public void IsPowerSensor_WithTemperatureDeviceClass_ShouldReturnFalse()
{
SetupEntities(("sensor.test_temp", "temperature", "°C", "Test"));
var entity = new Entity(_haContextMock.Object, "sensor.test_temp");
SetupEntities(("sensor.sonoff_100215c534_temp", "temperature", "°C", "AC Temp"));
var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_temp");
var sut = CreateSut();
sut.IsPowerSensor(entity).Should().BeFalse();
@@ -20,8 +20,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.2" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
</ItemGroup>
</Project>
@@ -12,7 +12,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,116 @@
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager;
using ShowerMonitorManager.Models;
namespace ShowerMonitor.Manager.Tests;
public class ExhaustFanControlServiceTests
{
private const string FanEntityId = "switch.exhaust_fan";
private readonly ShowerMonitorOptions _defaultOptions = new()
{
ExhaustFanEntityId = FanEntityId,
FanRunAfterShowerMinutes = 10
};
private readonly Mock<IHaContext> _haContextMock = new();
private ExhaustFanControlService CreateService(ShowerMonitorOptions? options = null)
{
return new ExhaustFanControlService(
Mock.Of<ILogger<ExhaustFanControlService>>(),
Options.Create(options ?? _defaultOptions));
}
[Fact]
public void Evaluate_WhenActive_TurnsFanOn()
{
var entityState = new EntityState { State = "off" };
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
var service = CreateService();
service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object);
_haContextMock.Verify(x => x.CallService("switch", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
}
[Fact]
public void Evaluate_WhenActiveAndFanAlreadyOn_DoesNotCallAgain()
{
var entityState = new EntityState { State = "on" };
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
var service = CreateService();
service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object);
_haContextMock.Verify(x => x.CallService("switch", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
[Fact]
public void Evaluate_AfterShowerEndsAndRunPeriodElapsed_TurnsFanOff()
{
var entityState = new EntityState { State = "off" };
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
var service = CreateService();
var now = DateTimeOffset.UtcNow;
service.Evaluate(ShowerState.Active, now, _haContextMock.Object);
service.Evaluate(ShowerState.Completed, now.AddMinutes(5), _haContextMock.Object);
service.Evaluate(ShowerState.Idle, now.AddMinutes(16), _haContextMock.Object);
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
}
[Fact]
public void Evaluate_AfterShowerEndsButRunPeriodNotElapsed_KeepsFanOn()
{
var entityState = new EntityState { State = "off" };
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
var service = CreateService();
var now = DateTimeOffset.UtcNow;
service.Evaluate(ShowerState.Active, now, _haContextMock.Object);
service.Evaluate(ShowerState.Completed, now.AddMinutes(5), _haContextMock.Object);
service.Evaluate(ShowerState.Idle, now.AddMinutes(8), _haContextMock.Object);
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
[Fact]
public void Reset_WhenFanWasTurnedOnByUs_TurnsFanOff()
{
var entityState = new EntityState { State = "off" };
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
var service = CreateService();
service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object);
service.Reset(_haContextMock.Object);
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
}
[Fact]
public void Reset_WhenFanWasNotTurnedOnByUs_DoesNotTurnFanOff()
{
var service = CreateService();
service.Reset(_haContextMock.Object);
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
}
@@ -0,0 +1,105 @@
using FluentAssertions;
using ShowerMonitorManager;
namespace ShowerMonitor.Manager.Tests;
public class HumidityRateCalculatorTests
{
private const int DefaultWindowSize = 5;
[Fact]
public void GetRatePerMinute_WithNoReadings_ReturnsZero()
{
var calculator = new HumidityRateCalculator(DefaultWindowSize);
calculator.GetRatePerMinute().Should().Be(0.0);
}
[Fact]
public void GetRatePerMinute_WithSingleReading_ReturnsZero()
{
var calculator = new HumidityRateCalculator(DefaultWindowSize);
calculator.RecordReading(52.9, DateTimeOffset.UtcNow);
calculator.GetRatePerMinute().Should().Be(0.0);
}
[Fact]
public void GetRatePerMinute_WithRisingHumidity_ReturnsPositiveRate()
{
var calculator = new HumidityRateCalculator(DefaultWindowSize);
var baseTime = DateTimeOffset.UtcNow;
calculator.RecordReading(52.9, baseTime);
calculator.RecordReading(62.9, baseTime.AddMinutes(1));
calculator.GetRatePerMinute().Should().BeApproximately(10.0, 0.01);
}
[Fact]
public void GetRatePerMinute_WithFallingHumidity_ReturnsNegativeRate()
{
var calculator = new HumidityRateCalculator(DefaultWindowSize);
var baseTime = DateTimeOffset.UtcNow;
calculator.RecordReading(62.9, baseTime);
calculator.RecordReading(52.9, baseTime.AddMinutes(2));
calculator.GetRatePerMinute().Should().BeApproximately(-5.0, 0.01);
}
[Fact]
public void GetRatePerMinute_ExceedingWindowSize_DropsStalestReading()
{
var calculator = new HumidityRateCalculator(3);
var baseTime = DateTimeOffset.UtcNow;
calculator.RecordReading(52.9, baseTime);
calculator.RecordReading(57.9, baseTime.AddMinutes(1));
calculator.RecordReading(62.9, baseTime.AddMinutes(2));
calculator.RecordReading(64.9, baseTime.AddMinutes(3));
var rate = calculator.GetRatePerMinute();
rate.Should().BeApproximately(3.5, 0.01);
}
[Fact]
public void GetRatePerMinute_WithSameTimestamp_ReturnsZero()
{
var calculator = new HumidityRateCalculator(DefaultWindowSize);
var sameTime = DateTimeOffset.UtcNow;
calculator.RecordReading(52.9, sameTime);
calculator.RecordReading(62.9, sameTime);
calculator.GetRatePerMinute().Should().Be(0.0);
}
[Fact]
public void Reset_ClearsAllReadings()
{
var calculator = new HumidityRateCalculator(DefaultWindowSize);
var baseTime = DateTimeOffset.UtcNow;
calculator.RecordReading(52.9, baseTime);
calculator.RecordReading(62.9, baseTime.AddMinutes(1));
calculator.Reset();
calculator.GetRatePerMinute().Should().Be(0.0);
}
[Fact]
public void GetRatePerMinute_SimulatesShowerSpike_DetectsHighRate()
{
var calculator = new HumidityRateCalculator(DefaultWindowSize);
var baseTime = DateTimeOffset.UtcNow;
calculator.RecordReading(52.9, baseTime);
calculator.RecordReading(59.9, baseTime.AddSeconds(30));
calculator.RecordReading(64.9, baseTime.AddSeconds(60));
var rate = calculator.GetRatePerMinute();
rate.Should().BeGreaterThan(4.0);
}
}
@@ -0,0 +1,170 @@
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace ShowerMonitor.Manager.Tests;
public class ShowerDetectionServiceTests
{
private readonly ShowerMonitorOptions _defaultOptions = new()
{
SpikeRateThreshold = 4.0,
MinDifferentialHumidity = 8.0,
PeakHumidityThreshold = 58.0,
ConfirmationWindowMinutes = 2,
RecoveryDifferentialThreshold = 5.0,
MaxShowerDurationMinutes = 60,
RateWindowSize = 5
};
private ShowerDetectionService CreateService(
IHumidityRateCalculator? rateCalculator = null,
ShowerMonitorOptions? options = null)
{
var opts = options ?? _defaultOptions;
var calculator = rateCalculator ?? new HumidityRateCalculator(opts.RateWindowSize);
return new ShowerDetectionService(
calculator,
Mock.Of<ILogger<ShowerDetectionService>>(),
Options.Create(opts));
}
[Fact]
public void InitialState_IsIdle()
{
var service = CreateService();
service.CurrentState.Should().Be(ShowerState.Idle);
}
[Fact]
public void Evaluate_WithNoSpike_RemainsIdle()
{
var service = CreateService();
var baseTime = DateTimeOffset.UtcNow;
service.Evaluate(52.9, 50.5, baseTime);
service.Evaluate(53.2, 50.5, baseTime.AddSeconds(30));
service.CurrentState.Should().Be(ShowerState.Idle);
}
[Fact]
public void Evaluate_WithShowerSpike_TransitionsToSuspected()
{
var service = CreateService();
var baseTime = DateTimeOffset.UtcNow;
service.Evaluate(52.9, 50.5, baseTime);
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
var state = service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
state.Should().Be(ShowerState.Suspected);
}
[Fact]
public void Evaluate_WithSustainedSpike_TransitionsToActive()
{
var service = CreateService();
var baseTime = DateTimeOffset.UtcNow;
service.Evaluate(52.9, 50.5, baseTime);
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
var state = service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
state.Should().Be(ShowerState.Active);
}
[Fact]
public void Evaluate_FullShowerCycle_CompletesSession()
{
var service = CreateService();
var baseTime = DateTimeOffset.UtcNow;
service.Evaluate(52.9, 50.5, baseTime);
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
service.CurrentState.Should().Be(ShowerState.Active);
service.Evaluate(61.0, 50.0, baseTime.AddMinutes(10));
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15));
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20));
service.TodaySessionCount.Should().BeGreaterThanOrEqualTo(1);
service.LastCompletedSession.Should().NotBeNull();
}
[Fact]
public void Evaluate_SuspectedThenDrops_ReturnsToIdle()
{
var service = CreateService();
var baseTime = DateTimeOffset.UtcNow;
service.Evaluate(52.9, 50.5, baseTime);
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
service.CurrentState.Should().Be(ShowerState.Suspected);
service.Evaluate(57.0, 50.0, baseTime.AddMinutes(2));
service.Evaluate(54.0, 50.0, baseTime.AddMinutes(3));
service.Evaluate(52.5, 50.5, baseTime.AddMinutes(4));
service.Evaluate(52.0, 50.5, baseTime.AddMinutes(5));
service.CurrentState.Should().Be(ShowerState.Idle);
}
[Fact]
public void ResetDailyCounters_ClearsSessionCount()
{
var service = CreateService();
var baseTime = DateTimeOffset.UtcNow;
service.Evaluate(52.9, 50.5, baseTime);
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15));
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20));
service.ResetDailyCounters();
service.TodaySessionCount.Should().Be(0);
service.LastCompletedSession.Should().BeNull();
}
[Fact]
public void Evaluate_BackToBackShowers_CountsAsTwoSessions()
{
var service = CreateService();
var baseTime = DateTimeOffset.UtcNow;
service.Evaluate(52.9, 50.5, baseTime);
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(10));
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(15));
var firstCount = service.TodaySessionCount;
service.Evaluate(52.9, 50.5, baseTime.AddMinutes(20));
service.Evaluate(58.5, 49.5, baseTime.AddMinutes(20).AddSeconds(30));
service.Evaluate(66.0, 49.5, baseTime.AddMinutes(21));
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(23));
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(30));
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(35));
service.TodaySessionCount.Should().BeGreaterThan(firstCount);
}
}
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,106 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace ShowerMonitorManager;
public sealed class ExhaustFanControlService : IExhaustFanControlService
{
private readonly ILogger<ExhaustFanControlService> _logger;
private readonly ShowerMonitorOptions _options;
private readonly Lock _lock = new();
private bool _fanTurnedOnByUs;
private DateTimeOffset? _showerEndedAt;
public ExhaustFanControlService(
ILogger<ExhaustFanControlService> logger,
IOptions<ShowerMonitorOptions> options)
{
_logger = logger;
_options = options.Value;
}
public void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext)
{
lock (_lock)
{
switch (state)
{
case ShowerState.Active:
case ShowerState.Suspected:
TurnOnFanIfNeeded(haContext);
_showerEndedAt = null;
break;
case ShowerState.Declining:
case ShowerState.Completed:
_showerEndedAt ??= timestamp;
EvaluatePostShowerFanOff(timestamp, haContext);
break;
case ShowerState.Idle:
EvaluatePostShowerFanOff(timestamp, haContext);
break;
}
}
}
public void Reset(IHaContext haContext)
{
lock (_lock)
{
if (_fanTurnedOnByUs)
{
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_logger.LogInformation("Exhaust fan turned OFF during reset (was turned on by shower detection)");
}
_fanTurnedOnByUs = false;
_showerEndedAt = null;
}
}
private void TurnOnFanIfNeeded(IHaContext haContext)
{
if (_fanTurnedOnByUs)
{
return;
}
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
{
return;
}
haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = true;
_logger.LogInformation("Exhaust fan turned ON by shower detection");
}
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp, IHaContext haContext)
{
if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue)
{
return;
}
var elapsed = timestamp - _showerEndedAt.Value;
var runAfterDuration = TimeSpan.FromMinutes(_options.FanRunAfterShowerMinutes);
if (elapsed < runAfterDuration)
{
return;
}
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = false;
_showerEndedAt = null;
_logger.LogInformation("Exhaust fan turned OFF after post-shower run period ({Duration})", runAfterDuration);
}
}
@@ -0,0 +1,52 @@
using ShowerMonitorManager.Interface;
namespace ShowerMonitorManager;
public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalculator
{
private readonly Lock _lock = new();
private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new();
public void RecordReading(double humidity, DateTimeOffset timestamp)
{
lock (_lock)
{
_readings.Enqueue((humidity, timestamp));
while (_readings.Count > windowSize)
{
_readings.Dequeue();
}
}
}
public double GetRatePerMinute()
{
lock (_lock)
{
if (_readings.Count < 2)
{
return 0.0;
}
var oldest = _readings.Peek();
var newest = _readings.Last();
var elapsedMinutes = (newest.Timestamp - oldest.Timestamp).TotalMinutes;
if (elapsedMinutes <= 0)
{
return 0.0;
}
return (newest.Humidity - oldest.Humidity) / elapsedMinutes;
}
}
public void Reset()
{
lock (_lock)
{
_readings.Clear();
}
}
}
@@ -0,0 +1,10 @@
using NetDaemon.HassModel;
using ShowerMonitor.Models.Enums;
namespace ShowerMonitorManager.Interface;
public interface IExhaustFanControlService
{
void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext);
void Reset(IHaContext haContext);
}
@@ -0,0 +1,8 @@
namespace ShowerMonitorManager.Interface;
public interface IHumidityRateCalculator
{
void RecordReading(double humidity, DateTimeOffset timestamp);
double GetRatePerMinute();
void Reset();
}
@@ -0,0 +1,15 @@
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
namespace ShowerMonitorManager.Interface;
public interface IShowerDetectionService
{
ShowerState CurrentState { get; }
ShowerSession? CurrentSession { get; }
ShowerSession? LastCompletedSession { get; }
int TodaySessionCount { get; }
ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp);
void ResetDailyCounters();
}

Some files were not shown because too many files have changed in this diff Show More