Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f45028715 | |||
| 6e4d684359 | |||
| 11c2574235 | |||
| c4015277a3 | |||
| c9bf646f81 | |||
| a14fb65be3 | |||
| 4a8eb30304 | |||
| 4c6b6938e8 | |||
| cd5f9d0352 | |||
| 411611215a |
+10
-3
@@ -105,6 +105,13 @@ UpgradeLog*.htm
|
|||||||
ServiceFabricBackup/
|
ServiceFabricBackup/
|
||||||
*.rptproj.bak
|
*.rptproj.bak
|
||||||
|
|
||||||
# Sensitive / local config (uncomment if you use appsettings.local.json etc.)
|
# Sensitive / local config
|
||||||
# appsettings.*.local.json
|
appsettings.Development.json
|
||||||
# *.local.json
|
appsettings.*.local.json
|
||||||
|
*.local.json
|
||||||
|
|
||||||
|
# Home Assistant long-lived tokens / per-user override files
|
||||||
|
appsettings.development.json
|
||||||
|
|
||||||
|
# Cursor MCP config (contains secrets)
|
||||||
|
.cursor/mcp.json
|
||||||
|
|||||||
Vendored
+7
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense to learn about possible attributes.
|
||||||
|
// Hover to view descriptions of existing attributes.
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": []
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Moq;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerControlServiceTests
|
||||||
|
{
|
||||||
|
private readonly BoilerControlService _sut;
|
||||||
|
|
||||||
|
public BoilerControlServiceTests()
|
||||||
|
{
|
||||||
|
var loggerMock = new Mock<ILogger<BoilerControlService>>();
|
||||||
|
_sut = new BoilerControlService(loggerMock.Object);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region TurnOn scenarios
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("off")]
|
||||||
|
[InlineData("OFF")]
|
||||||
|
[InlineData("Off")]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("unavailable")]
|
||||||
|
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
||||||
|
budgetExhausted: false, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("off")]
|
||||||
|
[InlineData(null)]
|
||||||
|
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOn(string? switchState)
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
||||||
|
budgetExhausted: true, budgetOverride: true);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region TurnOff scenarios
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff()
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: false, waterReady: false, currentSwitchState: "on",
|
||||||
|
budgetExhausted: false, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff()
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: true, waterReady: true, currentSwitchState: "on",
|
||||||
|
budgetExhausted: false, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetermineAction_WhenBudgetExhaustedAndNoOverride_ShouldReturnTurnOff()
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: true, waterReady: false, currentSwitchState: "on",
|
||||||
|
budgetExhausted: true, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("on")]
|
||||||
|
[InlineData("ON")]
|
||||||
|
[InlineData("On")]
|
||||||
|
public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState)
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: false, waterReady: false, currentSwitchState: switchState,
|
||||||
|
budgetExhausted: false, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region NoChange scenarios
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange()
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: true, waterReady: false, currentSwitchState: "on",
|
||||||
|
budgetExhausted: false, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.NoChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange()
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: false, waterReady: false, currentSwitchState: "off",
|
||||||
|
budgetExhausted: false, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.NoChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DetermineAction_WhenBudgetExhaustedAndAlreadyOff_ShouldReturnNoChange()
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(
|
||||||
|
isNowCheap: true, waterReady: false, currentSwitchState: "off",
|
||||||
|
budgetExhausted: true, budgetOverride: false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.NoChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Comprehensive theory covering all key combinations
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, false, "off", false, false, BoilerAction.TurnOn)]
|
||||||
|
[InlineData(true, false, "on", false, false, BoilerAction.NoChange)]
|
||||||
|
[InlineData(true, true, "on", false, false, BoilerAction.TurnOff)]
|
||||||
|
[InlineData(true, true, "off", false, false, BoilerAction.NoChange)]
|
||||||
|
[InlineData(false, false, "on", false, false, BoilerAction.TurnOff)]
|
||||||
|
[InlineData(false, false, "off", false, false, BoilerAction.NoChange)]
|
||||||
|
[InlineData(true, false, "on", true, false, BoilerAction.TurnOff)]
|
||||||
|
[InlineData(true, false, "off", true, false, BoilerAction.NoChange)]
|
||||||
|
[InlineData(true, false, "off", true, true, BoilerAction.TurnOn)]
|
||||||
|
[InlineData(true, false, "on", true, true, BoilerAction.NoChange)]
|
||||||
|
public void DetermineAction_AllCombinations_ShouldReturnExpectedAction(
|
||||||
|
bool isNowCheap, bool waterReady, string switchState,
|
||||||
|
bool budgetExhausted, bool budgetOverride, BoilerAction expectedAction)
|
||||||
|
{
|
||||||
|
var result = _sut.DetermineAction(isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
|
result.Should().Be(expectedAction);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -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="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
using FluentAssertions;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerMonitorConfigTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenAllFieldsSet_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = 30,
|
||||||
|
HeatingPowerThresholdWatts = 5.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenPowerEntityMissing_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = null,
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = 30,
|
||||||
|
HeatingPowerThresholdWatts = 5.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenSwitchEntityMissing_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
||||||
|
BoilerSwitchEntityId = null,
|
||||||
|
PollIntervalSeconds = 30,
|
||||||
|
HeatingPowerThresholdWatts = 5.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenPollIntervalMissing_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = null,
|
||||||
|
HeatingPowerThresholdWatts = 5.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenThresholdMissing_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = 30,
|
||||||
|
HeatingPowerThresholdWatts = null
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenPowerEntityIsWhitespace_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = " ",
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = 30,
|
||||||
|
HeatingPowerThresholdWatts = 5.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenPollIntervalIsZero_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = 0,
|
||||||
|
HeatingPowerThresholdWatts = 5.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenThresholdIsZero_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = 30,
|
||||||
|
HeatingPowerThresholdWatts = 0.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsFullyConfigured_WhenPollIntervalIsNegative_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var config = new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
||||||
|
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
||||||
|
PollIntervalSeconds = -1,
|
||||||
|
HeatingPowerThresholdWatts = 5.0
|
||||||
|
};
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using FluentAssertions;
|
||||||
|
using HomeAssistant.Entities.Interfaces;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerMonitorEntityServiceTests
|
||||||
|
{
|
||||||
|
private readonly Mock<IEntityManager> _entityManagerMock;
|
||||||
|
private readonly Mock<IHaContext> _haContextMock;
|
||||||
|
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock;
|
||||||
|
private readonly BoilerMonitorEntityService _sut;
|
||||||
|
|
||||||
|
public BoilerMonitorEntityServiceTests()
|
||||||
|
{
|
||||||
|
_entityManagerMock = new Mock<IEntityManager>();
|
||||||
|
_haContextMock = new Mock<IHaContext>();
|
||||||
|
_loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
||||||
|
_sut = new BoilerMonitorEntityService(
|
||||||
|
_entityManagerMock.Object,
|
||||||
|
_haContextMock.Object,
|
||||||
|
_loggerMock.Object);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetupEntityState(string entityId, string? state)
|
||||||
|
{
|
||||||
|
if (state is null)
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(h => h.GetState(entityId)).Returns((EntityState?)null);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(h => h.GetState(entityId))
|
||||||
|
.Returns(new EntityState { State = state });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#region ReadPersistedState
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "7200");
|
||||||
|
SetupEntityState(SessionCountEntityId, "3");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "ON");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200));
|
||||||
|
result.SessionCount.Should().Be(3);
|
||||||
|
result.SkipPriceCapState.Should().Be("ON");
|
||||||
|
result.BudgetOverrideState.Should().Be("OFF");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WithZeroRuntime_ShouldReturnZeroValues()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "0");
|
||||||
|
SetupEntityState(SessionCountEntityId, "0");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
||||||
|
result.SessionCount.Should().Be(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenRuntimeIsUnavailable_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "unavailable");
|
||||||
|
SetupEntityState(SessionCountEntityId, "3");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenRuntimeIsUnknown_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "unknown");
|
||||||
|
SetupEntityState(SessionCountEntityId, "2");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "3600");
|
||||||
|
SetupEntityState(SessionCountEntityId, "unavailable");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenRuntimeEntityDoesNotExist_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, null);
|
||||||
|
SetupEntityState(SessionCountEntityId, "2");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "3600");
|
||||||
|
SetupEntityState(SessionCountEntityId, null);
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenRuntimeIsNonNumeric_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "not_a_number");
|
||||||
|
SetupEntityState(SessionCountEntityId, "2");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "3600");
|
||||||
|
SetupEntityState(SessionCountEntityId, "abc");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenRuntimeIsNegative_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "-100");
|
||||||
|
SetupEntityState(SessionCountEntityId, "2");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "3600");
|
||||||
|
SetupEntityState(SessionCountEntityId, "-1");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "1800");
|
||||||
|
SetupEntityState(SessionCountEntityId, "1");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, null);
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, null);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800));
|
||||||
|
result.SessionCount.Should().Be(1);
|
||||||
|
result.SkipPriceCapState.Should().BeNull();
|
||||||
|
result.BudgetOverrideState.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")] // empty string
|
||||||
|
[InlineData(" ")] // whitespace
|
||||||
|
public void ReadPersistedState_WhenRuntimeIsEmptyOrWhitespace_ShouldReturnNull(string state)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, state);
|
||||||
|
SetupEntityState(SessionCountEntityId, "2");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupEntityState(TodayRuntimeEntityId, "134.66");
|
||||||
|
SetupEntityState(SessionCountEntityId, "1");
|
||||||
|
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
||||||
|
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = _sut.ReadPersistedState();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66));
|
||||||
|
result.SessionCount.Should().Be(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region ResetTransientEntitiesAsync
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await _sut.ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetTransientEntitiesAsync_ShouldNotResetRuntimeEntities()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await _sut.ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await _sut.ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using FluentAssertions;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerMonitorOptionsTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Defaults_ShouldHaveEnabledTrue()
|
||||||
|
{
|
||||||
|
var options = new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
options.Enabled.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SectionName_ShouldBeBoilerMonitor()
|
||||||
|
{
|
||||||
|
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Enabled_WhenSetToFalse_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var options = new BoilerMonitorOptions { Enabled = false };
|
||||||
|
|
||||||
|
options.Enabled.Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
using FluentAssertions;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerRunTimeTrackerTests
|
||||||
|
{
|
||||||
|
private readonly BoilerRunTimeTracker _sut = new();
|
||||||
|
|
||||||
|
#region RecordPollResult
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_WhenHeating_ShouldAccumulateRunTime()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_WhenNotHeating_ShouldNotAccumulate()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_sut.RecordPollResult(false, interval);
|
||||||
|
_sut.RecordPollResult(false, interval);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_WhenHeatingStarts_ShouldIncrementSessionCount()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.SessionCount.Should().Be(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_ContinuousHeating_ShouldCountAsOneSession()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.SessionCount.Should().Be(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_HeatingStopsAndRestarts_ShouldCountAsTwoSessions()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(false, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.SessionCount.Should().Be(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_MultipleSessions_ShouldAccumulateCorrectly()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(false, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
|
||||||
|
snapshot.SessionCount.Should().Be(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_WhenHeating_ShouldSetIsInSessionTrue()
|
||||||
|
{
|
||||||
|
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.IsInSession.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordPollResult_WhenNotHeating_ShouldSetIsInSessionFalse()
|
||||||
|
{
|
||||||
|
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
||||||
|
_sut.RecordPollResult(false, TimeSpan.FromSeconds(30));
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.IsInSession.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Reset
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Reset_ShouldClearAllState()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
|
||||||
|
_sut.Reset();
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
||||||
|
snapshot.SessionCount.Should().Be(0);
|
||||||
|
snapshot.IsInSession.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Reset_AfterReset_ShouldAccumulateFromZero()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(30);
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
_sut.Reset();
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(30));
|
||||||
|
snapshot.SessionCount.Should().Be(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region RestoreFromSnapshot
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RestoreFromSnapshot_ShouldSetAccumulatedRunTimeAndSessionCount()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var runTime = TimeSpan.FromMinutes(45);
|
||||||
|
const int sessionCount = 3;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
_sut.RestoreFromSnapshot(runTime, sessionCount);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(runTime);
|
||||||
|
snapshot.SessionCount.Should().Be(sessionCount);
|
||||||
|
snapshot.IsInSession.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RestoreFromSnapshot_ShouldOverwriteExistingState()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
||||||
|
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
||||||
|
|
||||||
|
var restoredRunTime = TimeSpan.FromHours(2);
|
||||||
|
const int restoredSessions = 5;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime);
|
||||||
|
snapshot.SessionCount.Should().Be(restoredSessions);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RestoreFromSnapshot_ShouldAllowFurtherAccumulationFromRestoredState()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var restoredRunTime = TimeSpan.FromMinutes(30);
|
||||||
|
const int restoredSessions = 2;
|
||||||
|
var pollInterval = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
_sut.RecordPollResult(true, pollInterval);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime + pollInterval);
|
||||||
|
snapshot.SessionCount.Should().Be(restoredSessions + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RestoreFromSnapshot_WithZeroValues_ShouldSetToZero()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
_sut.RestoreFromSnapshot(TimeSpan.Zero, 0);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
||||||
|
snapshot.SessionCount.Should().Be(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Thread safety
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RecordPollResult_ConcurrentCalls_ShouldNotCorruptState()
|
||||||
|
{
|
||||||
|
var interval = TimeSpan.FromSeconds(1);
|
||||||
|
const int iterationsPerThread = 1000;
|
||||||
|
const int threadCount = 4;
|
||||||
|
|
||||||
|
var tasks = Enumerable.Range(0, threadCount).Select(_ => Task.Run(() =>
|
||||||
|
{
|
||||||
|
for (var i = 0; i < iterationsPerThread; i++)
|
||||||
|
{
|
||||||
|
_sut.RecordPollResult(true, interval);
|
||||||
|
}
|
||||||
|
})).ToArray();
|
||||||
|
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(iterationsPerThread * threadCount));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region GetSnapshot
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GetSnapshot_Initial_ShouldReturnZeroState()
|
||||||
|
{
|
||||||
|
var snapshot = _sut.GetSnapshot();
|
||||||
|
|
||||||
|
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
||||||
|
snapshot.SessionCount.Should().Be(0);
|
||||||
|
snapshot.IsInSession.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,430 @@
|
|||||||
|
using BoilerMonitor.Models;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Time.Testing;
|
||||||
|
using Moq;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class WaterReadyServiceTests
|
||||||
|
{
|
||||||
|
private readonly Mock<ILogger<WaterReadyService>> _loggerMock;
|
||||||
|
private readonly FakeTimeProvider _timeProvider;
|
||||||
|
|
||||||
|
public WaterReadyServiceTests()
|
||||||
|
{
|
||||||
|
_loggerMock = new Mock<ILogger<WaterReadyService>>();
|
||||||
|
_timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow);
|
||||||
|
}
|
||||||
|
|
||||||
|
private WaterReadyService CreateSut()
|
||||||
|
{
|
||||||
|
return new WaterReadyService(_loggerMock.Object, _timeProvider);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region IsWaterReady — basic behavior (no grace period active)
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_SwitchOnAndLowPower_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_SwitchOnAndPowerBelowThreshold_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", 4.9, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", 5.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_SwitchOff_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_NullSwitchState_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady(null, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_NullPowerWatts_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_BothNull_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ON")]
|
||||||
|
[InlineData("On")]
|
||||||
|
[InlineData("on")]
|
||||||
|
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady(switchState, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(9.9, 10.0, true)]
|
||||||
|
[InlineData(10.0, 10.0, false)]
|
||||||
|
[InlineData(10.1, 10.0, false)]
|
||||||
|
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected)
|
||||||
|
{
|
||||||
|
// Arrange — fresh instance per case to avoid cooldown side-effects
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", powerWatts, threshold);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Warm-up grace period
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_DuringGracePeriod_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
|
// Act — still within grace period, low power should be suppressed
|
||||||
|
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_AfterGracePeriodExpires_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod);
|
||||||
|
|
||||||
|
// Act — grace period has elapsed, low power means water is ready
|
||||||
|
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_DuringGracePeriodWithHighPower_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
|
// Act — high power during grace period is still "not ready" (heating)
|
||||||
|
var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_JustBeforeGracePeriodExpires_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(1));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_WithoutNotifyTurnedOn_ShouldNotApplyGracePeriod()
|
||||||
|
{
|
||||||
|
// Arrange — no NotifyTurnedOn call, so no grace period should be active
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_MultipleTurnOns_ShouldResetGracePeriod()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(10));
|
||||||
|
|
||||||
|
// Act — second turn-on resets the grace period
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
_timeProvider.Advance(TimeSpan.FromSeconds(10));
|
||||||
|
|
||||||
|
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert — still within the new grace period
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_SwitchOffDuringGracePeriod_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
|
// Act — switch is off, so not ready regardless of grace period
|
||||||
|
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Water ready cooldown period
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfSwitchState()
|
||||||
|
{
|
||||||
|
// Arrange — trigger water ready detection, then turn switch off
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Act — switch is now off, but cooldown should keep reporting ready
|
||||||
|
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_AfterCooldownExpires_ShouldResumeNormalDetection()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod);
|
||||||
|
|
||||||
|
// Act — cooldown expired, switch is off → not ready
|
||||||
|
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_JustBeforeCooldownExpires_ShouldStillReturnTrue()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod - TimeSpan.FromSeconds(1));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsInCooldown_WhenNoCooldownTriggered_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsInCooldown_AfterCooldownExpires_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResetCooldown_ShouldClearActiveCooldown()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResetCooldown_ShouldAllowBoilerToTurnOnAgain()
|
||||||
|
{
|
||||||
|
// Arrange — water becomes ready, then cooldown is reset (midnight)
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
|
// Act — switch is off, no power → not ready (normal detection resumes)
|
||||||
|
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
|
||||||
|
{
|
||||||
|
// Arrange — first detection sets _waterReadySince
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Advance halfway through cooldown
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2);
|
||||||
|
|
||||||
|
// Act — second detection during cooldown should NOT reset the timestamp
|
||||||
|
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Advance remaining half
|
||||||
|
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2);
|
||||||
|
|
||||||
|
// Assert — cooldown should have expired based on original timestamp
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
// Act — water is not ready (high power), no cooldown should be triggered
|
||||||
|
sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
using static NordPool.Models.NordPoolConsts;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
||||||
|
{
|
||||||
|
private const double DefaultDailyHours = 1.0;
|
||||||
|
|
||||||
|
public BoilerConfig ReadConfig()
|
||||||
|
{
|
||||||
|
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
||||||
|
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours;
|
||||||
|
|
||||||
|
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
||||||
|
if (intervalCount <= 0)
|
||||||
|
{
|
||||||
|
intervalCount = IntervalsPerHour;
|
||||||
|
}
|
||||||
|
|
||||||
|
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
||||||
|
var priceCap = double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 ? pc : double.MaxValue;
|
||||||
|
|
||||||
|
var deadline = DateTime.Today.AddDays(1);
|
||||||
|
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
||||||
|
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime))
|
||||||
|
{
|
||||||
|
deadline = DateTime.Today.Add(readyByTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
|
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||||
|
intervalCount, priceCap, skipPriceCap, deadline);
|
||||||
|
|
||||||
|
return new BoilerConfig
|
||||||
|
{
|
||||||
|
IntervalCount = intervalCount,
|
||||||
|
PriceCap = priceCap,
|
||||||
|
Deadline = deadline,
|
||||||
|
SkipPriceCap = skipPriceCap
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
||||||
|
{
|
||||||
|
private const string SwitchOnState = "on";
|
||||||
|
|
||||||
|
public BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride)
|
||||||
|
{
|
||||||
|
var isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
|
||||||
|
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
|
||||||
|
|
||||||
|
if (shouldBeOn && !isCurrentlyOn)
|
||||||
|
{
|
||||||
|
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
|
||||||
|
|
||||||
|
return BoilerAction.TurnOn;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shouldBeOn && isCurrentlyOn)
|
||||||
|
{
|
||||||
|
var reason = GetTurnOffReason(waterReady, isNowCheap, effectiveBudgetExhausted);
|
||||||
|
|
||||||
|
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
|
||||||
|
|
||||||
|
return BoilerAction.TurnOff;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||||
|
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||||
|
|
||||||
|
return BoilerAction.NoChange;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetTurnOffReason(bool waterReady, bool isNowCheap, bool effectiveBudgetExhausted)
|
||||||
|
{
|
||||||
|
if (waterReady)
|
||||||
|
{
|
||||||
|
return "water is already ready";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (effectiveBudgetExhausted)
|
||||||
|
{
|
||||||
|
return "daily budget is exhausted";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "not in a cheap interval";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BoilerMonitorManager</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||||
|
<_Parameter1>BoilerMonitor.Manager.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using HomeAssistant.Entities.Interfaces;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class BoilerMonitorEntityService(
|
||||||
|
IEntityManager entityManager,
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<BoilerMonitorEntityService> logger) : IBoilerMonitorEntityService
|
||||||
|
{
|
||||||
|
private static readonly string[] CleanableEntityIds =
|
||||||
|
[
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId,
|
||||||
|
StatusEntityId,
|
||||||
|
WaterReadyEntityId,
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
RemainingTimeEntityId,
|
||||||
|
BudgetPercentageEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
SessionCountEntityId,
|
||||||
|
BudgetOverrideEntityId
|
||||||
|
];
|
||||||
|
|
||||||
|
private static object CreateDeviceBlock() => new
|
||||||
|
{
|
||||||
|
identifiers = new[] { DeviceIdentifier },
|
||||||
|
name = DeviceName,
|
||||||
|
model = DeviceName,
|
||||||
|
manufacturer = DeviceManufacturer
|
||||||
|
};
|
||||||
|
|
||||||
|
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
var entities = GetAllEntities();
|
||||||
|
|
||||||
|
var createTasks = entities.Select(async entity =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||||
|
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await Task.WhenAll(createTasks).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults");
|
||||||
|
|
||||||
|
await Task.WhenAll(
|
||||||
|
ResetStatusAsync(),
|
||||||
|
ResetWaterReadyAsync(),
|
||||||
|
ResetSkipPriceCapAsync(),
|
||||||
|
ResetTodayRuntimeAsync(),
|
||||||
|
ResetRemainingTimeAsync(),
|
||||||
|
ResetBudgetPercentageAsync(),
|
||||||
|
ResetBudgetExhaustedAsync(),
|
||||||
|
ResetSessionCountAsync(),
|
||||||
|
ResetBudgetOverrideAsync()
|
||||||
|
).ConfigureAwait(false);
|
||||||
|
|
||||||
|
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UpdateEntitiesAsync(BoilerMonitorUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
var timestamp = DateTime.UtcNow.ToString("O");
|
||||||
|
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
|
||||||
|
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
|
||||||
|
|
||||||
|
// logger.LogInformation("Updating BoilerMonitor entities: runtime={RunTime}, remaining={Remaining}, budget={Budget}%, sessions={Sessions}",
|
||||||
|
// formattedRunTime, formattedRemaining, ctx.BudgetPercentage, ctx.SessionCount);
|
||||||
|
|
||||||
|
var updateTasks = new[]
|
||||||
|
{
|
||||||
|
UpdateStatusAsync(StatusConfigured),
|
||||||
|
UpdateWaterReadyAsync(ctx, timestamp),
|
||||||
|
UpdateTodayRuntimeAsync(ctx.TodayRunTime, formattedRunTime, timestamp),
|
||||||
|
UpdateRemainingTimeAsync(ctx.RemainingTime, formattedRemaining, ctx.BudgetHours, timestamp),
|
||||||
|
UpdateBudgetPercentageAsync(ctx.BudgetPercentage, timestamp),
|
||||||
|
UpdateBudgetExhaustedAsync(ctx.BudgetExhausted),
|
||||||
|
UpdateSessionCountAsync(ctx.SessionCount, timestamp)
|
||||||
|
};
|
||||||
|
|
||||||
|
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
|
||||||
|
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||||
|
|
||||||
|
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)");
|
||||||
|
|
||||||
|
await Task.WhenAll(
|
||||||
|
ResetStatusAsync(),
|
||||||
|
ResetWaterReadyAsync()
|
||||||
|
).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PersistedBoilerState? ReadPersistedState()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var runtimeState = haContext.GetState(TodayRuntimeEntityId)?.State;
|
||||||
|
var sessionCountState = haContext.GetState(SessionCountEntityId)?.State;
|
||||||
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
|
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
|
|
||||||
|
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds)
|
||||||
|
|| !TryParseEntityInt(sessionCountState, out var sessionCount))
|
||||||
|
{
|
||||||
|
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||||
|
runtimeState, sessionCountState);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var persisted = new PersistedBoilerState
|
||||||
|
{
|
||||||
|
AccumulatedRunTime = TimeSpan.FromSeconds(runtimeSeconds),
|
||||||
|
SessionCount = sessionCount,
|
||||||
|
SkipPriceCapState = skipPriceCapState,
|
||||||
|
BudgetOverrideState = budgetOverrideState
|
||||||
|
};
|
||||||
|
|
||||||
|
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||||
|
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
|
||||||
|
|
||||||
|
return persisted;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SetStatusAsync(string status)
|
||||||
|
{
|
||||||
|
await UpdateStatusAsync(status).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
||||||
|
{
|
||||||
|
seconds = 0;
|
||||||
|
return !string.IsNullOrWhiteSpace(state)
|
||||||
|
&& state is not ("unavailable" or "unknown")
|
||||||
|
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
|
||||||
|
&& seconds >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryParseEntityInt(string? state, out int value)
|
||||||
|
{
|
||||||
|
value = 0;
|
||||||
|
return !string.IsNullOrWhiteSpace(state)
|
||||||
|
&& state is not ("unavailable" or "unknown")
|
||||||
|
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
|
||||||
|
&& value >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ICollection<BoilerMonitorEntity> GetAllEntities()
|
||||||
|
{
|
||||||
|
var device = CreateDeviceBlock();
|
||||||
|
|
||||||
|
return
|
||||||
|
[
|
||||||
|
new BoilerMonitorEntity("text", "boilermonitor_config_power_entity_id", "Boiler power entity ID")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:flash", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("text", "boilermonitor_config_switch_entity_id", "Boiler switch entity ID")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:toggle-switch", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("number", "boilermonitor_config_poll_interval", "Poll interval (seconds)")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new
|
||||||
|
{
|
||||||
|
min = (double)MinPollIntervalSeconds,
|
||||||
|
max = (double)MaxPollIntervalSeconds,
|
||||||
|
step = (double)PollIntervalStepSeconds,
|
||||||
|
unit_of_measurement = "s",
|
||||||
|
icon = "mdi:timer-outline",
|
||||||
|
device
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new
|
||||||
|
{
|
||||||
|
min = MinHeatingThresholdWatts,
|
||||||
|
max = MaxHeatingThresholdWatts,
|
||||||
|
step = HeatingThresholdStepWatts,
|
||||||
|
unit_of_measurement = "W",
|
||||||
|
icon = "mdi:thermometer",
|
||||||
|
device
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("button", "boilermonitor_cleanup", "Cleanup all entities")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:delete-sweep", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_status", "Boiler Monitor status")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:information-outline", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_water_ready", "Boiler water ready")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:water-thermometer", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("switch", "boilermonitor_skip_price_cap", "Skip price cap, heat until ready")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { optimistic = true, icon = "mdi:water-thermometer-outline", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:percent", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("binary_sensor", "boilermonitor_budget_exhausted", "Budget exhausted")
|
||||||
|
{
|
||||||
|
Options = new EntityCreationOptions
|
||||||
|
{
|
||||||
|
UniqueId = BudgetExhaustedEntityId,
|
||||||
|
Name = "Budget exhausted"
|
||||||
|
},
|
||||||
|
AdditionalConfig = new { icon = "mdi:battery-alert", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_session_count", "Heating sessions today")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:counter", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device }
|
||||||
|
}
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateStatusAsync(string status)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(StatusEntityId, status).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetStatusAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(StatusEntityId, StatusAwaitingConfiguration).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetWaterReadyAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
|
{
|
||||||
|
boiler_switch_state = "unknown",
|
||||||
|
boiler_power_watts = 0.0,
|
||||||
|
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||||
|
friendly_name = "Boiler water ready",
|
||||||
|
last_updated = (string?)null
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetSkipPriceCapAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(SkipPriceCapEntityId, "OFF").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetTodayRuntimeAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted = "0h 0m",
|
||||||
|
friendly_name = "Today runtime",
|
||||||
|
last_updated = (string?)null
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetRemainingTimeAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted = "0h 0m",
|
||||||
|
budget_hours = 0.0,
|
||||||
|
friendly_name = "Remaining budget time",
|
||||||
|
last_updated = (string?)null
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetBudgetPercentageAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
|
{
|
||||||
|
unit_of_measurement = "%",
|
||||||
|
friendly_name = "Budget usage",
|
||||||
|
last_updated = (string?)null
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetBudgetExhaustedAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetExhaustedEntityId, "off").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetSessionCountAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
|
{
|
||||||
|
friendly_name = "Heating sessions today",
|
||||||
|
last_updated = (string?)null
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetBudgetOverrideAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
|
{
|
||||||
|
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||||
|
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||||
|
friendly_name = "Boiler water ready",
|
||||||
|
last_updated = timestamp
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(TodayRuntimeEntityId, ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted,
|
||||||
|
friendly_name = "Today runtime",
|
||||||
|
last_updated = timestamp
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, string timestamp)
|
||||||
|
{
|
||||||
|
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
||||||
|
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted,
|
||||||
|
budget_hours = budgetHours,
|
||||||
|
friendly_name = "Remaining budget time",
|
||||||
|
last_updated = timestamp
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
||||||
|
{
|
||||||
|
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
||||||
|
await SetEntityStateSafe(BudgetPercentageEntityId, ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
|
{
|
||||||
|
unit_of_measurement = "%",
|
||||||
|
friendly_name = "Budget usage",
|
||||||
|
last_updated = timestamp
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetExhaustedEntityId, exhausted ? "on" : "off").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||||
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
|
{
|
||||||
|
friendly_name = "Heating sessions today",
|
||||||
|
last_updated = timestamp
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SetEntityStateSafe(string entityId, string state)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
||||||
|
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SetEntityAttributesSafe(string entityId, object attributes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
||||||
|
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FormatTimeSpan(TimeSpan ts)
|
||||||
|
{
|
||||||
|
var totalHours = (int)ts.TotalHours;
|
||||||
|
var minutes = ts.Minutes;
|
||||||
|
|
||||||
|
return $"{totalHours}h {minutes}m";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,503 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Reactive.Concurrency;
|
||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
using NetDaemon.Extensions.Scheduler;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
[NetDaemonApp]
|
||||||
|
public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||||
|
{
|
||||||
|
private readonly ILogger<BoilerMonitorInit> _logger;
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
private readonly IMqttEntityManager _mqttEntityManager;
|
||||||
|
private readonly IBoilerControlService _boilerControlService;
|
||||||
|
private readonly IBoilerRunTimeTracker _tracker;
|
||||||
|
private readonly IBoilerMonitorEntityService _entityService;
|
||||||
|
private readonly IWaterReadyService _waterReadyService;
|
||||||
|
private readonly BoilerMonitorOptions _options;
|
||||||
|
|
||||||
|
private bool _lastWaterReady;
|
||||||
|
private bool _cleanedUp;
|
||||||
|
|
||||||
|
public BoilerMonitorInit(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<BoilerMonitorInit> logger,
|
||||||
|
IScheduler scheduler,
|
||||||
|
IMqttEntityManager mqttEntityManager,
|
||||||
|
IBoilerControlService boilerControlService,
|
||||||
|
IBoilerRunTimeTracker tracker,
|
||||||
|
IBoilerMonitorEntityService entityService,
|
||||||
|
IWaterReadyService waterReadyService,
|
||||||
|
IOptions<BoilerMonitorOptions> options)
|
||||||
|
{
|
||||||
|
_haContext = haContext;
|
||||||
|
_logger = logger;
|
||||||
|
_scheduler = scheduler;
|
||||||
|
_mqttEntityManager = mqttEntityManager;
|
||||||
|
_boilerControlService = boilerControlService;
|
||||||
|
_tracker = tracker;
|
||||||
|
_entityService = entityService;
|
||||||
|
_waterReadyService = waterReadyService;
|
||||||
|
_options = options.Value;
|
||||||
|
|
||||||
|
_ = InitializeAndScheduleAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task InitializeAndScheduleAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await InitializeAsync();
|
||||||
|
await SubscribeToConfigCommandsAsync();
|
||||||
|
await SubscribeToSwitchCommandsAsync();
|
||||||
|
SchedulePeriodicPolling();
|
||||||
|
ScheduleMidnightReset();
|
||||||
|
ScheduleEndOfDayReminder();
|
||||||
|
SubscribeToSkipPriceCapChanges();
|
||||||
|
SubscribeToCleanupButton();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BoilerMonitor initialization and scheduling");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||||
|
|
||||||
|
if (_options.CleanupEntitiesOnStartup)
|
||||||
|
{
|
||||||
|
await _entityService.CleanupEntitiesAsync();
|
||||||
|
await _entityService.CreateEntitiesAsync();
|
||||||
|
await _entityService.ResetEntitiesAsync();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var persisted = _entityService.ReadPersistedState();
|
||||||
|
await _entityService.CreateEntitiesAsync();
|
||||||
|
|
||||||
|
if (persisted is not null)
|
||||||
|
{
|
||||||
|
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||||
|
await _entityService.ResetTransientEntitiesAsync();
|
||||||
|
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||||
|
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _entityService.ResetEntitiesAsync();
|
||||||
|
_logger.LogInformation("No persisted state found, performing full entity reset");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
await PollAndUpdateAsync();
|
||||||
|
|
||||||
|
_logger.LogInformation("BoilerMonitor initialized");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await _entityService.CleanupEntitiesAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SchedulePeriodicPolling()
|
||||||
|
{
|
||||||
|
var now = DateTime.Now;
|
||||||
|
var currentSecondInInterval = (now.Minute * 60 + now.Second) % DefaultPollIntervalSeconds;
|
||||||
|
var secondsUntilNext = DefaultPollIntervalSeconds - currentSecondInInterval;
|
||||||
|
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
|
||||||
|
var nextPollTime = now.Add(delayUntilNext);
|
||||||
|
|
||||||
|
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
|
||||||
|
|
||||||
|
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, async void () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await PollAndUpdateAsync();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BoilerMonitor poll cycle");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleMidnightReset()
|
||||||
|
{
|
||||||
|
_scheduler.ScheduleCron("0 0 * * *", () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||||
|
_tracker.Reset();
|
||||||
|
_waterReadyService.ResetCooldown();
|
||||||
|
_ = _entityService.ResetEntitiesAsync();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during midnight reset");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleEndOfDayReminder()
|
||||||
|
{
|
||||||
|
_scheduler.ScheduleCron("0 22 * * *", () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||||
|
if (string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||||
|
{
|
||||||
|
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
|
||||||
|
title = "Boiler reminder"
|
||||||
|
});
|
||||||
|
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToSkipPriceCapChanges()
|
||||||
|
{
|
||||||
|
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
||||||
|
skipPriceCapSwitch.StateChanges()
|
||||||
|
.Subscribe(e =>
|
||||||
|
{
|
||||||
|
if (e.Old?.State == e.New?.State)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
||||||
|
_ = PollAndUpdateAsync();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToCleanupButton()
|
||||||
|
{
|
||||||
|
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
||||||
|
cleanupButton.StateChanges()
|
||||||
|
.Subscribe(_ =>
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
|
||||||
|
Task.Run(HandleCleanupAsync);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SubscribeToConfigCommandsAsync()
|
||||||
|
{
|
||||||
|
var configEntityIds = new[]
|
||||||
|
{
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var entityId in configEntityIds)
|
||||||
|
{
|
||||||
|
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
||||||
|
subscription.Subscribe(async void (state) =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
||||||
|
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "Error handling command for entity {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SubscribeToSwitchCommandsAsync()
|
||||||
|
{
|
||||||
|
var switchEntityIds = new[]
|
||||||
|
{
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
BudgetOverrideEntityId
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var entityId in switchEntityIds)
|
||||||
|
{
|
||||||
|
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
||||||
|
subscription.Subscribe(async void (state) =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
||||||
|
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleCleanupAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _entityService.CleanupEntitiesAsync();
|
||||||
|
_cleanedUp = true;
|
||||||
|
_tracker.Reset();
|
||||||
|
_logger.LogInformation("BoilerMonitor cleanup complete. Entities removed, monitoring stopped");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BoilerMonitor cleanup");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PollAndUpdateAsync()
|
||||||
|
{
|
||||||
|
if (_cleanedUp)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var config = ReadConfigFromHaEntities();
|
||||||
|
|
||||||
|
if (!config.IsFullyConfigured)
|
||||||
|
{
|
||||||
|
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
||||||
|
_logger.LogWarning("BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||||
|
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||||
|
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
||||||
|
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
||||||
|
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
||||||
|
var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value);
|
||||||
|
|
||||||
|
_tracker.RecordPollResult(isHeating, pollInterval);
|
||||||
|
|
||||||
|
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
||||||
|
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
||||||
|
var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval");
|
||||||
|
|
||||||
|
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
|
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
var skipPriceCapState = _haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
|
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
||||||
|
|
||||||
|
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
|
||||||
|
|
||||||
|
if (!_lastWaterReady && waterReady)
|
||||||
|
{
|
||||||
|
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||||
|
{
|
||||||
|
message = "Hot water is ready.",
|
||||||
|
title = "Boiler"
|
||||||
|
});
|
||||||
|
_logger.LogInformation("Water ready notification sent");
|
||||||
|
}
|
||||||
|
_lastWaterReady = waterReady;
|
||||||
|
|
||||||
|
var snapshot = _tracker.GetSnapshot();
|
||||||
|
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
||||||
|
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
|
||||||
|
|
||||||
|
if (remainingTime < TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
remainingTime = TimeSpan.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
||||||
|
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
|
||||||
|
: 0.0;
|
||||||
|
|
||||||
|
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
||||||
|
|
||||||
|
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||||
|
|
||||||
|
var boilerAction = _boilerControlService.DetermineAction(effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
|
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
|
||||||
|
|
||||||
|
var context = new BoilerMonitorUpdateContext
|
||||||
|
{
|
||||||
|
TodayRunTime = snapshot.AccumulatedRunTime,
|
||||||
|
RemainingTime = remainingTime,
|
||||||
|
BudgetPercentage = budgetPercentage,
|
||||||
|
BudgetExhausted = budgetExhausted,
|
||||||
|
SessionCount = snapshot.SessionCount,
|
||||||
|
BudgetHours = dailyHours,
|
||||||
|
IsCurrentlyHeating = isHeating,
|
||||||
|
WaterReady = waterReady,
|
||||||
|
BoilerSwitchState = boilerSwitchState,
|
||||||
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
|
IsNowCheap = effectiveIsNowCheap,
|
||||||
|
NextCheapIntervalStart = nextCheapInterval
|
||||||
|
};
|
||||||
|
|
||||||
|
await _entityService.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
|
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||||
|
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExecuteBoilerAction(BoilerAction action, string switchEntityId)
|
||||||
|
{
|
||||||
|
switch (action)
|
||||||
|
{
|
||||||
|
case BoilerAction.TurnOn:
|
||||||
|
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
||||||
|
_waterReadyService.NotifyTurnedOn();
|
||||||
|
break;
|
||||||
|
case BoilerAction.TurnOff:
|
||||||
|
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
||||||
|
break;
|
||||||
|
case BoilerAction.NoChange:
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BoilerMonitorConfig ReadConfigFromHaEntities()
|
||||||
|
{
|
||||||
|
var powerEntityId = _haContext.GetState(ConfigPowerEntityId)?.State;
|
||||||
|
var switchEntityId = _haContext.GetState(ConfigSwitchEntityId)?.State;
|
||||||
|
|
||||||
|
int? pollInterval = null;
|
||||||
|
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(pollIntervalState)
|
||||||
|
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
|
||||||
|
&& pollIntervalValue > 0)
|
||||||
|
{
|
||||||
|
pollInterval = (int)pollIntervalValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
double? heatingThreshold = null;
|
||||||
|
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(thresholdState)
|
||||||
|
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
|
||||||
|
&& thresholdValue > 0)
|
||||||
|
{
|
||||||
|
heatingThreshold = thresholdValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId,
|
||||||
|
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId,
|
||||||
|
PollIntervalSeconds = pollInterval,
|
||||||
|
HeatingPowerThresholdWatts = heatingThreshold
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private double? ReadSensorDouble(string entityId)
|
||||||
|
{
|
||||||
|
var state = _haContext.GetState(entityId);
|
||||||
|
|
||||||
|
if (state?.State is null or "unavailable" or "unknown")
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
||||||
|
{
|
||||||
|
if (entityState?.Attributes is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
|
||||||
|
{
|
||||||
|
return value switch
|
||||||
|
{
|
||||||
|
bool b => b,
|
||||||
|
string s => bool.TryParse(s, out var parsed) && parsed,
|
||||||
|
_ => false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Attribute not found or not parseable
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName)
|
||||||
|
{
|
||||||
|
if (entityState?.Attributes is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
|
||||||
|
{
|
||||||
|
if (value is string s && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed))
|
||||||
|
{
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Attribute not found or not parseable
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public static class BoilerMonitorServiceRegistration
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var options = configuration
|
||||||
|
.GetSection(BoilerMonitorOptions.SectionName)
|
||||||
|
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
if (!options.Enabled)
|
||||||
|
{
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||||
|
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||||
|
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
|
||||||
|
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||||
|
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||||
|
.AddSingleton(TimeProvider.System)
|
||||||
|
.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
||||||
|
{
|
||||||
|
private readonly Lock _lock = new();
|
||||||
|
private TimeSpan _accumulatedRunTime = TimeSpan.Zero;
|
||||||
|
private int _sessionCount;
|
||||||
|
private bool _isInSession;
|
||||||
|
|
||||||
|
public void RecordPollResult(bool isHeating, TimeSpan pollInterval)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (isHeating)
|
||||||
|
{
|
||||||
|
_accumulatedRunTime += pollInterval;
|
||||||
|
|
||||||
|
if (!_isInSession)
|
||||||
|
{
|
||||||
|
_sessionCount++;
|
||||||
|
_isInSession = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_isInSession = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public RunTimeSnapshot GetSnapshot()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return new RunTimeSnapshot
|
||||||
|
{
|
||||||
|
AccumulatedRunTime = _accumulatedRunTime,
|
||||||
|
SessionCount = _sessionCount,
|
||||||
|
IsInSession = _isInSession
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Reset()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_accumulatedRunTime = TimeSpan.Zero;
|
||||||
|
_sessionCount = 0;
|
||||||
|
_isInSession = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_accumulatedRunTime = accumulatedRunTime;
|
||||||
|
_sessionCount = sessionCount;
|
||||||
|
_isInSession = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerControlService
|
||||||
|
{
|
||||||
|
BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerMonitorEntityService
|
||||||
|
{
|
||||||
|
Task CreateEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task UpdateEntitiesAsync(BoilerMonitorUpdateContext context, CancellationToken cancellationToken = default);
|
||||||
|
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task SetStatusAsync(string status);
|
||||||
|
PersistedBoilerState? ReadPersistedState();
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerMonitorInit
|
||||||
|
{
|
||||||
|
Task InitializeAsync();
|
||||||
|
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerRunTimeTracker
|
||||||
|
{
|
||||||
|
void RecordPollResult(bool isHeating, TimeSpan pollInterval);
|
||||||
|
RunTimeSnapshot GetSnapshot();
|
||||||
|
void Reset();
|
||||||
|
void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount);
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IWaterReadyService
|
||||||
|
{
|
||||||
|
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
||||||
|
bool IsInCooldown { get; }
|
||||||
|
void NotifyTurnedOn();
|
||||||
|
void ResetCooldown();
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
public string? BoilerPowerEntityId { get; init; }
|
||||||
|
public string? BoilerSwitchEntityId { get; init; }
|
||||||
|
public int? PollIntervalSeconds { get; init; }
|
||||||
|
public double? HeatingPowerThresholdWatts { get; init; }
|
||||||
|
|
||||||
|
public bool IsFullyConfigured =>
|
||||||
|
!string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||||
|
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||||
|
PollIntervalSeconds is > 0 &&
|
||||||
|
HeatingPowerThresholdWatts is > 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public sealed class BoilerMonitorOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "BoilerMonitor";
|
||||||
|
|
||||||
|
public bool Enabled { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup.
|
||||||
|
/// Manual cleanup (e.g. HA button) is not affected.
|
||||||
|
/// </summary>
|
||||||
|
public bool CleanupEntitiesOnStartup { get; init; } = true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record BoilerMonitorUpdateContext
|
||||||
|
{
|
||||||
|
public required TimeSpan TodayRunTime { get; init; }
|
||||||
|
public required TimeSpan RemainingTime { get; init; }
|
||||||
|
public required double BudgetPercentage { get; init; }
|
||||||
|
public required bool BudgetExhausted { get; init; }
|
||||||
|
public required int SessionCount { get; init; }
|
||||||
|
public required double BudgetHours { get; init; }
|
||||||
|
public required bool IsCurrentlyHeating { get; init; }
|
||||||
|
public required bool WaterReady { get; init; }
|
||||||
|
public required string? BoilerSwitchState { get; init; }
|
||||||
|
public required double? BoilerPowerWatts { get; init; }
|
||||||
|
public required bool IsNowCheap { get; init; }
|
||||||
|
public required DateTime? NextCheapIntervalStart { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record PersistedBoilerState
|
||||||
|
{
|
||||||
|
public required TimeSpan AccumulatedRunTime { get; init; }
|
||||||
|
public required int SessionCount { get; init; }
|
||||||
|
public required string? SkipPriceCapState { get; init; }
|
||||||
|
public required string? BudgetOverrideState { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record RunTimeSnapshot
|
||||||
|
{
|
||||||
|
public required TimeSpan AccumulatedRunTime { get; init; }
|
||||||
|
public required int SessionCount { get; init; }
|
||||||
|
public required bool IsInSession { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
||||||
|
{
|
||||||
|
private const string SwitchOnState = "on";
|
||||||
|
private readonly Lock _lock = new();
|
||||||
|
private DateTimeOffset? _lastTurnedOnAt;
|
||||||
|
private DateTimeOffset? _waterReadySince;
|
||||||
|
|
||||||
|
public bool IsInCooldown
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return IsWithinCooldownPeriod();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (IsWithinCooldownPeriod())
|
||||||
|
{
|
||||||
|
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (switchState is null || powerWatts is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsWithinWarmUpGracePeriod())
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Ignoring low power reading ({PowerWatts}W) during warm-up grace period",
|
||||||
|
powerWatts.Value);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var isReady = powerWatts.Value < heatingThresholdWatts;
|
||||||
|
|
||||||
|
if (isReady)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_waterReadySince ??= timeProvider.GetUtcNow();
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation(
|
||||||
|
"Water detected as ready, cooldown period ({CooldownPeriod}) started",
|
||||||
|
BoilerMonitorConsts.WaterReadyCooldownPeriod);
|
||||||
|
}
|
||||||
|
|
||||||
|
return isReady;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void NotifyTurnedOn()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_lastTurnedOnAt = timeProvider.GetUtcNow();
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogDebug("Boiler turn-on recorded, warm-up grace period started ({GracePeriod})", BoilerMonitorConsts.WarmUpGracePeriod);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ResetCooldown()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_waterReadySince = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation("Water ready cooldown has been reset");
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWithinCooldownPeriod()
|
||||||
|
{
|
||||||
|
if (_waterReadySince is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var elapsed = timeProvider.GetUtcNow() - _waterReadySince.Value;
|
||||||
|
return elapsed < BoilerMonitorConsts.WaterReadyCooldownPeriod;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWithinWarmUpGracePeriod()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_lastTurnedOnAt is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var elapsed = timeProvider.GetUtcNow() - _lastTurnedOnAt.Value;
|
||||||
|
return elapsed < BoilerMonitorConsts.WarmUpGracePeriod;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Boiler scheduling configuration read from Home Assistant entity state.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BoilerConfig
|
||||||
|
{
|
||||||
|
public required int IntervalCount { get; init; }
|
||||||
|
|
||||||
|
public required double PriceCap { get; init; }
|
||||||
|
|
||||||
|
public required DateTime Deadline { get; init; }
|
||||||
|
|
||||||
|
public required bool SkipPriceCap { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BoilerMonitor.Models</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
public static class BoilerMonitorConsts
|
||||||
|
{
|
||||||
|
public const int DefaultPollIntervalSeconds = 30;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Power threshold in watts below which the boiler is considered to have finished heating (water ready).
|
||||||
|
/// Also used as the default threshold above which the boiler is considered actively heating.
|
||||||
|
/// </summary>
|
||||||
|
public const double DefaultHeatingPowerThresholdWatts = 5.0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Grace period after the boiler switch is turned on, during which
|
||||||
|
/// low power readings are ignored for "water ready" detection.
|
||||||
|
/// This prevents false positives caused by the heating element ramp-up delay.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly TimeSpan WarmUpGracePeriod = TimeSpan.FromMinutes(2);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cooldown period after the water has been detected as ready,
|
||||||
|
/// during which the boiler will not be turned back on.
|
||||||
|
/// This prevents wasteful on/off cycling when water is already heated.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly TimeSpan WaterReadyCooldownPeriod = TimeSpan.FromHours(1);
|
||||||
|
|
||||||
|
public const int MinPollIntervalSeconds = 5;
|
||||||
|
public const int MaxPollIntervalSeconds = 300;
|
||||||
|
public const int PollIntervalStepSeconds = 5;
|
||||||
|
|
||||||
|
public const double MinHeatingThresholdWatts = 1.0;
|
||||||
|
public const double MaxHeatingThresholdWatts = 100.0;
|
||||||
|
public const double HeatingThresholdStepWatts = 0.5;
|
||||||
|
|
||||||
|
public const string ConfigPowerEntityId = "text.boilermonitor_config_power_entity_id";
|
||||||
|
public const string ConfigSwitchEntityId = "text.boilermonitor_config_switch_entity_id";
|
||||||
|
public const string ConfigPollIntervalEntityId = "number.boilermonitor_config_poll_interval";
|
||||||
|
public const string ConfigHeatingThresholdEntityId = "number.boilermonitor_config_heating_threshold";
|
||||||
|
|
||||||
|
public const string CleanupButtonEntityId = "button.boilermonitor_cleanup";
|
||||||
|
public const string StatusEntityId = "sensor.boilermonitor_status";
|
||||||
|
|
||||||
|
public const string WaterReadyEntityId = "sensor.boilermonitor_water_ready";
|
||||||
|
public const string SkipPriceCapEntityId = "switch.boilermonitor_skip_price_cap";
|
||||||
|
public const string TodayRuntimeEntityId = "sensor.boilermonitor_today_runtime";
|
||||||
|
public const string RemainingTimeEntityId = "sensor.boilermonitor_remaining_time";
|
||||||
|
public const string BudgetPercentageEntityId = "sensor.boilermonitor_budget_percentage";
|
||||||
|
public const string BudgetExhaustedEntityId = "binary_sensor.boilermonitor_budget_exhausted";
|
||||||
|
public const string SessionCountEntityId = "sensor.boilermonitor_session_count";
|
||||||
|
public const string BudgetOverrideEntityId = "switch.boilermonitor_budget_override";
|
||||||
|
|
||||||
|
public const string NordPoolCheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
|
||||||
|
|
||||||
|
public const string BoilerDailyHoursEntityId = "input_number.boiler_daily_hours";
|
||||||
|
public const string BoilerPriceCapEntityId = "input_number.boiler_price_cap";
|
||||||
|
public const string BoilerReadyByEntityId = "input_datetime.boiler_ready_by";
|
||||||
|
|
||||||
|
public const string StatusConfigured = "configured";
|
||||||
|
public const string StatusAwaitingConfiguration = "awaiting_configuration";
|
||||||
|
public const string StatusCleanedUp = "cleaned_up";
|
||||||
|
|
||||||
|
public const string SwitchOnState = "on";
|
||||||
|
|
||||||
|
public const string DeviceIdentifier = "boiler_monitor";
|
||||||
|
public const string DeviceName = "Boiler Monitor";
|
||||||
|
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using HomeAssistant.Models;
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
public class BoilerMonitorEntity : EntityCreateModel
|
||||||
|
{
|
||||||
|
public string Domain { get; set; }
|
||||||
|
public string Identifier { get; set; }
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
public BoilerMonitorEntity(string domain, string identifier, string name)
|
||||||
|
{
|
||||||
|
Domain = domain;
|
||||||
|
Identifier = identifier;
|
||||||
|
EntityId = $"{Domain}.{Identifier}";
|
||||||
|
Name = string.IsNullOrWhiteSpace(name) ? identifier : name;
|
||||||
|
|
||||||
|
Options = new EntityCreationOptions
|
||||||
|
{
|
||||||
|
UniqueId = EntityId,
|
||||||
|
Name = Name
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace NordPoolManager.Models.Enums;
|
namespace BoilerMonitor.Models.Enums;
|
||||||
|
|
||||||
public enum BoilerAction
|
public enum BoilerAction
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the boiler scheduling configuration from Home Assistant entity state.
|
||||||
|
/// </summary>
|
||||||
|
public interface IBoilerConfigReader
|
||||||
|
{
|
||||||
|
BoilerConfig ReadConfig();
|
||||||
|
}
|
||||||
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>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
@@ -7,14 +7,14 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Runtime" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Client" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<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);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
@@ -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>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"isRoot": true,
|
"isRoot": true,
|
||||||
"tools": {
|
"tools": {
|
||||||
"netdaemon.hassmodel.codegen": {
|
"netdaemon.hassmodel.codegen": {
|
||||||
"version": "26.3.0",
|
"version": "26.11.0",
|
||||||
"commands": [
|
"commands": [
|
||||||
"nd-codegen"
|
"nd-codegen"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -34,21 +34,29 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AutoMapper" Version="16.1.1" />
|
<PackageReference Include="AutoMapper" Version="16.1.1" />
|
||||||
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Runtime" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Client" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
|
||||||
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||||
<ProjectReference Include="..\Mappings\Mappings.csproj" />
|
<ProjectReference Include="..\Mappings\Mappings.csproj" />
|
||||||
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
||||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
||||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.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>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,11 @@
|
|||||||
"Override": {
|
"Override": {
|
||||||
"System.Net.Http.HttpClient": "Warning",
|
"System.Net.Http.HttpClient": "Warning",
|
||||||
"NordPoolManager": "Information",
|
"NordPoolManager": "Information",
|
||||||
"PowerMonitorManager": "Information"
|
"PowerMonitorManager": "Information",
|
||||||
|
"BoilerMonitorManager": "Information",
|
||||||
|
"ShowerMonitorManager": "Information",
|
||||||
|
"LightMonitorManager": "Information",
|
||||||
|
"BatteryMonitorManager": "Information"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"WriteTo": [
|
"WriteTo": [
|
||||||
@@ -26,7 +30,42 @@
|
|||||||
"OutputFile": "HomeAssistantGenerated.cs",
|
"OutputFile": "HomeAssistantGenerated.cs",
|
||||||
"UseAttributeBaseClasses" : "false"
|
"UseAttributeBaseClasses" : "false"
|
||||||
},
|
},
|
||||||
|
"NordPool": {
|
||||||
|
"CleanupEntitiesOnStartup": false
|
||||||
|
},
|
||||||
|
"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"]
|
||||||
|
},
|
||||||
|
"BatteryMonitor": {
|
||||||
|
"Enabled": true,
|
||||||
|
"BatteryThresholdPercent": 5
|
||||||
|
},
|
||||||
"PowerMonitor": {
|
"PowerMonitor": {
|
||||||
|
"Enabled": false,
|
||||||
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
||||||
"PollIntervalSeconds": 1,
|
"PollIntervalSeconds": 1,
|
||||||
"SmoothingWindowSize": 10,
|
"SmoothingWindowSize": 10,
|
||||||
|
|||||||
@@ -12,11 +12,19 @@ using NetDaemon.Extensions.MqttEntityManager;
|
|||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using NetDaemon.Extensions.Tts;
|
using NetDaemon.Extensions.Tts;
|
||||||
using NetDaemon.Runtime;
|
using NetDaemon.Runtime;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
using NordPoolManager;
|
using NordPoolManager;
|
||||||
using NordPoolManager.Interface;
|
using NordPoolManager.Interface;
|
||||||
|
using NordPoolManager.Models;
|
||||||
using PowerMonitorManager;
|
using PowerMonitorManager;
|
||||||
using PowerMonitorManager.Interface;
|
|
||||||
using PowerMonitorManager.Models;
|
using PowerMonitorManager.Models;
|
||||||
|
using ShowerMonitorManager;
|
||||||
|
using ShowerMonitorManager.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
|
using LightMonitorManager.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
|
|
||||||
#pragma warning disable CA1812
|
#pragma warning disable CA1812
|
||||||
|
|
||||||
@@ -43,17 +51,20 @@ try
|
|||||||
config.AddProfile<GlobalMappingProfile>();
|
config.AddProfile<GlobalMappingProfile>();
|
||||||
})
|
})
|
||||||
.AddTransient<IEntityManager, EntityManager>()
|
.AddTransient<IEntityManager, EntityManager>()
|
||||||
|
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
||||||
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
|
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
|
||||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||||
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||||
.Configure<PowerMonitorOptions>(
|
.AddPowerMonitor(context.Configuration)
|
||||||
context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
||||||
.AddNetDaemonApp<PowerMonitorInit>()
|
.AddBoilerMonitor(context.Configuration)
|
||||||
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
|
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
|
||||||
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
|
.AddShowerMonitor(context.Configuration)
|
||||||
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
|
.Configure<LightMonitorOptions>(context.Configuration.GetSection(LightMonitorOptions.SectionName))
|
||||||
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
|
.AddLightMonitor(context.Configuration)
|
||||||
|
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
|
||||||
|
.AddBatteryMonitor(context.Configuration)
|
||||||
)
|
)
|
||||||
.Build()
|
.Build()
|
||||||
.RunAsync()
|
.RunAsync()
|
||||||
|
|||||||
@@ -20,6 +20,38 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager", "Pow
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{1F613F65-5F3C-41E6-B86B-774301D80E42}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{1F613F65-5F3C-41E6-B86B-774301D80E42}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Models", "BoilerMonitor.Models\BoilerMonitor.Models.csproj", "{72331F53-884D-42A1-8EEA-8CC83FFAB623}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Manager", "BoilerMonitor.Manager\BoilerMonitor.Manager.csproj", "{488964A2-C7A2-45C9-9CDB-98515AFD7242}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Manager.Tests", "BoilerMonitor.Manager.Tests\BoilerMonitor.Manager.Tests.csproj", "{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}"
|
||||||
|
EndProject
|
||||||
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E98121-7DA4-4085-A8E3-B0430628452F}"
|
||||||
|
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
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -150,8 +182,187 @@ Global
|
|||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x64.Build.0 = Release|Any CPU
|
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.ActiveCfg = Release|Any CPU
|
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.Build.0 = Release|Any CPU
|
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{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
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
|
GlobalSection(NestedProjects) = preSolution
|
||||||
|
{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
|
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>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user