Files
HomeAssistant/HomeAssistant.Server/MqttRecreateApp.cs
T

217 lines
7.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using BoilerMonitorManager.Interface;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NetDaemon.AppModel;
using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using NordPoolManager.Interface;
using PowerMonitorManager.Interface;
using ShowerMonitorManager.Interface;
namespace HomeAssistantServer;
[NetDaemonApp]
public sealed class MqttRecreateApp
{
private const string RecreateButtonEntityId = "button.appdaemon_recreate_all";
private const string NordPoolPriceEntityId = "sensor.nordpool_price";
private const string DefaultUnitOfMeasurement = "EUR/kWh";
private readonly IHaContext _haContext;
private readonly IMqttEntityManager _mqttEntityManager;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<MqttRecreateApp> _logger;
public MqttRecreateApp(
IHaContext haContext,
IMqttEntityManager mqttEntityManager,
IServiceProvider serviceProvider,
ILogger<MqttRecreateApp> logger)
{
_haContext = haContext;
_mqttEntityManager = mqttEntityManager;
_serviceProvider = serviceProvider;
_logger = logger;
_ = InitializeAsync();
}
private async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(5));
await _mqttEntityManager.CreateAsync(
RecreateButtonEntityId,
new EntityCreationOptions
{
UniqueId = RecreateButtonEntityId,
Name = "Recreate all MQTT entities"
},
new
{
icon = "mdi:refresh",
device = new
{
identifiers = new[] { "appdaemon" },
name = "AppDaemon",
model = "AppDaemon",
manufacturer = "HomeAssistant App Daemon"
}
}).ConfigureAwait(false);
_logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId);
var button = new Entity(_haContext, RecreateButtonEntityId);
button.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Recreate-all button pressed, recreating all MQTT entities");
Task.Run(HandleRecreateAsync);
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing MqttRecreateApp");
}
}
private async Task HandleRecreateAsync()
{
try
{
await RecreateNordPoolAsync();
await RecreateBoilerMonitorAsync();
await RecreateShowerMonitorAsync();
await RecreatePowerMonitorAsync();
_logger.LogInformation("All MQTT entities recreated successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating MQTT entities");
}
}
private async Task RecreateNordPoolAsync()
{
var entityService = _serviceProvider.GetService<INordPoolEntityService>();
if (entityService is null)
{
_logger.LogDebug("NordPool entity service not registered (disabled), skipping");
return;
}
try
{
var unitOfMeasurement = ReadUnitOfMeasurement() ?? DefaultUnitOfMeasurement;
_logger.LogInformation("Recreating NordPool MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateEntitiesAsync(unitOfMeasurement).ConfigureAwait(false);
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating NordPool entities");
}
}
private async Task RecreateBoilerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IBoilerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping");
return;
}
try
{
_logger.LogInformation("Recreating BoilerMonitor MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateEntitiesAsync().ConfigureAwait(false);
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating BoilerMonitor entities");
}
}
private async Task RecreateShowerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IShowerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping");
return;
}
try
{
_logger.LogInformation("Recreating ShowerMonitor MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating ShowerMonitor entities");
}
}
private async Task RecreatePowerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IPowerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping");
return;
}
try
{
_logger.LogInformation("Recreating PowerMonitor MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateSystemEntitiesAsync().ConfigureAwait(false);
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating PowerMonitor entities");
}
}
private string? ReadUnitOfMeasurement()
{
try
{
var state = _haContext.GetState(NordPoolPriceEntityId);
if (state?.Attributes is IDictionary<string, object> attributes &&
attributes.TryGetValue("unit_of_measurement", out var value))
{
return value switch
{
string s => s,
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
_ => null
};
}
}
catch
{
}
return null;
}
}