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:
2026-12-01 12:33:31 +02:00
parent 77458383d1
commit f919d6b25b
115 changed files with 3115 additions and 1959 deletions
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IOtherPowerCalculationService
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IPowerCostCalculationService
@@ -1,6 +1,10 @@
#region
using PowerMonitor.Models;
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IPowerMonitorEntityService
@@ -8,12 +12,12 @@ public interface IPowerMonitorEntityService
Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default);
Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors,
CancellationToken cancellationToken = default);
CancellationToken cancellationToken = default);
Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default);
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
Task RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default);
Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames,
CancellationToken cancellationToken = default);
CancellationToken cancellationToken = default);
}
@@ -1,5 +1,9 @@
#region
using PowerMonitor.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IPowerSensorDiscoveryService
@@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models;
public sealed class CostAccumulator(DateTime now)
{
private readonly Lock _lock = new();
private readonly Lock _lock = new Lock();
private double _cost15Min;
private double _cost1Hour;
@@ -77,7 +77,10 @@ public sealed class CostAccumulator(DateTime now)
_lastDailyReset = now;
}
if (!IsNewMonthWindow(now, _lastMonthlyReset)) return;
if (!IsNewMonthWindow(now, _lastMonthlyReset))
{
return;
}
_previousMonthly = _costMonthly;
_costMonthly = 0;
@@ -88,6 +91,7 @@ public sealed class CostAccumulator(DateTime now)
{
var currentSlot = now.Minute / 15;
var lastSlot = lastReset.Minute / 15;
return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot;
}
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager.Models;
public sealed class PowerMonitorOptions
@@ -1,13 +1,17 @@
#region
using Microsoft.Extensions.Options;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager;
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
{
private readonly double _alpha;
private readonly Lock _lock = new();
private readonly Lock _lock = new Lock();
private double? _previousSmoothed;
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
@@ -29,11 +33,13 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
}
double smoothed;
lock (_lock)
{
smoothed = _previousSmoothed.HasValue
? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
: rawOther;
? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
: rawOther;
_previousSmoothed = smoothed;
}
@@ -1,15 +1,19 @@
#region
using System.Collections.Concurrent;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
public sealed class PowerCostCalculationService : IPowerCostCalculationService
{
private readonly Lock _accumulatorLock = new();
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
private readonly Lock _priceLock = new();
private readonly Lock _accumulatorLock = new Lock();
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new ConcurrentDictionary<string, CostAccumulator>();
private readonly Lock _priceLock = new Lock();
private double _lastKnownPrice;
private CostAccumulator? _otherAccumulator;
@@ -38,8 +42,10 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
}
}
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds,
DateTime now)
public void RecordCosts(PowerCalculationResult calculation,
double nordPoolPrice,
int pollIntervalSeconds,
DateTime now)
{
lock (_priceLock)
{
@@ -57,6 +63,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
var otherCost =
CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
GetOrCreateOtherAccumulator(now).AddCost(otherCost, now);
foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings)
@@ -86,8 +93,8 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
public IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots()
{
return _deviceAccumulators.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.GetSnapshot());
kvp => kvp.Key,
kvp => kvp.Value.GetSnapshot());
}
public void SetPrice(double price)
@@ -102,13 +109,14 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
public CostSnapshot GetDeviceCostSnapshot(string entityId)
{
return _deviceAccumulators.TryGetValue(entityId, out var accumulator)
? accumulator.GetSnapshot()
: CreateEmptySnapshot();
? accumulator.GetSnapshot()
: CreateEmptySnapshot();
}
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
{
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
return powerKw * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
}
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -7,6 +9,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
public sealed class PowerLimitEnforcementService(
@@ -25,13 +29,17 @@ public sealed class PowerLimitEnforcementService(
public void EnforceLimit(double currentPowerWatts)
{
if (!_options.EnforceLimitEnabled) return;
if (!_options.EnforceLimitEnabled)
{
return;
}
var now = timeProvider.GetUtcNow();
if (!IsLimitActive)
{
TryEnforce(currentPowerWatts, now);
return;
}
@@ -43,6 +51,7 @@ public sealed class PowerLimitEnforcementService(
if (IsLimitActive)
{
logger.LogInformation("Debug: trigger requested but limit already active");
return;
}
@@ -55,6 +64,7 @@ public sealed class PowerLimitEnforcementService(
if (!IsLimitActive)
{
logger.LogInformation("Debug: reset requested but limit not active");
return;
}
@@ -64,9 +74,15 @@ public sealed class PowerLimitEnforcementService(
private void ExecuteEnforce(double currentPowerWatts)
{
foreach (var entityId in _options.EnforceSwitchOffEntityIds) TurnOff(entityId);
foreach (var entityId in _options.EnforceSwitchOffEntityIds)
{
TurnOff(entityId);
}
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOff(entityId);
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOff(entityId);
}
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
@@ -78,7 +94,10 @@ public sealed class PowerLimitEnforcementService(
private void ExecuteRecover()
{
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification();
@@ -88,22 +107,25 @@ public sealed class PowerLimitEnforcementService(
private void TryEnforce(double currentPowerWatts, DateTimeOffset now)
{
if (currentPowerWatts <= _options.PowerLimitWatts) return;
if (currentPowerWatts <= _options.PowerLimitWatts)
{
return;
}
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping",
currentPowerWatts, _options.PowerLimitWatts);
"Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping",
currentPowerWatts, _options.PowerLimitWatts);
}
return;
}
logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts,
_options.PowerLimitWatts);
_options.PowerLimitWatts);
ExecuteEnforce(currentPowerWatts);
}
@@ -112,12 +134,16 @@ public sealed class PowerLimitEnforcementService(
{
var elapsed = now - _enforcedAt;
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds)) return;
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds))
{
return;
}
if (currentPowerWatts >= _options.PowerLimitWatts)
{
logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced",
currentPowerWatts, _options.PowerLimitWatts);
currentPowerWatts, _options.PowerLimitWatts);
_enforcedAt = now;
return;
@@ -126,11 +152,14 @@ public sealed class PowerLimitEnforcementService(
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors",
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
"Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors",
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
}
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification();
@@ -141,46 +170,46 @@ public sealed class PowerLimitEnforcementService(
private void TurnOff(string entityId)
{
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService,
ServiceTarget.FromEntity(entityId));
ServiceTarget.FromEntity(entityId));
}
private void TurnOn(string entityId)
{
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService,
ServiceTarget.FromEntity(entityId));
ServiceTarget.FromEntity(entityId));
}
private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts)
{
var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt,
limitWatts / PowerMonitorConsts.WattsPerKilowatt);
limitWatts / PowerMonitorConsts.WattsPerKilowatt);
haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationCreateService,
data: new
{
title = PowerMonitorConsts.PowerLimitNotificationTitle,
message,
notification_id = PowerMonitorConsts.PowerLimitNotificationId
});
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationCreateService,
data: new
{
title = PowerMonitorConsts.PowerLimitNotificationTitle,
message,
notification_id = PowerMonitorConsts.PowerLimitNotificationId
});
}
private void DismissLimitNotification()
{
haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationDismissService,
data: new
{
notification_id = PowerMonitorConsts.PowerLimitNotificationId
});
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationDismissService,
data: new
{
notification_id = PowerMonitorConsts.PowerLimitNotificationId
});
}
internal static string BuildLimitMessage(double currentKw, double limitKw)
{
return string.Format(CultureInfo.InvariantCulture,
"Home power usage **{0:F2} kW** exceeded the limit of **{1:F1} kW**.\n\nHigh-power appliances have been turned off and automatic control paused. Normal control resumes after power drops below the limit.",
currentKw, limitKw);
"Home power usage **{0:F2} kW** exceeded the limit of **{1:F1} kW**.\n\nHigh-power appliances have been turned off and automatic control paused. Normal control resumes after power drops below the limit.",
currentKw, limitKw);
}
}
+132 -105
View File
@@ -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)
+75 -46
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -10,6 +12,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
[NetDaemonApp]
@@ -108,6 +112,7 @@ public sealed class PowerMonitorInit
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing PowerMonitor");
throw;
}
}
@@ -129,17 +134,22 @@ public sealed class PowerMonitorInit
if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId))
{
_logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes");
return;
}
var meter = new Entity(_haContext, _options.MainMeterEntityId);
meter.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State) return;
_ = PollAndUpdateAsync();
});
meter.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State)
{
return;
}
_ = PollAndUpdateAsync();
});
if (_logger.IsEnabled(LogLevel.Information))
{
@@ -150,31 +160,33 @@ public sealed class PowerMonitorInit
private void SubscribeToRediscoverButton()
{
var button = new Entity(_haContext, "button.powermonitor_rediscover_sensors");
button.StateChanges()
.Subscribe(change =>
{
_logger.LogInformation("Re-discovery button pressed, scanning for power sensors");
_ = HandleRediscoveryAsync();
});
.Subscribe(change =>
{
_logger.LogInformation("Re-discovery button pressed, scanning for power sensors");
_ = HandleRediscoveryAsync();
});
}
private void SubscribeToLimitBreachDebugButton()
{
var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach");
button.StateChanges()
.Subscribe(_ =>
{
if (_enforcementService.IsLimitActive)
{
_logger.LogInformation("Limit breach debug button pressed while active, resetting breach");
_enforcementService.ResetLimitBreach();
}
else
{
_logger.LogInformation("Limit breach debug button pressed, triggering fake breach");
_enforcementService.TriggerLimitBreach();
}
});
.Subscribe(_ =>
{
if (_enforcementService.IsLimitActive)
{
_logger.LogInformation("Limit breach debug button pressed while active, resetting breach");
_enforcementService.ResetLimitBreach();
}
else
{
_logger.LogInformation("Limit breach debug button pressed, triggering fake breach");
_enforcementService.TriggerLimitBreach();
}
});
}
private async Task HandleRediscoveryAsync()
@@ -193,18 +205,22 @@ public sealed class PowerMonitorInit
if (added.Count > 0)
{
await _entityService.CreateDeviceEntitiesAsync(added);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
}
}
if (removed.Count > 0) await RemoreDevicePriceEntities(removed);
if (removed.Count > 0)
{
await RemoreDevicePriceEntities(removed);
}
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)",
newSensors.Count, added.Count, removed.Count);
newSensors.Count, added.Count, removed.Count);
}
}
catch (Exception ex)
@@ -229,11 +245,13 @@ public sealed class PowerMonitorInit
try
{
var totalPower = ReadMainMeterPower();
if (totalPower is null)
{
_mainMeterConsecutiveFailures++;
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures,
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
return;
}
@@ -251,8 +269,9 @@ public sealed class PowerMonitorInit
var now = _timeProvider.GetLocalNow();
var elapsedSeconds = _lastPollTimestamp.HasValue
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
: _options.PollIntervalSeconds;
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
: _options.PollIntervalSeconds;
_lastPollTimestamp = now;
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
@@ -261,18 +280,16 @@ public sealed class PowerMonitorInit
_anomalyStartTime = isAnomaly switch
{
true when _anomalyStartTime is null => now,
false => null,
_ => _anomalyStartTime
true when _anomalyStartTime is null => now, false => null, _ => _anomalyStartTime
};
var anomalyDuration = _anomalyStartTime.HasValue
? now - _anomalyStartTime.Value
: TimeSpan.Zero;
? now - _anomalyStartTime.Value
: TimeSpan.Zero;
var systemStatus = _mainMeterConsecutiveFailures >= PowerMonitorConsts.MainMeterMaxConsecutiveFailures
? "warning"
: "ok";
? "warning"
: "ok";
var context = new PowerUpdateContext
{
@@ -300,9 +317,9 @@ public sealed class PowerMonitorInit
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
effectivePrice);
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
effectivePrice);
}
}
catch (Exception ex)
@@ -318,10 +335,14 @@ public sealed class PowerMonitorInit
if (state?.State is null or "unavailable" or "unknown")
{
_logger.LogDebug("NordPool price entity unavailable, using last known price");
return 0;
}
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) return price;
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0)
{
return price;
}
if (_logger.IsEnabled(LogLevel.Debug))
{
@@ -340,11 +361,13 @@ public sealed class PowerMonitorInit
case (true, false):
_notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts);
_highPowerNotificationActive = true;
break;
case (false, true):
_notificationService.DismissHighPowerNotification();
_highPowerNotificationActive = false;
break;
}
}
@@ -352,11 +375,15 @@ public sealed class PowerMonitorInit
private double? ReadMainMeterPower()
{
var state = _haContext.GetState(_options.MainMeterEntityId);
if (state?.State is null or "unavailable" or "unknown") return null;
if (state?.State is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
? value
: null;
? value
: null;
}
private (IReadOnlyDictionary<string, double> readings, List<string> degraded) ReadDeviceSensors()
@@ -367,19 +394,21 @@ public sealed class PowerMonitorInit
foreach (var sensor in _discoveryService.CurrentDeviceSensors)
{
var state = _haContext.GetState(sensor.EntityId);
if (state?.State is null or "unavailable" or "unknown")
{
readings[sensor.EntityId] = 0;
degraded.Add(sensor.EntityId);
continue;
}
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
{
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit,
StringComparison.OrdinalIgnoreCase)
? value * PowerMonitorConsts.WattsPerKilowatt
: value;
StringComparison.OrdinalIgnoreCase)
? value * PowerMonitorConsts.WattsPerKilowatt
: value;
readings[sensor.EntityId] = powerWatts;
}
@@ -1,7 +1,11 @@
#region
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
using PowerMonitorManager.Interface;
#endregion
namespace PowerMonitorManager;
public static class PowerMonitorServiceRegistration
@@ -9,13 +13,13 @@ public static class PowerMonitorServiceRegistration
public static IServiceCollection AddPowerMonitor(this IServiceCollection services)
{
services
.AddNetDaemonApp<PowerMonitorInit>()
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
.AddTransient<IPowerNotificationService, PowerNotificationService>()
.AddTransient<IPowerLimitEnforcementService, PowerLimitEnforcementService>();
.AddNetDaemonApp<PowerMonitorInit>()
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
.AddTransient<IPowerNotificationService, PowerNotificationService>()
.AddTransient<IPowerLimitEnforcementService, PowerLimitEnforcementService>();
return services;
}
@@ -1,9 +1,13 @@
#region
using System.Globalization;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
public sealed class PowerNotificationService(
@@ -18,28 +22,28 @@ public sealed class PowerNotificationService(
var message = BuildHighPowerMessage(currentKw, thresholdKw);
haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationCreateService,
data: new
{
title = PowerMonitorConsts.HighPowerNotificationTitle,
message,
notification_id = PowerMonitorConsts.HighPowerNotificationId
});
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationCreateService,
data: new
{
title = PowerMonitorConsts.HighPowerNotificationTitle,
message,
notification_id = PowerMonitorConsts.HighPowerNotificationId
});
logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)",
currentKw, thresholdKw);
currentKw, thresholdKw);
}
public void DismissHighPowerNotification()
{
haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationDismissService,
data: new
{
notification_id = PowerMonitorConsts.HighPowerNotificationId
});
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationDismissService,
data: new
{
notification_id = PowerMonitorConsts.HighPowerNotificationId
});
logger.LogDebug("Dismissed high power usage notification");
}
@@ -47,9 +51,9 @@ public sealed class PowerNotificationService(
private static string BuildHighPowerMessage(double currentKw, double thresholdKw)
{
return string.Format(
CultureInfo.InvariantCulture,
"Total home power usage is **{0:F2} kW**, which exceeds the threshold of **{1:F1} kW**.\n\nConsider turning off high-power appliances to reduce consumption.",
currentKw,
thresholdKw);
CultureInfo.InvariantCulture,
"Total home power usage is **{0:F2} kW**, which exceeds the threshold of **{1:F1} kW**.\n\nConsider turning off high-power appliances to reduce consumption.",
currentKw,
thresholdKw);
}
}
@@ -1,3 +1,5 @@
#region
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
@@ -9,6 +11,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
@@ -38,25 +42,25 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
var allEntities = _haContext.GetAllEntities();
var powerSensors = allEntities
.Where(IsPowerSensor)
.Where(e => !IsMainMeter(e.EntityId))
.Where(e => !IsExcluded(e.EntityId))
.Select(e => new PowerSensorInfo
{
EntityId = e.EntityId,
FriendlyName = GetFriendlyName(e),
DeviceName = ExtractDeviceName(e.EntityId),
UnitOfMeasurement = GetUnitOfMeasurement(e)
})
.ToList();
.Where(IsPowerSensor)
.Where(e => !IsMainMeter(e.EntityId))
.Where(e => !IsExcluded(e.EntityId))
.Select(e => new PowerSensorInfo
{
EntityId = e.EntityId,
FriendlyName = GetFriendlyName(e),
DeviceName = ExtractDeviceName(e.EntityId),
UnitOfMeasurement = GetUnitOfMeasurement(e)
})
.ToList();
_currentDeviceSensors = powerSensors;
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation(
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
}
return powerSensors;
@@ -64,10 +68,17 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
internal static bool IsPowerSensor(Entity entity)
{
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) return false;
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase))
{
return false;
}
var attributes = entity.EntityState?.AttributesJson;
if (attributes is null) return false;
if (attributes is null)
{
return false;
}
var deviceClass = GetJsonStringProperty(attributes.Value, "device_class");
var unit = GetJsonStringProperty(attributes.Value, "unit_of_measurement");
@@ -90,38 +101,44 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
internal static string ExtractDeviceName(string entityId)
{
var withoutDomain = entityId.Contains('.')
? entityId[(entityId.IndexOf('.') + 1)..]
: entityId;
? entityId[(entityId.IndexOf('.') + 1)..]
: entityId;
return withoutDomain.EndsWith("_power", StringComparison.OrdinalIgnoreCase)
? withoutDomain[..^"_power".Length]
: withoutDomain;
? withoutDomain[..^"_power".Length]
: withoutDomain;
}
private static string GetFriendlyName(Entity entity)
{
var name = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name");
return name ?? entity.EntityId;
}
private static string GetUnitOfMeasurement(Entity entity)
{
var unit = GetJsonStringProperty(entity.EntityState?.AttributesJson, "unit_of_measurement");
return unit ?? PowerMonitorConsts.WattUnit;
}
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
{
if (element is null) return null;
if (element is null)
{
return null;
}
return element.Value.TryGetProperty(propertyName, out var value)
? value.GetString()
: null;
? value.GetString()
: null;
}
internal static Regex GlobToRegex(string globPattern)
{
var regexPattern = "^" + Regex.Escape(globPattern).Replace("\\*", ".*") + "$";
return new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}