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 static readonly string[] AppDaemonIdentifiers = ["appdaemon"]; private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly IMqttEntityManager _mqttEntityManager; private readonly IServiceProvider _serviceProvider; public MqttRecreateApp( IHaContext haContext, IMqttEntityManager mqttEntityManager, IServiceProvider serviceProvider, ILogger 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 = AppDaemonIdentifiers, name = "AppDaemon", model = "AppDaemon", manufacturer = "HomeAssistant App Daemon" } }).ConfigureAwait(false); if (_logger.IsEnabled(LogLevel.Information)) _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(); 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(); 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(); 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(); if (entityService is null) { _logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping"); return; } try { _logger.LogInformation("Recreating PowerMonitor MQTT entities"); await entityService.RemoveSystemEntitiesAsync().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 attributes && attributes.TryGetValue("unit_of_measurement", out var value)) return value switch { string s => s, JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), _ => null }; } catch (Exception ex) { if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId); } return null; } }