feat: add PowerMonitorEntityService with system and per-device MQTT entities

Made-with: Cursor
This commit is contained in:
Marius
2026-03-17 12:57:45 +02:00
parent 7f0ebcf826
commit 33d915f7b4
3 changed files with 679 additions and 0 deletions
@@ -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);
}
}
}