127 lines
4.4 KiB
C#
127 lines
4.4 KiB
C#
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);
|
|
}
|
|
}
|
|
}
|