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
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerMonitorEntityService(
|
||||
@@ -44,48 +48,50 @@ public sealed class PowerMonitorEntityService(
|
||||
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);
|
||||
}
|
||||
});
|
||||
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 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);
|
||||
}
|
||||
});
|
||||
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);
|
||||
}
|
||||
@@ -100,22 +106,22 @@ public sealed class PowerMonitorEntityService(
|
||||
{
|
||||
UpdateTotalPowerAsync(context, timestamp),
|
||||
UpdateCostEntityAsync(TotalCost15MinEntityId, context.TotalCost.Cost15Min, context.TotalCost,
|
||||
"Total cost (15 min)", timestamp),
|
||||
"Total cost (15 min)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCost1HEntityId, context.TotalCost.Cost1Hour, context.TotalCost,
|
||||
"Total cost (1h)", timestamp),
|
||||
"Total cost (1h)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCostDailyEntityId, context.TotalCost.CostDaily, context.TotalCost,
|
||||
"Total cost (daily)", timestamp),
|
||||
"Total cost (daily)", timestamp),
|
||||
UpdateCostEntityAsync(TotalCostMonthlyEntityId, context.TotalCost.CostMonthly, context.TotalCost,
|
||||
"Total cost (monthly)", timestamp),
|
||||
"Total cost (monthly)", timestamp),
|
||||
UpdateOtherPowerAsync(context, timestamp),
|
||||
UpdateCostEntityAsync(OtherCost15MinEntityId, context.OtherCost.Cost15Min, context.OtherCost,
|
||||
"Other cost (15 min)", timestamp),
|
||||
"Other cost (15 min)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCost1HEntityId, context.OtherCost.Cost1Hour, context.OtherCost,
|
||||
"Other cost (1h)", timestamp),
|
||||
"Other cost (1h)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCostDailyEntityId, context.OtherCost.CostDaily, context.OtherCost,
|
||||
"Other cost (daily)", timestamp),
|
||||
"Other cost (daily)", timestamp),
|
||||
UpdateCostEntityAsync(OtherCostMonthlyEntityId, context.OtherCost.CostMonthly, context.OtherCost,
|
||||
"Other cost (monthly)", timestamp),
|
||||
"Other cost (monthly)", timestamp),
|
||||
UpdateAnomalyAsync(context, timestamp),
|
||||
UpdateStatusAsync(context, timestamp)
|
||||
};
|
||||
@@ -123,14 +129,18 @@ public sealed class PowerMonitorEntityService(
|
||||
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));
|
||||
costSnapshot, $"{deviceName} cost (15 min)", timestamp));
|
||||
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour,
|
||||
costSnapshot, $"{deviceName} cost (1h)", timestamp));
|
||||
costSnapshot, $"{deviceName} cost (1h)", timestamp));
|
||||
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily,
|
||||
costSnapshot, $"{deviceName} cost (daily)", timestamp));
|
||||
costSnapshot, $"{deviceName} cost (daily)", timestamp));
|
||||
|
||||
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly,
|
||||
costSnapshot, $"{deviceName} cost (monthly)", timestamp));
|
||||
costSnapshot, $"{deviceName} cost (monthly)", timestamp));
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
@@ -175,40 +185,43 @@ public sealed class PowerMonitorEntityService(
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up PowerMonitor entities");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames,
|
||||
CancellationToken cancellationToken = default)
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var entityIds = removedDeviceNames.SelectMany(GetDeviceCostEntityIds).ToList();
|
||||
|
||||
var tasks = entityIds.Select(async id =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await entityManager.RemoveEntity(id).ConfigureAwait(false);
|
||||
{
|
||||
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);
|
||||
}
|
||||
});
|
||||
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("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
||||
new PowerMonitorEntity("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
||||
{
|
||||
AdditionalConfig = new
|
||||
{
|
||||
@@ -221,7 +234,7 @@ public sealed class PowerMonitorEntityService(
|
||||
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")
|
||||
new PowerMonitorEntity("sensor", "powermonitor_other_power", "PowerMonitor other power")
|
||||
{
|
||||
AdditionalConfig = new
|
||||
{
|
||||
@@ -234,13 +247,13 @@ public sealed class PowerMonitorEntityService(
|
||||
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")
|
||||
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("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
|
||||
new PowerMonitorEntity("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
|
||||
{
|
||||
AdditionalConfig = new { icon = "mdi:flash-alert" }
|
||||
}
|
||||
@@ -263,6 +276,7 @@ public sealed class PowerMonitorEntityService(
|
||||
internal static IEnumerable<PowerMonitorEntity> GetPowerDeviceEntitiesNames(PowerSensorInfo sensor)
|
||||
{
|
||||
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId);
|
||||
|
||||
return
|
||||
[
|
||||
CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"),
|
||||
@@ -287,76 +301,89 @@ public sealed class PowerMonitorEntityService(
|
||||
{
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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)
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user