Enable PowerMonitor limit enforcement and prune unused boiler/replay code
PowerMonitor now ships enabled with power-limit enforcement settings: watt limit, recovery and cooldown windows, and switch-off plus pause/restore entity lists. Remove the unused BoilerRunTimeTracker, its DI registration and tests, the StatusCleanedUp constant, and the boiler replay runner; simplify BoilerConfigReader, control-service logging and entity parsing. Switch CostAccumulator to System.Threading.Lock, update the Shower exhaust fan service and tests, drop the legacy HistoryReplay/McpServer sources and reporting tooling, and expand AGENTS.md with the current project wiring and DI notes.
This commit is contained in:
@@ -20,12 +20,18 @@ public static class PowerMonitorConsts
|
||||
|
||||
public const double DefaultHighPowerThresholdWatts = 6000.0;
|
||||
|
||||
public const double DefaultPowerLimitWatts = 5500.0;
|
||||
public const int DefaultRecoverySeconds = 600;
|
||||
public const int DefaultLimitCooldownSeconds = 30;
|
||||
|
||||
public const string HighPowerNotificationId = "power_monitor_high_power";
|
||||
public const string HighPowerNotificationTitle = "High Power Usage Alert";
|
||||
public const string PowerLimitNotificationId = "power_monitor_power_limit";
|
||||
public const string PowerLimitNotificationTitle = "Power Limit Enforced";
|
||||
public const string PersistentNotificationDomain = "persistent_notification";
|
||||
public const string PersistentNotificationCreateService = "create";
|
||||
public const string PersistentNotificationDismissService = "dismiss";
|
||||
|
||||
public const int MinutesPerQuarterHour = 15;
|
||||
public const int MinutesPerHour = 60;
|
||||
public const string SwitchDomain = "switch";
|
||||
public const string TurnOnService = "turn_on";
|
||||
public const string TurnOffService = "turn_off";
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models;
|
||||
|
||||
public sealed class CostAccumulator
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
private double _cost15Min;
|
||||
private double _cost1Hour;
|
||||
|
||||
@@ -13,4 +13,11 @@ public sealed class PowerMonitorOptions
|
||||
public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts;
|
||||
public string[] ExcludedSensorPatterns { get; set; } = [];
|
||||
public double HighPowerThresholdWatts { get; set; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts;
|
||||
|
||||
public bool EnforceLimitEnabled { get; set; } = true;
|
||||
public double PowerLimitWatts { get; set; } = PowerMonitorConsts.DefaultPowerLimitWatts;
|
||||
public int RecoverySeconds { get; set; } = PowerMonitorConsts.DefaultRecoverySeconds;
|
||||
public int LimitCooldownSeconds { get; set; } = PowerMonitorConsts.DefaultLimitCooldownSeconds;
|
||||
public string[] EnforceSwitchOffEntityIds { get; set; } = [];
|
||||
public string[] PauseAndRestoreEntityIds { get; set; } = [];
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
||||
{
|
||||
private readonly double _alpha;
|
||||
private double? _previousSmoothed;
|
||||
private readonly object _lock = new();
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
|
||||
{
|
||||
|
||||
@@ -10,11 +10,11 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
|
||||
private CostAccumulator? _totalAccumulator;
|
||||
private CostAccumulator? _otherAccumulator;
|
||||
private readonly object _accumulatorLock = new();
|
||||
private readonly Lock _accumulatorLock = new();
|
||||
|
||||
private double _lastKnownPrice;
|
||||
private string _priceSource = "live";
|
||||
private readonly object _priceLock = new();
|
||||
private readonly Lock _priceLock = new();
|
||||
|
||||
public double LastKnownPrice
|
||||
{
|
||||
|
||||
@@ -25,6 +25,7 @@ public sealed class PowerMonitorEntityService(
|
||||
private const string AnomalyEntityId = "binary_sensor.powermonitor_anomaly";
|
||||
private const string StatusEntityId = "sensor.powermonitor_status";
|
||||
private const string RediscoverButtonEntityId = "button.powermonitor_rediscover_sensors";
|
||||
private const string TriggerLimitBreachButtonEntityId = "button.powermonitor_trigger_limit_breach";
|
||||
|
||||
private static readonly string[] SystemEntityIds =
|
||||
[
|
||||
@@ -34,7 +35,8 @@ public sealed class PowerMonitorEntityService(
|
||||
OtherCost15MinEntityId, OtherCost1HEntityId, OtherCostDailyEntityId, OtherCostMonthlyEntityId,
|
||||
AnomalyEntityId,
|
||||
StatusEntityId,
|
||||
RediscoverButtonEntityId
|
||||
RediscoverButtonEntityId,
|
||||
TriggerLimitBreachButtonEntityId
|
||||
];
|
||||
|
||||
public async Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
@@ -199,6 +201,10 @@ public sealed class PowerMonitorEntityService(
|
||||
new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
|
||||
{
|
||||
AdditionalConfig = new { icon = "mdi:refresh" }
|
||||
},
|
||||
new("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
|
||||
{
|
||||
AdditionalConfig = new { icon = "mdi:flash-alert" }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Reactive.Concurrency;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NetDaemon.AppModel;
|
||||
using NetDaemon.Extensions.Scheduler;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using NordPool.Models;
|
||||
@@ -18,40 +16,41 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
{
|
||||
private readonly ILogger<PowerMonitorInit> _logger;
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly IScheduler _scheduler;
|
||||
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 IPowerLimitEnforcementService _enforcementService;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
|
||||
private int _mainMeterConsecutiveFailures;
|
||||
private DateTimeOffset? _anomalyStartTime;
|
||||
private DateTimeOffset? _lastPollTimestamp;
|
||||
private bool _highPowerNotificationActive;
|
||||
|
||||
public PowerMonitorInit(
|
||||
IHaContext haContext,
|
||||
ILogger<PowerMonitorInit> logger,
|
||||
IScheduler scheduler,
|
||||
IOptions<PowerMonitorOptions> options,
|
||||
IPowerSensorDiscoveryService discoveryService,
|
||||
IOtherPowerCalculationService calculationService,
|
||||
IPowerCostCalculationService costService,
|
||||
IPowerMonitorEntityService entityService,
|
||||
IPowerNotificationService notificationService,
|
||||
IPowerLimitEnforcementService enforcementService,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
_haContext = haContext;
|
||||
_logger = logger;
|
||||
_scheduler = scheduler;
|
||||
_options = options.Value;
|
||||
_discoveryService = discoveryService;
|
||||
_calculationService = calculationService;
|
||||
_costService = costService;
|
||||
_entityService = entityService;
|
||||
_notificationService = notificationService;
|
||||
_enforcementService = enforcementService;
|
||||
_timeProvider = timeProvider;
|
||||
|
||||
_ = InitializeAndScheduleAsync();
|
||||
@@ -62,8 +61,9 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
try
|
||||
{
|
||||
await InitializeAsync();
|
||||
SchedulePeriodicPolling();
|
||||
SubscribeToMainMeterChanges();
|
||||
SubscribeToRediscoverButton();
|
||||
SubscribeToLimitBreachDebugButton();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -101,20 +101,27 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
await _entityService.CleanupEntitiesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private void SchedulePeriodicPolling()
|
||||
private void SubscribeToMainMeterChanges()
|
||||
{
|
||||
var now = _timeProvider.GetLocalNow();
|
||||
var intervalSeconds = _options.PollIntervalSeconds;
|
||||
var currentSecondInInterval = (now.Minute * 60 + now.Second) % intervalSeconds;
|
||||
var secondsUntilNext = intervalSeconds - currentSecondInInterval;
|
||||
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
|
||||
var nextPollTime = now.Add(delayUntilNext);
|
||||
if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId))
|
||||
{
|
||||
_logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"Scheduling PowerMonitor polling every {Interval}s, first at {Time}",
|
||||
intervalSeconds, nextPollTime);
|
||||
var meter = new Entity(_haContext, _options.MainMeterEntityId);
|
||||
meter.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_scheduler.RunEvery(TimeSpan.FromSeconds(intervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync());
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
|
||||
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
|
||||
}
|
||||
|
||||
private void SubscribeToRediscoverButton()
|
||||
@@ -128,6 +135,25 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleRediscoveryAsync()
|
||||
{
|
||||
try
|
||||
@@ -154,9 +180,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
|
||||
}
|
||||
|
||||
_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)
|
||||
{
|
||||
@@ -172,9 +196,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -190,9 +213,15 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
|
||||
var now = _timeProvider.GetLocalNow();
|
||||
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, _options.PollIntervalSeconds, now.LocalDateTime);
|
||||
var elapsedSeconds = _lastPollTimestamp.HasValue
|
||||
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
|
||||
: _options.PollIntervalSeconds;
|
||||
_lastPollTimestamp = now;
|
||||
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
|
||||
|
||||
var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts;
|
||||
|
||||
if (isAnomaly && _anomalyStartTime is null)
|
||||
{
|
||||
_anomalyStartTime = now;
|
||||
@@ -231,12 +260,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
|
||||
EvaluateHighPowerNotification(calculation.TotalPowerWatts);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
|
||||
calculation.TotalPowerWatts,
|
||||
calculation.SmoothedOtherPowerWatts,
|
||||
deviceReadings.Count,
|
||||
effectivePrice);
|
||||
_enforcementService.EnforceLimit(calculation.TotalPowerWatts);
|
||||
|
||||
_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)
|
||||
{
|
||||
@@ -247,7 +274,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
private double ReadNordPoolPrice()
|
||||
{
|
||||
var state = _haContext.GetState(NordPoolConsts.CurrentPriceEntityId);
|
||||
if (state?.State is null || state.State == "unavailable" || state.State == "unknown")
|
||||
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
_logger.LogDebug("NordPool price entity unavailable, using last known price");
|
||||
return 0;
|
||||
@@ -259,6 +287,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
}
|
||||
|
||||
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -281,12 +310,12 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
private double? ReadMainMeterPower()
|
||||
{
|
||||
var state = _haContext.GetState(_options.MainMeterEntityId);
|
||||
if (state?.State is null || state.State == "unavailable" || state.State == "unknown")
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(state.State, System.Globalization.CultureInfo.InvariantCulture, out var value)
|
||||
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
@@ -299,18 +328,19 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
foreach (var sensor in _discoveryService.CurrentDeviceSensors)
|
||||
{
|
||||
var state = _haContext.GetState(sensor.EntityId);
|
||||
if (state?.State is null || state.State == "unavailable" || state.State == "unknown")
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
readings[sensor.EntityId] = 0;
|
||||
degraded.Add(sensor.EntityId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (double.TryParse(state.State, System.Globalization.CultureInfo.InvariantCulture, out var value))
|
||||
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
|
||||
{
|
||||
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase)
|
||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||
: value;
|
||||
|
||||
readings[sensor.EntityId] = powerWatts;
|
||||
}
|
||||
else
|
||||
|
||||
@@ -25,7 +25,8 @@ public static class PowerMonitorServiceRegistration
|
||||
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
|
||||
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
|
||||
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
|
||||
.AddTransient<IPowerNotificationService, PowerNotificationService>();
|
||||
.AddTransient<IPowerNotificationService, PowerNotificationService>()
|
||||
.AddTransient<IPowerLimitEnforcementService, PowerLimitEnforcementService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -6,26 +6,18 @@ using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerNotificationService : IPowerNotificationService
|
||||
public sealed class PowerNotificationService(
|
||||
IHaContext haContext,
|
||||
ILogger<PowerNotificationService> logger)
|
||||
: IPowerNotificationService
|
||||
{
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly ILogger<PowerNotificationService> _logger;
|
||||
|
||||
public PowerNotificationService(
|
||||
IHaContext haContext,
|
||||
ILogger<PowerNotificationService> logger)
|
||||
{
|
||||
_haContext = haContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts)
|
||||
{
|
||||
var currentKw = currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt;
|
||||
var thresholdKw = thresholdWatts / PowerMonitorConsts.WattsPerKilowatt;
|
||||
var message = BuildHighPowerMessage(currentKw, thresholdKw);
|
||||
|
||||
_haContext.CallService(
|
||||
haContext.CallService(
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationCreateService,
|
||||
data: new
|
||||
@@ -35,14 +27,12 @@ public sealed class PowerNotificationService : IPowerNotificationService
|
||||
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()
|
||||
{
|
||||
_haContext.CallService(
|
||||
haContext.CallService(
|
||||
PowerMonitorConsts.PersistentNotificationDomain,
|
||||
PowerMonitorConsts.PersistentNotificationDismissService,
|
||||
data: new
|
||||
@@ -50,10 +40,10 @@ public sealed class PowerNotificationService : IPowerNotificationService
|
||||
notification_id = PowerMonitorConsts.HighPowerNotificationId
|
||||
});
|
||||
|
||||
_logger.LogDebug("Dismissed high power usage notification");
|
||||
logger.LogDebug("Dismissed high power usage notification");
|
||||
}
|
||||
|
||||
internal static string BuildHighPowerMessage(double currentKw, double thresholdKw)
|
||||
private static string BuildHighPowerMessage(double currentKw, double thresholdKw)
|
||||
{
|
||||
return string.Format(
|
||||
CultureInfo.InvariantCulture,
|
||||
|
||||
@@ -54,8 +54,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
|
||||
_currentDeviceSensors = powerSensors;
|
||||
|
||||
_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;
|
||||
@@ -82,12 +81,12 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
string.Equals(unit, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
internal bool IsMainMeter(string entityId)
|
||||
private bool IsMainMeter(string entityId)
|
||||
{
|
||||
return string.Equals(entityId, _options.MainMeterEntityId, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
internal bool IsExcluded(string entityId)
|
||||
private bool IsExcluded(string entityId)
|
||||
{
|
||||
return _exclusionPatterns.Any(pattern => pattern.IsMatch(entityId));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user