Files
HomeAssistant/PowerMonitor.Manager/PowerMonitorEntityService.cs
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00

412 lines
19 KiB
C#

#region
using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using PowerMonitor.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
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 const string TriggerLimitBreachButtonEntityId = "button.powermonitor_trigger_limit_breach";
private static readonly string[] SystemEntityIds =
[
TotalPowerEntityId,
TotalCost15MinEntityId, TotalCost1HEntityId, TotalCostDailyEntityId, TotalCostMonthlyEntityId,
OtherPowerEntityId,
OtherCost15MinEntityId, OtherCost1HEntityId, OtherCostDailyEntityId, OtherCostMonthlyEntityId,
AnomalyEntityId,
StatusEntityId,
RediscoverButtonEntityId,
TriggerLimitBreachButtonEntityId
];
public async Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var entities = GetSystemEntitiesList();
var tasks = entities.Select(async entity =>
{
try
{
if (logger.IsEnabled(LogLevel.Information))
{
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(GetPowerDeviceEntitiesNames).ToList();
var tasks = entities.Select(async entity =>
{
try
{
if (logger.IsEnabled(LogLevel.Information))
{
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 RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var tasks = SystemEntityIds.Select(entityManager.RemoveEntity);
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 RemoveDeviceEntitiesAsync(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);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Entity removed: {EntityId}", id);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to remove device entity: {EntityId}", id);
}
});
await Task.WhenAll(tasks).ConfigureAwait(false);
}
internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList()
{
return new List<PowerMonitorEntity>
{
new PowerMonitorEntity("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 PowerMonitorEntity("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 PowerMonitorEntity("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"),
new PowerMonitorEntity("sensor", "powermonitor_status", "PowerMonitor status"),
new PowerMonitorEntity("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
{
AdditionalConfig = new { icon = "mdi:refresh" }
},
new PowerMonitorEntity("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
{
AdditionalConfig = new { icon = "mdi:flash-alert" }
}
};
}
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> GetPowerDeviceEntitiesNames(PowerSensorInfo sensor)
{
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId);
return
[
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
[
$"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);
}
}
}