feat: add PowerMonitorInit orchestrator with polling and re-discovery button
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerMonitorInit
|
||||
{
|
||||
Task InitializeAsync();
|
||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
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 NordPoolManager.Interface;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
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 INordPoolPriceService _priceService;
|
||||
|
||||
private int _mainMeterConsecutiveFailures;
|
||||
private DateTime? _anomalyStartTime;
|
||||
|
||||
public PowerMonitorInit(
|
||||
IHaContext haContext,
|
||||
ILogger<PowerMonitorInit> logger,
|
||||
IScheduler scheduler,
|
||||
IOptions<PowerMonitorOptions> options,
|
||||
IPowerSensorDiscoveryService discoveryService,
|
||||
IOtherPowerCalculationService calculationService,
|
||||
IPowerCostCalculationService costService,
|
||||
IPowerMonitorEntityService entityService,
|
||||
INordPoolPriceService priceService)
|
||||
{
|
||||
_haContext = haContext;
|
||||
_logger = logger;
|
||||
_scheduler = scheduler;
|
||||
_options = options.Value;
|
||||
_discoveryService = discoveryService;
|
||||
_calculationService = calculationService;
|
||||
_costService = costService;
|
||||
_entityService = entityService;
|
||||
_priceService = priceService;
|
||||
|
||||
_ = InitializeAndScheduleAsync();
|
||||
}
|
||||
|
||||
private async Task InitializeAndScheduleAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await InitializeAsync();
|
||||
SchedulePeriodicPolling();
|
||||
SubscribeToRediscoverButton();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during PowerMonitor initialization");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
await _entityService.CreateSystemEntitiesAsync();
|
||||
await _entityService.ResetEntitiesAsync();
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
|
||||
var sensors = _discoveryService.DiscoverDeviceSensors();
|
||||
await _entityService.CreateDeviceEntitiesAsync(sensors);
|
||||
|
||||
_logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count);
|
||||
|
||||
await PollAndUpdateAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing PowerMonitor");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _entityService.CleanupEntitiesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private void SchedulePeriodicPolling()
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
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);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Scheduling PowerMonitor polling every {Interval}s, first at {Time}",
|
||||
intervalSeconds, nextPollTime);
|
||||
|
||||
_scheduler.RunEvery(TimeSpan.FromSeconds(intervalSeconds), nextPollTime, async void () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await PollAndUpdateAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during PowerMonitor poll cycle");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
private async Task HandleRediscoveryAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var previousSensors = _discoveryService.CurrentDeviceSensors;
|
||||
var newSensors = _discoveryService.DiscoverDeviceSensors();
|
||||
|
||||
var previousIds = previousSensors.Select(s => s.DeviceName).ToHashSet();
|
||||
var currentIds = newSensors.Select(s => s.DeviceName).ToHashSet();
|
||||
|
||||
var added = newSensors.Where(s => !previousIds.Contains(s.DeviceName)).ToList();
|
||||
var removed = previousSensors.Where(s => !currentIds.Contains(s.DeviceName)).ToList();
|
||||
|
||||
if (added.Count > 0)
|
||||
{
|
||||
await _entityService.CreateDeviceEntitiesAsync(added);
|
||||
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
|
||||
}
|
||||
|
||||
if (removed.Count > 0)
|
||||
{
|
||||
var removedNames = removed.Select(s => s.DeviceName).ToList();
|
||||
await _entityService.CleanupDeviceEntitiesAsync(removedNames);
|
||||
_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);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during sensor re-discovery");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollAndUpdateAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var totalPower = ReadMainMeterPower();
|
||||
if (totalPower is null)
|
||||
{
|
||||
_mainMeterConsecutiveFailures++;
|
||||
_logger.LogWarning(
|
||||
"Main meter unavailable ({Failures}/{Max})",
|
||||
_mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
|
||||
return;
|
||||
}
|
||||
|
||||
_mainMeterConsecutiveFailures = 0;
|
||||
|
||||
var (deviceReadings, degradedSensors) = ReadDeviceSensors();
|
||||
|
||||
var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings);
|
||||
|
||||
var nordPoolPrice = _priceService.CurrentPrice;
|
||||
var priceSource = nordPoolPrice > 0 ? "live" : _costService.PriceSource;
|
||||
var effectivePrice = nordPoolPrice > 0 ? nordPoolPrice : _costService.LastKnownPrice;
|
||||
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, _options.PollIntervalSeconds, DateTime.Now);
|
||||
|
||||
var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts;
|
||||
if (isAnomaly && _anomalyStartTime is null)
|
||||
{
|
||||
_anomalyStartTime = DateTime.Now;
|
||||
}
|
||||
else if (!isAnomaly)
|
||||
{
|
||||
_anomalyStartTime = null;
|
||||
}
|
||||
|
||||
var anomalyDuration = _anomalyStartTime.HasValue
|
||||
? DateTime.Now - _anomalyStartTime.Value
|
||||
: TimeSpan.Zero;
|
||||
|
||||
var systemStatus = _mainMeterConsecutiveFailures >= PowerMonitorConsts.MainMeterMaxConsecutiveFailures
|
||||
? "warning"
|
||||
: "ok";
|
||||
|
||||
var context = new PowerUpdateContext
|
||||
{
|
||||
Calculation = calculation,
|
||||
CurrentNordPoolPrice = effectivePrice,
|
||||
PriceUnit = "EUR/kWh",
|
||||
PriceSource = priceSource,
|
||||
DeviceCosts = _costService.GetAllDeviceCostSnapshots(),
|
||||
TotalCost = _costService.GetTotalCostSnapshot(),
|
||||
OtherCost = _costService.GetOtherCostSnapshot(),
|
||||
IsAnomaly = isAnomaly,
|
||||
AnomalyDuration = anomalyDuration,
|
||||
AnomalyThresholdWatts = _options.AnomalyThresholdWatts,
|
||||
TrackedSensorCount = _discoveryService.CurrentDeviceSensors.Count,
|
||||
DegradedSensors = degradedSensors,
|
||||
SystemStatus = systemStatus
|
||||
};
|
||||
|
||||
await _entityService.UpdateEntitiesAsync(context);
|
||||
|
||||
_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)
|
||||
{
|
||||
_logger.LogError(ex, "Error during PowerMonitor poll and update");
|
||||
}
|
||||
}
|
||||
|
||||
private double? ReadMainMeterPower()
|
||||
{
|
||||
var state = _haContext.GetState(_options.MainMeterEntityId);
|
||||
if (state?.State is null || state.State == "unavailable" || state.State == "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(state.State, System.Globalization.CultureInfo.InvariantCulture, out var value)
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
private (IReadOnlyDictionary<string, double> readings, List<string> degraded) ReadDeviceSensors()
|
||||
{
|
||||
var readings = new Dictionary<string, double>();
|
||||
var degraded = new List<string>();
|
||||
|
||||
foreach (var sensor in _discoveryService.CurrentDeviceSensors)
|
||||
{
|
||||
var state = _haContext.GetState(sensor.EntityId);
|
||||
if (state?.State is null || state.State == "unavailable" || state.State == "unknown")
|
||||
{
|
||||
readings[sensor.EntityId] = 0;
|
||||
degraded.Add(sensor.EntityId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (double.TryParse(state.State, System.Globalization.CultureInfo.InvariantCulture, out var value))
|
||||
{
|
||||
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase)
|
||||
? value * PowerMonitorConsts.WattsPerKilowatt
|
||||
: value;
|
||||
readings[sensor.EntityId] = powerWatts;
|
||||
}
|
||||
else
|
||||
{
|
||||
readings[sensor.EntityId] = 0;
|
||||
degraded.Add(sensor.EntityId);
|
||||
}
|
||||
}
|
||||
|
||||
return (readings, degraded);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user