77458383d1
- Expand inline guard, return and logger blocks across the monitor services, init classes and tests - Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton - Record the NordPool and boiler service lifetimes in AGENTS.md - Drop the unused persisted-state argument from the boiler test data helper
547 lines
20 KiB
C#
547 lines
20 KiB
C#
using System.Globalization;
|
|
using System.Text.Json;
|
|
using BoilerMonitor.Models;
|
|
using BoilerMonitorManager.Interface;
|
|
using BoilerMonitorManager.Models;
|
|
using HomeAssistant.Entities.Interfaces;
|
|
using Microsoft.Extensions.Logging;
|
|
using NetDaemon.Extensions.MqttEntityManager;
|
|
using NetDaemon.HassModel;
|
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
|
|
|
namespace BoilerMonitorManager;
|
|
|
|
public sealed class BoilerMonitorEntityService(
|
|
IEntityManager entityManager,
|
|
IHaContext haContext,
|
|
ILogger<BoilerMonitorEntityService> logger) : IBoilerMonitorEntityService
|
|
{
|
|
private static readonly string[] CleanableEntityIds =
|
|
[
|
|
ConfigPowerEntityId,
|
|
ConfigSwitchEntityId,
|
|
ConfigPollIntervalEntityId,
|
|
ConfigHeatingThresholdEntityId,
|
|
StatusEntityId,
|
|
WaterReadyEntityId,
|
|
SkipPriceCapEntityId,
|
|
TodayRuntimeEntityId,
|
|
RemainingTimeEntityId,
|
|
BudgetPercentageEntityId,
|
|
BudgetExhaustedEntityId,
|
|
SessionCountEntityId,
|
|
BudgetOverrideEntityId,
|
|
AutoManagementEntityId
|
|
];
|
|
|
|
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
var entities = GetAllEntities();
|
|
|
|
var createTasks = entities.Select(async entity =>
|
|
{
|
|
try
|
|
{
|
|
if (logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
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}", entity.EntityId);
|
|
}
|
|
});
|
|
|
|
await Task.WhenAll(createTasks).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults");
|
|
|
|
await Task.WhenAll(
|
|
ResetStatusAsync(),
|
|
ResetWaterReadyAsync(),
|
|
ResetSkipPriceCapAsync(),
|
|
ResetTodayRuntimeAsync(),
|
|
ResetRemainingTimeAsync(),
|
|
ResetBudgetPercentageAsync(),
|
|
ResetBudgetExhaustedAsync(),
|
|
ResetSessionCountAsync(),
|
|
ResetBudgetOverrideAsync(),
|
|
ResetAutoManagementAsync()
|
|
).ConfigureAwait(false);
|
|
|
|
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
|
}
|
|
|
|
public async Task UpdateEntitiesAsync(BoilerMonitorUpdateContext ctx, CancellationToken cancellationToken = default)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
var timestamp = DateTime.UtcNow.ToString("O");
|
|
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
|
|
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
|
|
|
|
var updateTasks = new[]
|
|
{
|
|
UpdateStatusAsync(StatusConfigured),
|
|
UpdateWaterReadyAsync(ctx, timestamp),
|
|
UpdateTodayRuntimeAsync(ctx.TodayRunTime, formattedRunTime, timestamp),
|
|
UpdateRemainingTimeAsync(ctx.RemainingTime, formattedRemaining, ctx.BudgetHours, timestamp),
|
|
UpdateBudgetPercentageAsync(ctx.BudgetPercentage, timestamp),
|
|
UpdateBudgetExhaustedAsync(ctx.BudgetExhausted),
|
|
UpdateSessionCountAsync(ctx.SessionCount, timestamp)
|
|
};
|
|
|
|
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
try
|
|
{
|
|
var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
|
|
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
|
|
|
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public async Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)");
|
|
|
|
await Task.WhenAll(
|
|
ResetStatusAsync(),
|
|
ResetWaterReadyAsync()
|
|
).ConfigureAwait(false);
|
|
}
|
|
|
|
public PersistedBoilerState? ReadPersistedState()
|
|
{
|
|
try
|
|
{
|
|
var runtimeState = haContext.GetState(TodayRuntimeEntityId)?.State;
|
|
var sessionCountState = haContext.GetState(SessionCountEntityId)?.State;
|
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
|
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
|
|
|
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) ||
|
|
!TryParseEntityInt(sessionCountState, out var sessionCount))
|
|
{
|
|
if (logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
logger.LogInformation(
|
|
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
|
runtimeState, sessionCountState);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
var persisted = new PersistedBoilerState
|
|
{
|
|
AccumulatedRunTime = TimeSpan.FromSeconds(runtimeSeconds),
|
|
SessionCount = sessionCount,
|
|
SkipPriceCapState = skipPriceCapState,
|
|
BudgetOverrideState = budgetOverrideState
|
|
};
|
|
|
|
if (logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
logger.LogInformation(
|
|
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
|
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
|
persisted.BudgetOverrideState);
|
|
}
|
|
|
|
return persisted;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async Task SetStatusAsync(string status)
|
|
{
|
|
await UpdateStatusAsync(status).ConfigureAwait(false);
|
|
}
|
|
|
|
public DateTimeOffset? ReadPersistedCooldownTimestamp()
|
|
{
|
|
try
|
|
{
|
|
var entity = haContext.GetState(WaterReadyEntityId);
|
|
if (entity?.Attributes is not IDictionary<string, object> attributes) return null;
|
|
|
|
if (!attributes.TryGetValue("cooldown_since", out var value)) return null;
|
|
|
|
var stringValue = value switch
|
|
{
|
|
string s => s,
|
|
JsonElement { ValueKind: JsonValueKind.String } jsonElement =>
|
|
jsonElement.GetString(),
|
|
_ => null
|
|
};
|
|
|
|
if (stringValue is not null &&
|
|
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
|
DateTimeStyles.RoundtripKind, out var parsed))
|
|
{
|
|
if (logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
|
|
}
|
|
|
|
return parsed;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Error reading persisted cooldown timestamp");
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static object CreateDeviceBlock()
|
|
{
|
|
return new
|
|
{
|
|
identifiers = new[] { DeviceIdentifier },
|
|
name = DeviceName,
|
|
model = DeviceName,
|
|
manufacturer = DeviceManufacturer
|
|
};
|
|
}
|
|
|
|
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
|
{
|
|
seconds = 0;
|
|
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state)
|
|
&& state is not ("unavailable" or "unknown")
|
|
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
|
|
&& seconds >= 0;
|
|
|
|
return tryParseEntitySeconds;
|
|
}
|
|
|
|
private static bool TryParseEntityInt(string? state, out int value)
|
|
{
|
|
value = 0;
|
|
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state)
|
|
&& state is not ("unavailable" or "unknown")
|
|
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
|
|
&& value >= 0;
|
|
|
|
return tryParseEntityInt;
|
|
}
|
|
|
|
private static ICollection<BoilerMonitorEntity> GetAllEntities()
|
|
{
|
|
var device = CreateDeviceBlock();
|
|
|
|
return
|
|
[
|
|
new BoilerMonitorEntity("text", "boilermonitor_config_power_entity_id", "Boiler power entity ID")
|
|
{
|
|
AdditionalConfig = new { icon = "mdi:flash", device }
|
|
},
|
|
new BoilerMonitorEntity("text", "boilermonitor_config_switch_entity_id", "Boiler switch entity ID")
|
|
{
|
|
AdditionalConfig = new { icon = "mdi:toggle-switch", device }
|
|
},
|
|
new BoilerMonitorEntity("number", "boilermonitor_config_poll_interval", "Poll interval (seconds)")
|
|
{
|
|
AdditionalConfig = new
|
|
{
|
|
min = (double)MinPollIntervalSeconds,
|
|
max = (double)MaxPollIntervalSeconds,
|
|
step = (double)PollIntervalStepSeconds,
|
|
unit_of_measurement = "s",
|
|
icon = "mdi:timer-outline",
|
|
device
|
|
}
|
|
},
|
|
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
|
|
"Heating power threshold (watts)")
|
|
{
|
|
AdditionalConfig = new
|
|
{
|
|
min = MinHeatingThresholdWatts,
|
|
max = MaxHeatingThresholdWatts,
|
|
step = HeatingThresholdStepWatts,
|
|
unit_of_measurement = "W",
|
|
icon = "mdi:thermometer",
|
|
device
|
|
}
|
|
},
|
|
new BoilerMonitorEntity("button", "boilermonitor_cleanup", "Cleanup all entities")
|
|
{
|
|
AdditionalConfig = new { icon = "mdi:delete-sweep", device }
|
|
},
|
|
new BoilerMonitorEntity("sensor", "boilermonitor_status", "Boiler Monitor status")
|
|
{
|
|
AdditionalConfig = new { icon = "mdi:information-outline", device }
|
|
},
|
|
new BoilerMonitorEntity("sensor", "boilermonitor_water_ready", "Boiler water ready")
|
|
{
|
|
AdditionalConfig = new { icon = "mdi:water-thermometer", device }
|
|
},
|
|
new BoilerMonitorEntity("switch", "boilermonitor_skip_price_cap", "Skip price cap, heat until ready")
|
|
{
|
|
AdditionalConfig = new { optimistic = true, icon = "mdi:water-thermometer-outline", device }
|
|
},
|
|
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
|
{
|
|
AdditionalConfig = new
|
|
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
|
},
|
|
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
|
{
|
|
AdditionalConfig = new
|
|
{ unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
|
},
|
|
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
|
{
|
|
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:percent", device }
|
|
},
|
|
new BoilerMonitorEntity("binary_sensor", "boilermonitor_budget_exhausted", "Budget exhausted")
|
|
{
|
|
Options = new EntityCreationOptions
|
|
{
|
|
UniqueId = BudgetExhaustedEntityId,
|
|
Name = "Budget exhausted"
|
|
},
|
|
AdditionalConfig = new { icon = "mdi:battery-alert", device }
|
|
},
|
|
new BoilerMonitorEntity("sensor", "boilermonitor_session_count", "Heating sessions today")
|
|
{
|
|
AdditionalConfig = new { icon = "mdi:counter", device }
|
|
},
|
|
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
|
|
{
|
|
AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device }
|
|
},
|
|
new BoilerMonitorEntity("switch", "boilermonitor_auto_management", "Automatic boiler control")
|
|
{
|
|
AdditionalConfig = new { optimistic = true, icon = "mdi:robot-outline", device }
|
|
}
|
|
];
|
|
}
|
|
|
|
private async Task UpdateStatusAsync(string status)
|
|
{
|
|
await SetEntityStateSafe(StatusEntityId, status).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetStatusAsync()
|
|
{
|
|
await SetEntityStateSafe(StatusEntityId, StatusAwaitingConfiguration).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetWaterReadyAsync()
|
|
{
|
|
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
|
{
|
|
boiler_switch_state = "unknown",
|
|
boiler_power_watts = 0.0,
|
|
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
|
friendly_name = "Boiler water ready",
|
|
last_updated = (string?)null
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetSkipPriceCapAsync()
|
|
{
|
|
await SetEntityStateSafe(SkipPriceCapEntityId, "OFF").ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetTodayRuntimeAsync()
|
|
{
|
|
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
|
{
|
|
formatted = "0h 0m",
|
|
friendly_name = "Today runtime",
|
|
last_updated = (string?)null
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetRemainingTimeAsync()
|
|
{
|
|
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
|
{
|
|
formatted = "0h 0m",
|
|
budget_hours = 0.0,
|
|
friendly_name = "Remaining budget time",
|
|
last_updated = (string?)null
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetBudgetPercentageAsync()
|
|
{
|
|
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
|
{
|
|
unit_of_measurement = "%",
|
|
friendly_name = "Budget usage",
|
|
last_updated = (string?)null
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetBudgetExhaustedAsync()
|
|
{
|
|
await SetEntityStateSafe(BudgetExhaustedEntityId, "off").ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetSessionCountAsync()
|
|
{
|
|
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
|
{
|
|
friendly_name = "Heating sessions today",
|
|
last_updated = (string?)null
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetBudgetOverrideAsync()
|
|
{
|
|
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ResetAutoManagementAsync()
|
|
{
|
|
await SetEntityStateSafe(AutoManagementEntityId, "ON").ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
|
{
|
|
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
|
{
|
|
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
|
boiler_power_watts = ctx.BoilerPowerWatts,
|
|
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
|
friendly_name = "Boiler water ready",
|
|
last_updated = timestamp
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
|
{
|
|
await SetEntityStateSafe(TodayRuntimeEntityId,
|
|
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
|
{
|
|
formatted,
|
|
friendly_name = "Today runtime",
|
|
last_updated = timestamp
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours,
|
|
string timestamp)
|
|
{
|
|
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
|
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
|
|
.ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
|
{
|
|
formatted,
|
|
budget_hours = budgetHours,
|
|
friendly_name = "Remaining budget time",
|
|
last_updated = timestamp
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
|
{
|
|
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
|
await SetEntityStateSafe(BudgetPercentageEntityId,
|
|
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
|
{
|
|
unit_of_measurement = "%",
|
|
friendly_name = "Budget usage",
|
|
last_updated = timestamp
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
|
{
|
|
await SetEntityStateSafe(BudgetExhaustedEntityId, exhausted ? "on" : "off").ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
|
{
|
|
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
|
|
.ConfigureAwait(false);
|
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
|
{
|
|
friendly_name = "Heating sessions today",
|
|
last_updated = timestamp
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task SetEntityStateSafe(string entityId, string state)
|
|
{
|
|
try
|
|
{
|
|
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
|
if (logger.IsEnabled(LogLevel.Debug))
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
|
|
private async Task SetEntityAttributesSafe(string entityId, object attributes)
|
|
{
|
|
try
|
|
{
|
|
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
|
if (logger.IsEnabled(LogLevel.Debug))
|
|
{
|
|
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
|
}
|
|
}
|
|
|
|
private static string FormatTimeSpan(TimeSpan ts)
|
|
{
|
|
var totalHours = (int)ts.TotalHours;
|
|
var minutes = ts.Minutes;
|
|
|
|
return $"{totalHours}h {minutes}m";
|
|
}
|
|
} |