feat: add PowerMonitorEntityService with system and per-device MQTT entities
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,325 @@
|
||||
using FluentAssertions;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
private readonly Mock<IEntityManager> _entityManagerMock;
|
||||
private readonly Mock<ILogger<PowerMonitorEntityService>> _loggerMock;
|
||||
private readonly PowerMonitorEntityService _sut;
|
||||
|
||||
public PowerMonitorEntityServiceTests()
|
||||
{
|
||||
_entityManagerMock = new Mock<IEntityManager>();
|
||||
_loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
|
||||
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object);
|
||||
}
|
||||
|
||||
#region GetSystemEntitiesList
|
||||
|
||||
[Fact]
|
||||
public void GetSystemEntitiesList_ShouldReturnAll13SystemEntities()
|
||||
{
|
||||
var result = _sut.GetSystemEntitiesList();
|
||||
|
||||
result.Should().HaveCount(13);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSystemEntitiesList_ShouldContainAllExpectedEntityIds()
|
||||
{
|
||||
var result = _sut.GetSystemEntitiesList();
|
||||
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_power");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_15min");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_1h");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_daily");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_monthly");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_power");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_15min");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_1h");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_daily");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_monthly");
|
||||
result.Should().Contain(e => e.EntityId == "binary_sensor.powermonitor_anomaly");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_status");
|
||||
result.Should().Contain(e => e.EntityId == "button.powermonitor_rediscover_sensors");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds()
|
||||
{
|
||||
var result = _sut.GetSystemEntitiesList();
|
||||
|
||||
result.Select(e => e.EntityId).Should().OnlyHaveUniqueItems();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetDeviceEntities
|
||||
|
||||
[Fact]
|
||||
public void GetDeviceEntities_ShouldReturn4CostEntitiesPerDevice()
|
||||
{
|
||||
var sensor = new PowerSensorInfo
|
||||
{
|
||||
EntityId = "sensor.sonoff_1002230e32_power",
|
||||
FriendlyName = "Sonoff Power",
|
||||
DeviceName = "sonoff_1002230e32"
|
||||
};
|
||||
|
||||
var result = PowerMonitorEntityService.GetDeviceEntities(sensor).ToList();
|
||||
|
||||
result.Should().HaveCount(4);
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_15min");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_1h");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_daily");
|
||||
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_monthly");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetDeviceCostEntityIds
|
||||
|
||||
[Fact]
|
||||
public void GetDeviceCostEntityIds_ShouldReturn4EntityIds()
|
||||
{
|
||||
var result = PowerMonitorEntityService.GetDeviceCostEntityIds("sonoff_abc").ToList();
|
||||
|
||||
result.Should().HaveCount(4);
|
||||
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_15min");
|
||||
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_1h");
|
||||
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_daily");
|
||||
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_monthly");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CreateSystemEntitiesAsync
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSystemEntitiesAsync_ShouldCreateAll13Entities()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await _sut.CreateSystemEntitiesAsync();
|
||||
|
||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(13));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSystemEntitiesAsync_WhenOneEntityFails_ShouldContinueWithOthers()
|
||||
{
|
||||
var callCount = 0;
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
|
||||
.Returns(() =>
|
||||
{
|
||||
callCount++;
|
||||
if (callCount == 3)
|
||||
{
|
||||
throw new InvalidOperationException("Entity creation failed");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
await _sut.CreateSystemEntitiesAsync();
|
||||
|
||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(13));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CreateDeviceEntitiesAsync
|
||||
|
||||
[Fact]
|
||||
public async Task CreateDeviceEntitiesAsync_ShouldCreate4EntitiesPerDevice()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
var sensors = new List<PowerSensorInfo>
|
||||
{
|
||||
new() { EntityId = "sensor.device_a_power", FriendlyName = "Device A", DeviceName = "device_a" },
|
||||
new() { EntityId = "sensor.device_b_power", FriendlyName = "Device B", DeviceName = "device_b" }
|
||||
};
|
||||
|
||||
await _sut.CreateDeviceEntitiesAsync(sensors);
|
||||
|
||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(8));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ResetEntitiesAsync
|
||||
|
||||
[Fact]
|
||||
public async Task ResetEntitiesAsync_ShouldSetDefaultStates()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await _sut.ResetEntitiesAsync();
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "0"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "0"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "initializing"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(12));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CleanupEntitiesAsync
|
||||
|
||||
[Fact]
|
||||
public async Task CleanupEntitiesAsync_ShouldRemoveAllSystemEntities()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await _sut.CleanupEntitiesAsync();
|
||||
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(13));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CleanupDeviceEntitiesAsync
|
||||
|
||||
[Fact]
|
||||
public async Task CleanupDeviceEntitiesAsync_ShouldRemove4EntitiesPerDevice()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
await _sut.CleanupDeviceEntitiesAsync(["device_a", "device_b"]);
|
||||
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(8));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region UpdateEntitiesAsync
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateEntitiesAsync_ShouldUpdateAllSystemEntities()
|
||||
{
|
||||
_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);
|
||||
|
||||
var context = CreateDefaultContext();
|
||||
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", It.IsAny<string>()), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateEntitiesAsync_WithDeviceCosts_ShouldUpdateDeviceEntities()
|
||||
{
|
||||
_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);
|
||||
|
||||
var context = CreateDefaultContext();
|
||||
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_15min", It.IsAny<string>()), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_1h", It.IsAny<string>()), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_daily", It.IsAny<string>()), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_monthly", It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateEntitiesAsync_WhenAnomaly_ShouldSetAnomalyOn()
|
||||
{
|
||||
_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);
|
||||
|
||||
var context = CreateDefaultContext(isAnomaly: true);
|
||||
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "on"), Times.Once);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region SetEntityStateSafe / SetEntityAttributesSafe
|
||||
|
||||
[Fact]
|
||||
public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
|
||||
|
||||
await act.Should().NotThrowAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { });
|
||||
|
||||
await act.Should().NotThrowAsync();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private static PowerUpdateContext CreateDefaultContext(bool isAnomaly = false)
|
||||
{
|
||||
return new PowerUpdateContext
|
||||
{
|
||||
Calculation = new PowerCalculationResult
|
||||
{
|
||||
TotalPowerWatts = 1000,
|
||||
KnownDevicesSumWatts = 800,
|
||||
RawOtherPowerWatts = 200,
|
||||
SmoothedOtherPowerWatts = 195,
|
||||
DataQuality = "ok",
|
||||
DevicePowerReadings = new Dictionary<string, double>
|
||||
{
|
||||
["sensor.device_a_power"] = 500,
|
||||
["sensor.device_b_power"] = 300
|
||||
}
|
||||
},
|
||||
CurrentNordPoolPrice = 0.10,
|
||||
PriceUnit = "EUR/kWh",
|
||||
PriceSource = "live",
|
||||
DeviceCosts = new Dictionary<string, CostSnapshot>
|
||||
{
|
||||
["sensor.device_a_power"] = new() { Cost15Min = 0.01, Cost1Hour = 0.04, CostDaily = 0.50, CostMonthly = 15.0 },
|
||||
["sensor.device_b_power"] = new() { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.30, CostMonthly = 9.0 }
|
||||
},
|
||||
TotalCost = new CostSnapshot { Cost15Min = 0.02, Cost1Hour = 0.08, CostDaily = 1.00, CostMonthly = 30.0 },
|
||||
OtherCost = new CostSnapshot { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.20, CostMonthly = 6.0 },
|
||||
IsAnomaly = isAnomaly,
|
||||
AnomalyDuration = TimeSpan.Zero,
|
||||
AnomalyThresholdWatts = 500,
|
||||
TrackedSensorCount = 2,
|
||||
DegradedSensors = [],
|
||||
SystemStatus = "ok"
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerMonitorEntityService
|
||||
{
|
||||
Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors, CancellationToken cancellationToken = default);
|
||||
Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default);
|
||||
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
Task CleanupDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
using System.Globalization;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerMonitorEntityService(
|
||||
IEntityManager entityManager,
|
||||
ILogger<PowerMonitorEntityService> logger) : IPowerMonitorEntityService
|
||||
{
|
||||
private const string TotalPowerEntityId = "sensor.powermonitor_total_power";
|
||||
private const string TotalCost15MinEntityId = "sensor.powermonitor_total_cost_15min";
|
||||
private const string TotalCost1HEntityId = "sensor.powermonitor_total_cost_1h";
|
||||
private const string TotalCostDailyEntityId = "sensor.powermonitor_total_cost_daily";
|
||||
private const string TotalCostMonthlyEntityId = "sensor.powermonitor_total_cost_monthly";
|
||||
private const string OtherPowerEntityId = "sensor.powermonitor_other_power";
|
||||
private const string OtherCost15MinEntityId = "sensor.powermonitor_other_cost_15min";
|
||||
private const string OtherCost1HEntityId = "sensor.powermonitor_other_cost_1h";
|
||||
private const string OtherCostDailyEntityId = "sensor.powermonitor_other_cost_daily";
|
||||
private const string OtherCostMonthlyEntityId = "sensor.powermonitor_other_cost_monthly";
|
||||
private const string AnomalyEntityId = "binary_sensor.powermonitor_anomaly";
|
||||
private const string StatusEntityId = "sensor.powermonitor_status";
|
||||
private const string RediscoverButtonEntityId = "button.powermonitor_rediscover_sensors";
|
||||
|
||||
private static readonly string[] SystemEntityIds =
|
||||
[
|
||||
TotalPowerEntityId,
|
||||
TotalCost15MinEntityId, TotalCost1HEntityId, TotalCostDailyEntityId, TotalCostMonthlyEntityId,
|
||||
OtherPowerEntityId,
|
||||
OtherCost15MinEntityId, OtherCost1HEntityId, OtherCostDailyEntityId, OtherCostMonthlyEntityId,
|
||||
AnomalyEntityId,
|
||||
StatusEntityId,
|
||||
RediscoverButtonEntityId
|
||||
];
|
||||
|
||||
public async Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var entities = GetSystemEntitiesList();
|
||||
var tasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Creating 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(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var entities = sensors.SelectMany(GetDeviceEntities).ToList();
|
||||
var tasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create device cost entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var timestamp = DateTime.UtcNow.ToString("O");
|
||||
|
||||
var tasks = new List<Task>
|
||||
{
|
||||
UpdateTotalPowerAsync(context, timestamp),
|
||||
UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost, "Total cost (15 min)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost, "Total cost (1h)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost, "Total cost (daily)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost, "Total cost (monthly)", timestamp),
|
||||
UpdateOtherPowerAsync(context, timestamp),
|
||||
UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost, "Other cost (15 min)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost, "Other cost (1h)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost, "Other cost (daily)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost, "Other cost (monthly)", timestamp),
|
||||
UpdateAnomalyAsync(context, timestamp),
|
||||
UpdateStatusAsync(context, timestamp)
|
||||
};
|
||||
|
||||
foreach (var (entityId, costSnapshot) in context.DeviceCosts)
|
||||
{
|
||||
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(entityId);
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min, costSnapshot, $"{deviceName} cost (15 min)", timestamp));
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour, costSnapshot, $"{deviceName} cost (1h)", timestamp));
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily, costSnapshot, $"{deviceName} cost (daily)", timestamp));
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly, costSnapshot, $"{deviceName} cost (monthly)", timestamp));
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var tasks = new[]
|
||||
{
|
||||
SetEntityStateSafe(TotalPowerEntityId, "0"),
|
||||
SetEntityStateSafe(TotalCost15MinEntityId, "0"),
|
||||
SetEntityStateSafe(TotalCost1HEntityId, "0"),
|
||||
SetEntityStateSafe(TotalCostDailyEntityId, "0"),
|
||||
SetEntityStateSafe(TotalCostMonthlyEntityId, "0"),
|
||||
SetEntityStateSafe(OtherPowerEntityId, "0"),
|
||||
SetEntityStateSafe(OtherCost15MinEntityId, "0"),
|
||||
SetEntityStateSafe(OtherCost1HEntityId, "0"),
|
||||
SetEntityStateSafe(OtherCostDailyEntityId, "0"),
|
||||
SetEntityStateSafe(OtherCostMonthlyEntityId, "0"),
|
||||
SetEntityStateSafe(AnomalyEntityId, "off"),
|
||||
SetEntityStateSafe(StatusEntityId, "initializing")
|
||||
};
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
logger.LogInformation("All PowerMonitor entity states reset to defaults");
|
||||
}
|
||||
|
||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
var tasks = SystemEntityIds.Select(id => entityManager.RemoveEntity(id));
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
logger.LogInformation("PowerMonitor system entities cleaned up");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up PowerMonitor entities");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CleanupDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var entityIds = removedDeviceNames.SelectMany(GetDeviceCostEntityIds).ToList();
|
||||
var tasks = entityIds.Select(async id =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.RemoveEntity(id).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to remove device entity: {EntityId}", id);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal ICollection<PowerMonitorEntity> GetSystemEntitiesList()
|
||||
{
|
||||
return new List<PowerMonitorEntity>
|
||||
{
|
||||
new("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
||||
{
|
||||
AdditionalConfig = new { unit_of_measurement = PowerMonitorConsts.WattUnit, device_class = PowerMonitorConsts.PowerDeviceClass, state_class = PowerMonitorConsts.MeasurementStateClass }
|
||||
},
|
||||
CreateCostEntity("powermonitor_total_cost_15min", "PowerMonitor total cost (15 min)"),
|
||||
CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"),
|
||||
CreateCostEntity("powermonitor_total_cost_daily", "PowerMonitor total cost (daily)"),
|
||||
CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"),
|
||||
new("sensor", "powermonitor_other_power", "PowerMonitor other power")
|
||||
{
|
||||
AdditionalConfig = new { unit_of_measurement = PowerMonitorConsts.WattUnit, device_class = PowerMonitorConsts.PowerDeviceClass, state_class = PowerMonitorConsts.MeasurementStateClass }
|
||||
},
|
||||
CreateCostEntity("powermonitor_other_cost_15min", "PowerMonitor other cost (15 min)"),
|
||||
CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"),
|
||||
CreateCostEntity("powermonitor_other_cost_daily", "PowerMonitor other cost (daily)"),
|
||||
CreateCostEntity("powermonitor_other_cost_monthly", "PowerMonitor other cost (monthly)"),
|
||||
new("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"),
|
||||
new("sensor", "powermonitor_status", "PowerMonitor status"),
|
||||
new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
|
||||
{
|
||||
AdditionalConfig = new { icon = "mdi:refresh" }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static PowerMonitorEntity CreateCostEntity(string identifier, string name)
|
||||
{
|
||||
return new PowerMonitorEntity("sensor", identifier, name)
|
||||
{
|
||||
AdditionalConfig = new
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.EurUnit,
|
||||
device_class = PowerMonitorConsts.MonetaryDeviceClass,
|
||||
state_class = PowerMonitorConsts.TotalStateClass
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
internal static IEnumerable<PowerMonitorEntity> GetDeviceEntities(PowerSensorInfo sensor)
|
||||
{
|
||||
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId);
|
||||
return new[]
|
||||
{
|
||||
CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"),
|
||||
CreateCostEntity($"powermonitor_{deviceName}_cost_1h", $"{sensor.FriendlyName} cost (1h)"),
|
||||
CreateCostEntity($"powermonitor_{deviceName}_cost_daily", $"{sensor.FriendlyName} cost (daily)"),
|
||||
CreateCostEntity($"powermonitor_{deviceName}_cost_monthly", $"{sensor.FriendlyName} cost (monthly)")
|
||||
};
|
||||
}
|
||||
|
||||
internal static IEnumerable<string> GetDeviceCostEntityIds(string deviceName)
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
$"sensor.powermonitor_{deviceName}_cost_15min",
|
||||
$"sensor.powermonitor_{deviceName}_cost_1h",
|
||||
$"sensor.powermonitor_{deviceName}_cost_daily",
|
||||
$"sensor.powermonitor_{deviceName}_cost_monthly"
|
||||
};
|
||||
}
|
||||
|
||||
private async Task UpdateTotalPowerAsync(PowerUpdateContext context, string timestamp)
|
||||
{
|
||||
var value = context.Calculation.TotalPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
|
||||
await SetEntityStateSafe(TotalPowerEntityId, value).ConfigureAwait(false);
|
||||
await SetEntityAttributesSafe(TotalPowerEntityId, new
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||
state_class = PowerMonitorConsts.MeasurementStateClass,
|
||||
friendly_name = "PowerMonitor total power",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateOtherPowerAsync(PowerUpdateContext context, string timestamp)
|
||||
{
|
||||
var value = context.Calculation.SmoothedOtherPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
|
||||
await SetEntityStateSafe(OtherPowerEntityId, value).ConfigureAwait(false);
|
||||
await SetEntityAttributesSafe(OtherPowerEntityId, new
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.WattUnit,
|
||||
device_class = PowerMonitorConsts.PowerDeviceClass,
|
||||
state_class = PowerMonitorConsts.MeasurementStateClass,
|
||||
friendly_name = "PowerMonitor other power",
|
||||
raw_power = context.Calculation.RawOtherPowerWatts,
|
||||
smoothed_power = context.Calculation.SmoothedOtherPowerWatts,
|
||||
data_quality = context.Calculation.DataQuality,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateCostEntityAsync(string entityId, double costValue, CostSnapshot snapshot, string friendlyName, string timestamp)
|
||||
{
|
||||
var value = costValue.ToString("F4", CultureInfo.InvariantCulture);
|
||||
await SetEntityStateSafe(entityId, value).ConfigureAwait(false);
|
||||
await SetEntityAttributesSafe(entityId, new
|
||||
{
|
||||
unit_of_measurement = PowerMonitorConsts.EurUnit,
|
||||
device_class = PowerMonitorConsts.MonetaryDeviceClass,
|
||||
state_class = PowerMonitorConsts.TotalStateClass,
|
||||
friendly_name = friendlyName,
|
||||
partial_window = snapshot.PartialWindow,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateAnomalyAsync(PowerUpdateContext context, string timestamp)
|
||||
{
|
||||
var state = context.IsAnomaly ? "on" : "off";
|
||||
await SetEntityStateSafe(AnomalyEntityId, state).ConfigureAwait(false);
|
||||
await SetEntityAttributesSafe(AnomalyEntityId, new
|
||||
{
|
||||
friendly_name = "PowerMonitor anomaly",
|
||||
smoothed_watts = context.Calculation.SmoothedOtherPowerWatts,
|
||||
threshold = context.AnomalyThresholdWatts,
|
||||
duration_above = context.AnomalyDuration.TotalSeconds,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateStatusAsync(PowerUpdateContext context, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(StatusEntityId, context.SystemStatus).ConfigureAwait(false);
|
||||
await SetEntityAttributesSafe(StatusEntityId, new
|
||||
{
|
||||
friendly_name = "PowerMonitor status",
|
||||
tracked_sensors_count = context.TrackedSensorCount,
|
||||
degraded_sensors = context.DegradedSensors,
|
||||
price_source = context.PriceSource,
|
||||
current_price = context.CurrentNordPoolPrice,
|
||||
price_unit = context.PriceUnit,
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal async Task SetEntityStateSafe(string entityId, string state)
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task SetEntityAttributesSafe(string entityId, object attributes)
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user