Apply code formatting cleanup across monitor projects
- Reindent appsettings.json and the MSBuild project files - Collapse single-statement guard blocks and tidy using and member order - Normalize XML doc indentation and file endings - Reorder BatteryMonitor test-data helpers and move the exclusion tests into their own region - Carry the same formatting through the boiler config, control, entity and test files
This commit is contained in:
@@ -5,4 +5,4 @@ namespace PowerMonitorManager.Interface;
|
||||
public interface IOtherPowerCalculationService
|
||||
{
|
||||
PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary<string, double> deviceReadings);
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,10 @@ namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerCostCalculationService
|
||||
{
|
||||
double LastKnownPrice { get; }
|
||||
string PriceSource { get; }
|
||||
void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now);
|
||||
CostSnapshot GetTotalCostSnapshot();
|
||||
CostSnapshot GetOtherCostSnapshot();
|
||||
IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots();
|
||||
double LastKnownPrice { get; }
|
||||
string PriceSource { get; }
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,10 @@ namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerLimitEnforcementService
|
||||
{
|
||||
bool IsLimitActive { get; }
|
||||
void EnforceLimit(double currentPowerWatts);
|
||||
|
||||
void TriggerLimitBreach();
|
||||
|
||||
void ResetLimitBreach();
|
||||
|
||||
bool IsLimitActive { get; }
|
||||
}
|
||||
@@ -6,9 +6,14 @@ namespace PowerMonitorManager.Interface;
|
||||
public interface IPowerMonitorEntityService
|
||||
{
|
||||
Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors, CancellationToken cancellationToken = default);
|
||||
|
||||
Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors,
|
||||
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);
|
||||
}
|
||||
|
||||
Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -5,4 +5,4 @@ public interface IPowerNotificationService
|
||||
void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts);
|
||||
|
||||
void DismissHighPowerNotification();
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,6 @@ namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerSensorDiscoveryService
|
||||
{
|
||||
IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors();
|
||||
IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors { get; }
|
||||
}
|
||||
IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors();
|
||||
}
|
||||
@@ -34,4 +34,4 @@ public static class PowerMonitorConsts
|
||||
public const string SwitchDomain = "switch";
|
||||
public const string TurnOnService = "turn_on";
|
||||
public const string TurnOffService = "turn_off";
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,6 @@ public sealed class CostAccumulator(DateTime now)
|
||||
private double _costDaily;
|
||||
private double _costMonthly;
|
||||
|
||||
private double _previous15Min;
|
||||
private double _previous1Hour;
|
||||
private double _previousDaily;
|
||||
private double _previousMonthly;
|
||||
|
||||
private DateTime _last15MinReset = now;
|
||||
private DateTime _last1HourReset = now;
|
||||
private DateTime _lastDailyReset = now;
|
||||
@@ -21,6 +16,11 @@ public sealed class CostAccumulator(DateTime now)
|
||||
|
||||
private bool _partialWindow = true;
|
||||
|
||||
private double _previous15Min;
|
||||
private double _previous1Hour;
|
||||
private double _previousDaily;
|
||||
private double _previousMonthly;
|
||||
|
||||
public void AddCost(double costIncrement, DateTime now)
|
||||
{
|
||||
lock (_lock)
|
||||
@@ -77,10 +77,7 @@ public sealed class CostAccumulator(DateTime now)
|
||||
_lastDailyReset = now;
|
||||
}
|
||||
|
||||
if (!IsNewMonthWindow(now, _lastMonthlyReset))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!IsNewMonthWindow(now, _lastMonthlyReset)) return;
|
||||
|
||||
_previousMonthly = _costMonthly;
|
||||
_costMonthly = 0;
|
||||
@@ -108,4 +105,4 @@ public sealed class CostAccumulator(DateTime now)
|
||||
{
|
||||
return now.Year != lastReset.Year || now.Month != lastReset.Month;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,4 +11,4 @@ public sealed class CostSnapshot
|
||||
public double PreviousDaily { get; init; }
|
||||
public double PreviousMonthly { get; init; }
|
||||
public bool PartialWindow { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,4 @@ public sealed class PowerCalculationResult
|
||||
public double SmoothedOtherPowerWatts { get; init; }
|
||||
public string DataQuality { get; init; } = "ok";
|
||||
public IReadOnlyDictionary<string, double> DevicePowerReadings { get; init; } = new Dictionary<string, double>();
|
||||
}
|
||||
}
|
||||
@@ -20,4 +20,4 @@ public sealed class PowerMonitorOptions
|
||||
public int LimitCooldownSeconds { get; set; } = PowerMonitorConsts.DefaultLimitCooldownSeconds;
|
||||
public string[] EnforceSwitchOffEntityIds { get; set; } = [];
|
||||
public string[] PauseAndRestoreEntityIds { get; set; } = [];
|
||||
}
|
||||
}
|
||||
@@ -15,4 +15,4 @@ public sealed class PowerUpdateContext
|
||||
public required int TrackedSensorCount { get; init; }
|
||||
public required IReadOnlyList<string> DegradedSensors { get; init; }
|
||||
public required string SystemStatus { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ namespace PowerMonitorManager;
|
||||
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
||||
{
|
||||
private readonly double _alpha;
|
||||
private double? _previousSmoothed;
|
||||
private readonly Lock _lock = new();
|
||||
private double? _previousSmoothed;
|
||||
|
||||
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
|
||||
{
|
||||
@@ -55,4 +55,4 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
||||
_previousSmoothed = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,35 +7,39 @@ namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
|
||||
private CostAccumulator? _totalAccumulator;
|
||||
private CostAccumulator? _otherAccumulator;
|
||||
private readonly Lock _accumulatorLock = new();
|
||||
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
|
||||
private readonly Lock _priceLock = new();
|
||||
|
||||
private double _lastKnownPrice;
|
||||
private CostAccumulator? _otherAccumulator;
|
||||
private string _priceSource = "live";
|
||||
private readonly Lock _priceLock = new();
|
||||
private CostAccumulator? _totalAccumulator;
|
||||
|
||||
public double LastKnownPrice
|
||||
{
|
||||
get { lock (_priceLock) { return _lastKnownPrice; } }
|
||||
get
|
||||
{
|
||||
lock (_priceLock)
|
||||
{
|
||||
return _lastKnownPrice;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string PriceSource
|
||||
{
|
||||
get { lock (_priceLock) { return _priceSource; } }
|
||||
}
|
||||
|
||||
public void SetPrice(double price)
|
||||
{
|
||||
lock (_priceLock)
|
||||
get
|
||||
{
|
||||
_lastKnownPrice = price;
|
||||
_priceSource = "stale";
|
||||
lock (_priceLock)
|
||||
{
|
||||
return _priceSource;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now)
|
||||
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds,
|
||||
DateTime now)
|
||||
{
|
||||
lock (_priceLock)
|
||||
{
|
||||
@@ -51,7 +55,8 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
var totalCost = CalculateCostIncrement(calculation.TotalPowerWatts, effectivePrice, pollIntervalSeconds);
|
||||
GetOrCreateTotalAccumulator(now).AddCost(totalCost, now);
|
||||
|
||||
var otherCost = CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
|
||||
var otherCost =
|
||||
CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
|
||||
GetOrCreateOtherAccumulator(now).AddCost(otherCost, now);
|
||||
|
||||
foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings)
|
||||
@@ -78,13 +83,6 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
}
|
||||
}
|
||||
|
||||
public CostSnapshot GetDeviceCostSnapshot(string entityId)
|
||||
{
|
||||
return _deviceAccumulators.TryGetValue(entityId, out var accumulator)
|
||||
? accumulator.GetSnapshot()
|
||||
: CreateEmptySnapshot();
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots()
|
||||
{
|
||||
return _deviceAccumulators.ToDictionary(
|
||||
@@ -92,6 +90,22 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
kvp => kvp.Value.GetSnapshot());
|
||||
}
|
||||
|
||||
public void SetPrice(double price)
|
||||
{
|
||||
lock (_priceLock)
|
||||
{
|
||||
_lastKnownPrice = price;
|
||||
_priceSource = "stale";
|
||||
}
|
||||
}
|
||||
|
||||
public CostSnapshot GetDeviceCostSnapshot(string entityId)
|
||||
{
|
||||
return _deviceAccumulators.TryGetValue(entityId, out var accumulator)
|
||||
? accumulator.GetSnapshot()
|
||||
: CreateEmptySnapshot();
|
||||
}
|
||||
|
||||
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
|
||||
{
|
||||
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
|
||||
@@ -118,4 +132,4 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
{
|
||||
return new CostSnapshot { PartialWindow = true };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,10 +25,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
public void EnforceLimit(double currentPowerWatts)
|
||||
{
|
||||
if (!_options.EnforceLimitEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (!_options.EnforceLimitEnabled) return;
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
|
||||
@@ -67,15 +64,9 @@ 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);
|
||||
|
||||
@@ -87,10 +78,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
private void ExecuteRecover()
|
||||
{
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
||||
{
|
||||
TurnOn(entityId);
|
||||
}
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
|
||||
|
||||
DismissLimitNotification();
|
||||
|
||||
@@ -100,22 +88,20 @@ 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);
|
||||
}
|
||||
logger.LogDebug(
|
||||
"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);
|
||||
logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts,
|
||||
_options.PowerLimitWatts);
|
||||
|
||||
ExecuteEnforce(currentPowerWatts);
|
||||
}
|
||||
@@ -124,28 +110,23 @@ 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);
|
||||
logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced",
|
||||
currentPowerWatts, _options.PowerLimitWatts);
|
||||
_enforcedAt = now;
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
logger.LogInformation(
|
||||
"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();
|
||||
|
||||
@@ -155,17 +136,20 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
private void TurnOff(string entityId)
|
||||
{
|
||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService, ServiceTarget.FromEntity(entityId));
|
||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService,
|
||||
ServiceTarget.FromEntity(entityId));
|
||||
}
|
||||
|
||||
private void TurnOn(string entityId)
|
||||
{
|
||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService, ServiceTarget.FromEntity(entityId));
|
||||
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService,
|
||||
ServiceTarget.FromEntity(entityId));
|
||||
}
|
||||
|
||||
private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts)
|
||||
{
|
||||
var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt, limitWatts / PowerMonitorConsts.WattsPerKilowatt);
|
||||
var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt,
|
||||
limitWatts / PowerMonitorConsts.WattsPerKilowatt);
|
||||
|
||||
haContext.CallService(
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
|
||||
@@ -8,20 +8,20 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>PowerMonitor.Manager.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>PowerMonitor.Manager.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
|
||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -49,9 +49,7 @@ public sealed class PowerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
@@ -64,7 +62,8 @@ public sealed class PowerMonitorEntityService(
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors, CancellationToken cancellationToken = default)
|
||||
public async Task CreateDeviceEntitiesAsync(IReadOnlyList<PowerSensorInfo> sensors,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -74,9 +73,7 @@ public sealed class PowerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
@@ -98,15 +95,23 @@ public sealed class PowerMonitorEntityService(
|
||||
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),
|
||||
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),
|
||||
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)
|
||||
};
|
||||
@@ -114,10 +119,14 @@ 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));
|
||||
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));
|
||||
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);
|
||||
@@ -154,9 +163,9 @@ public sealed class PowerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
var tasks = SystemEntityIds.Select(entityManager.RemoveEntity);
|
||||
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
|
||||
|
||||
logger.LogInformation("PowerMonitor system entities cleaned up");
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -166,22 +175,20 @@ public sealed class PowerMonitorEntityService(
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RemoveDeviceEntitiesAsync(IReadOnlyList<string> removedDeviceNames, CancellationToken cancellationToken = default)
|
||||
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);
|
||||
}
|
||||
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Entity removed: {EntityId}", id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -191,7 +198,7 @@ public sealed class PowerMonitorEntityService(
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList()
|
||||
{
|
||||
@@ -199,7 +206,12 @@ public sealed class PowerMonitorEntityService(
|
||||
{
|
||||
new("sensor", "powermonitor_total_power", "PowerMonitor total power")
|
||||
{
|
||||
AdditionalConfig = new { unit_of_measurement = PowerMonitorConsts.WattUnit, device_class = PowerMonitorConsts.PowerDeviceClass, state_class = PowerMonitorConsts.MeasurementStateClass }
|
||||
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)"),
|
||||
@@ -207,7 +219,12 @@ public sealed class PowerMonitorEntityService(
|
||||
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 }
|
||||
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)"),
|
||||
@@ -293,7 +310,8 @@ public sealed class PowerMonitorEntityService(
|
||||
}).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);
|
||||
@@ -360,4 +378,4 @@ public sealed class PowerMonitorEntityService(
|
||||
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,21 +15,21 @@ namespace PowerMonitorManager;
|
||||
[NetDaemonApp]
|
||||
public sealed class PowerMonitorInit
|
||||
{
|
||||
private readonly ILogger<PowerMonitorInit> _logger;
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly PowerMonitorOptions _options;
|
||||
private readonly IPowerSensorDiscoveryService _discoveryService;
|
||||
private readonly IOtherPowerCalculationService _calculationService;
|
||||
private readonly IPowerCostCalculationService _costService;
|
||||
private readonly IPowerMonitorEntityService _entityService;
|
||||
private readonly IPowerNotificationService _notificationService;
|
||||
private readonly IPowerSensorDiscoveryService _discoveryService;
|
||||
private readonly IPowerLimitEnforcementService _enforcementService;
|
||||
private readonly IPowerMonitorEntityService _entityService;
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly ILogger<PowerMonitorInit> _logger;
|
||||
private readonly IPowerNotificationService _notificationService;
|
||||
private readonly PowerMonitorOptions _options;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private DateTimeOffset? _anomalyStartTime;
|
||||
private bool _highPowerNotificationActive;
|
||||
private DateTimeOffset? _lastPollTimestamp;
|
||||
|
||||
private int _mainMeterConsecutiveFailures;
|
||||
private DateTimeOffset? _anomalyStartTime;
|
||||
private DateTimeOffset? _lastPollTimestamp;
|
||||
private bool _highPowerNotificationActive;
|
||||
|
||||
public PowerMonitorInit(
|
||||
IHaContext haContext,
|
||||
@@ -99,9 +99,7 @@ public sealed class PowerMonitorInit
|
||||
await _entityService.CreateDeviceEntitiesAsync(sensors);
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count);
|
||||
}
|
||||
|
||||
await PollAndUpdateAsync();
|
||||
}
|
||||
@@ -115,7 +113,7 @@ public sealed class PowerMonitorInit
|
||||
private IReadOnlyList<PowerSensorInfo> GetPowerSensorEntitiesNames()
|
||||
{
|
||||
var sensors = _discoveryService.DiscoverDeviceSensors();
|
||||
|
||||
|
||||
return sensors;
|
||||
}
|
||||
|
||||
@@ -136,18 +134,13 @@ public sealed class PowerMonitorInit
|
||||
meter.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (e.Old?.State == e.New?.State) return;
|
||||
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
|
||||
}
|
||||
}
|
||||
|
||||
private void SubscribeToRediscoverButton()
|
||||
@@ -197,20 +190,14 @@ public sealed class PowerMonitorInit
|
||||
{
|
||||
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);
|
||||
}
|
||||
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)",
|
||||
newSensors.Count, added.Count, removed.Count);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -222,11 +209,9 @@ public sealed class PowerMonitorInit
|
||||
{
|
||||
var removedNames = removed.Select(s => s.DeviceName).ToList();
|
||||
await _entityService.RemoveDeviceEntitiesAsync(removedNames);
|
||||
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollAndUpdateAsync()
|
||||
@@ -237,8 +222,9 @@ public sealed class PowerMonitorInit
|
||||
if (totalPower is null)
|
||||
{
|
||||
_mainMeterConsecutiveFailures++;
|
||||
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||
|
||||
_logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures,
|
||||
PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -302,10 +288,10 @@ public sealed class PowerMonitorInit
|
||||
_enforcementService.EnforceLimit(calculation.TotalPowerWatts);
|
||||
|
||||
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);
|
||||
}
|
||||
_logger.LogDebug(
|
||||
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
||||
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
|
||||
effectivePrice);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -316,23 +302,18 @@ public sealed class PowerMonitorInit
|
||||
private double ReadNordPoolPrice()
|
||||
{
|
||||
var state = _haContext.GetState(NordPoolConsts.CurrentPriceEntityId);
|
||||
|
||||
|
||||
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))
|
||||
{
|
||||
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -357,10 +338,7 @@ 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
|
||||
@@ -384,10 +362,11 @@ public sealed class PowerMonitorInit
|
||||
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
|
||||
{
|
||||
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase)
|
||||
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit,
|
||||
StringComparison.OrdinalIgnoreCase)
|
||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||
: value;
|
||||
|
||||
|
||||
readings[sensor.EntityId] = powerWatts;
|
||||
}
|
||||
else
|
||||
@@ -399,4 +378,4 @@ public sealed class PowerMonitorInit
|
||||
|
||||
return (readings, degraded);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,4 +19,4 @@ public static class PowerMonitorServiceRegistration
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,8 @@ public sealed class PowerNotificationService(
|
||||
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
||||
});
|
||||
|
||||
logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", currentKw, thresholdKw);
|
||||
logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)",
|
||||
currentKw, thresholdKw);
|
||||
}
|
||||
|
||||
public void DismissHighPowerNotification()
|
||||
@@ -51,4 +52,4 @@ public sealed class PowerNotificationService(
|
||||
currentKw,
|
||||
thresholdKw);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,15 +13,13 @@ namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
{
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly PowerMonitorOptions _options;
|
||||
private readonly ILogger<PowerSensorDiscoveryService> _logger;
|
||||
private readonly Regex[] _exclusionPatterns;
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly ILogger<PowerSensorDiscoveryService> _logger;
|
||||
private readonly PowerMonitorOptions _options;
|
||||
|
||||
private volatile IReadOnlyList<PowerSensorInfo> _currentDeviceSensors = [];
|
||||
|
||||
public IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors => _currentDeviceSensors;
|
||||
|
||||
public PowerSensorDiscoveryService(
|
||||
IHaContext haContext,
|
||||
IOptions<PowerMonitorOptions> options,
|
||||
@@ -33,6 +31,8 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
_exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)];
|
||||
}
|
||||
|
||||
public IReadOnlyList<PowerSensorInfo> CurrentDeviceSensors => _currentDeviceSensors;
|
||||
|
||||
public IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors()
|
||||
{
|
||||
var allEntities = _haContext.GetAllEntities();
|
||||
@@ -53,26 +53,19 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
_currentDeviceSensors = powerSensors;
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||
_logger.LogInformation(
|
||||
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
||||
}
|
||||
|
||||
return powerSensors;
|
||||
}
|
||||
|
||||
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");
|
||||
@@ -117,10 +110,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
|
||||
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()
|
||||
@@ -132,4 +122,4 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
var regexPattern = "^" + Regex.Escape(globPattern).Replace("\\*", ".*") + "$";
|
||||
return new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user