179 lines
5.5 KiB
C#
179 lines
5.5 KiB
C#
using System.Reactive.Linq;
|
|
using HomeAssistantGenerated;
|
|
using Microsoft.Extensions.Logging;
|
|
using NetDaemon.AppModel;
|
|
using NetDaemon.HassModel;
|
|
using PowerMonitor.Models;
|
|
using PowerMonitorManager.Interface;
|
|
using PowerMonitorManager.Models;
|
|
|
|
namespace PowerMonitorManager;
|
|
|
|
[NetDaemonApp]
|
|
public sealed class PowerMonitorInit : IPowerMonitorInit, IAsyncDisposable, IDisposable
|
|
{
|
|
private readonly ILogger<PowerMonitorInit> _logger;
|
|
private readonly IOtherPowerCalculationService _calculationService;
|
|
private readonly IPowerMonitorEntityService _entityService;
|
|
private readonly SemaphoreSlim _updateLock = new(1, 1);
|
|
private readonly List<IDisposable> _subscriptions = [];
|
|
private readonly Task _initializationTask;
|
|
|
|
private NumericSensorEntity TotalHomePowerEntity { get; }
|
|
private IReadOnlyList<NumericSensorEntity> MonitoredSensorEntities { get; }
|
|
|
|
public PowerMonitorInit(
|
|
IHaContext haContext,
|
|
ILogger<PowerMonitorInit> logger,
|
|
IOtherPowerCalculationService calculationService,
|
|
IPowerMonitorEntityService entityService)
|
|
{
|
|
_logger = logger;
|
|
_calculationService = calculationService;
|
|
_entityService = entityService;
|
|
|
|
TotalHomePowerEntity = new NumericSensorEntity(haContext, PowerSensorConfig.TotalHomePowerEntityId);
|
|
|
|
MonitoredSensorEntities = PowerSensorConfig.MonitoredSensorEntityIds
|
|
.Select(id => new NumericSensorEntity(haContext, id))
|
|
.ToList()
|
|
.AsReadOnly();
|
|
|
|
_initializationTask = InitializeAndSubscribeAsync();
|
|
}
|
|
|
|
private async Task InitializeAndSubscribeAsync()
|
|
{
|
|
try
|
|
{
|
|
await InitializeAsync().ConfigureAwait(false);
|
|
SubscribeToSensorChanges();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error during power monitor initialization");
|
|
}
|
|
}
|
|
|
|
private async Task InitializeAsync()
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(3)).ConfigureAwait(false);
|
|
|
|
await _entityService.CreateEntityAsync().ConfigureAwait(false);
|
|
await _entityService.ResetEntityAsync().ConfigureAwait(false);
|
|
|
|
await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
|
|
|
|
await RecalculateAndUpdateAsync().ConfigureAwait(false);
|
|
|
|
_logger.LogInformation(
|
|
"Power monitor initialized. Monitoring {Count} sensors against total home power",
|
|
MonitoredSensorEntities.Count);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error initializing power monitor");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private void SubscribeToSensorChanges()
|
|
{
|
|
var totalSubscription = TotalHomePowerEntity
|
|
.StateAllChanges()
|
|
.Subscribe(_ => HandleSensorStateChanged(PowerSensorConfig.TotalHomePowerEntityId));
|
|
_subscriptions.Add(totalSubscription);
|
|
|
|
foreach (var sensor in MonitoredSensorEntities)
|
|
{
|
|
var entityId = sensor.EntityId;
|
|
var subscription = sensor
|
|
.StateAllChanges()
|
|
.Subscribe(_ => HandleSensorStateChanged(entityId));
|
|
_subscriptions.Add(subscription);
|
|
}
|
|
|
|
_logger.LogInformation(
|
|
"Subscribed to state changes on {Count} sensors (1 total + {MonitoredCount} monitored)",
|
|
_subscriptions.Count, MonitoredSensorEntities.Count);
|
|
}
|
|
|
|
private async void HandleSensorStateChanged(string sensorEntityId)
|
|
{
|
|
try
|
|
{
|
|
_logger.LogDebug("Sensor state changed: {EntityId}", sensorEntityId);
|
|
await RecalculateAndUpdateAsync().ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error handling sensor state change for {EntityId}", sensorEntityId);
|
|
}
|
|
}
|
|
|
|
private async Task RecalculateAndUpdateAsync()
|
|
{
|
|
if (!await _updateLock.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false))
|
|
{
|
|
_logger.LogDebug("Skipping power recalculation, another update is in progress");
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
var totalPower = TotalHomePowerEntity.State;
|
|
var monitoredValues = MonitoredSensorEntities
|
|
.Select(s => s.State)
|
|
.ToList();
|
|
|
|
var result = _calculationService.CalculateOtherPower(totalPower, monitoredValues);
|
|
|
|
var context = new PowerUpdateContext
|
|
{
|
|
TotalHomePower = totalPower ?? 0.0,
|
|
TotalMonitoredPower = result.SumOfMonitored,
|
|
OtherPower = result.OtherPower,
|
|
MonitoredSensorCount = MonitoredSensorEntities.Count
|
|
};
|
|
|
|
await _entityService.UpdateEntityAsync(context).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
_updateLock.Release();
|
|
}
|
|
}
|
|
|
|
public async Task CleanupEntityAsync()
|
|
{
|
|
await _entityService.CleanupEntityAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
try
|
|
{
|
|
await _initializationTask.ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogDebug(ex, "Initialization task completed with an error during dispose");
|
|
}
|
|
|
|
Dispose();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
foreach (var subscription in _subscriptions)
|
|
{
|
|
subscription.Dispose();
|
|
}
|
|
|
|
_subscriptions.Clear();
|
|
_updateLock.Dispose();
|
|
}
|
|
}
|