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:
2026-11-29 13:58:08 +02:00
parent f176a1b8fc
commit f0bbd4f10b
98 changed files with 306 additions and 4737 deletions
+65 -35
View File
@@ -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