This commit is contained in:
Marius
2026-03-08 19:10:16 +02:00
commit 861c344832
74 changed files with 34756 additions and 0 deletions
@@ -0,0 +1,8 @@
using PowerMonitorManager.Models;
namespace PowerMonitorManager.Interface;
public interface IOtherPowerCalculationService
{
PowerCalculationResult CalculateOtherPower(double? totalHomePower, IReadOnlyList<double?> monitoredSensorValues);
}
@@ -0,0 +1,11 @@
using PowerMonitorManager.Models;
namespace PowerMonitorManager.Interface;
public interface IPowerMonitorEntityService
{
Task CreateEntityAsync();
Task ResetEntityAsync();
Task UpdateEntityAsync(PowerUpdateContext context);
Task CleanupEntityAsync();
}
@@ -0,0 +1,6 @@
namespace PowerMonitorManager.Interface;
public interface IPowerMonitorInit
{
Task CleanupEntityAsync();
}
@@ -0,0 +1,5 @@
namespace PowerMonitorManager.Models;
public sealed record PowerCalculationResult(
double OtherPower,
double SumOfMonitored);
@@ -0,0 +1,9 @@
namespace PowerMonitorManager.Models;
public sealed record PowerUpdateContext
{
public required double TotalHomePower { get; init; }
public required double TotalMonitoredPower { get; init; }
public required double OtherPower { get; init; }
public required int MonitoredSensorCount { get; init; }
}
@@ -0,0 +1,16 @@
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
namespace PowerMonitorManager;
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
{
public PowerCalculationResult CalculateOtherPower(double? totalHomePower, IReadOnlyList<double?> monitoredSensorValues)
{
var total = totalHomePower ?? 0.0;
var sumOfMonitored = monitoredSensorValues.Sum(v => v ?? 0.0);
var otherPower = Math.Max(0.0, total - sumOfMonitored);
return new PowerCalculationResult(otherPower, sumOfMonitored);
}
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>PowerMonitorManager</RootNamespace>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>PowerMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,126 @@
using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using PowerMonitor.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
namespace PowerMonitorManager;
public sealed class PowerMonitorEntityService(
IEntityManager entityManager,
ILogger<PowerMonitorEntityService> logger) : IPowerMonitorEntityService
{
private const string OtherPowerEntityId = PowerSensorConfig.OtherPowerUsageEntityId;
private const string UnitOfMeasurement = "W";
private const string DeviceClass = "power";
private const string StateClass = "measurement";
private const string FriendlyName = "Other Power Usage";
public async Task CreateEntityAsync()
{
try
{
var entity = new PowerMonitorEntity("sensor", "other_power_usage", FriendlyName)
{
AdditionalConfig = new
{
unit_of_measurement = UnitOfMeasurement,
device_class = DeviceClass,
state_class = StateClass
}
};
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", OtherPowerEntityId);
}
}
public async Task ResetEntityAsync()
{
logger.LogInformation("Resetting Other Power entity state to defaults");
await SetEntityStateSafe(OtherPowerEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(OtherPowerEntityId, BuildAttributes(0.0, 0.0, 0.0, 0, null)).ConfigureAwait(false);
}
public async Task UpdateEntityAsync(PowerUpdateContext context)
{
var timestamp = DateTime.UtcNow.ToString("O");
var stateValue = context.OtherPower.ToString("F2", CultureInfo.InvariantCulture);
logger.LogDebug(
"Updating other_power_usage: {OtherPower}W (total: {Total}W, monitored: {Monitored}W, sensors: {Count})",
stateValue, context.TotalHomePower, context.TotalMonitoredPower, context.MonitoredSensorCount);
await SetEntityStateSafe(OtherPowerEntityId, stateValue).ConfigureAwait(false);
await SetEntityAttributesSafe(OtherPowerEntityId, BuildAttributes(
context.TotalHomePower,
context.TotalMonitoredPower,
context.OtherPower,
context.MonitoredSensorCount,
timestamp)).ConfigureAwait(false);
}
public async Task CleanupEntityAsync()
{
try
{
await entityManager.RemoveEntity(OtherPowerEntityId).ConfigureAwait(false);
logger.LogInformation("Other Power entity cleaned up successfully");
}
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up Other Power entity");
throw;
}
}
private static object BuildAttributes(
double totalHomePower,
double totalMonitoredPower,
double otherPower,
int monitoredSensorCount,
string? lastUpdated) => new
{
unit_of_measurement = UnitOfMeasurement,
device_class = DeviceClass,
state_class = StateClass,
friendly_name = FriendlyName,
total_home_power = totalHomePower,
total_monitored_power = totalMonitoredPower,
other_power = otherPower,
monitored_sensor_count = monitoredSensorCount,
last_updated = lastUpdated
};
internal async Task SetEntityStateSafe(string entityId, string state)
{
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
}
}
internal async Task SetEntityAttributesSafe(string entityId, object attributes)
{
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
}
}
}
+178
View File
@@ -0,0 +1,178 @@
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();
}
}