Files
HomeAssistant/NordPool.Manager/NordPoolEntityService.cs
T
gitea_admin 24729ee267 Apply code formatting cleanup across monitor projects
- Reindent appsettings.json and the MSBuild project files
- Collapse single-statement guard blocks and tidy using and member order
- Normalize XML doc indentation and file endings
- Reorder BatteryMonitor test-data helpers and move the exclusion tests into
  their own region
- Carry the same formatting through the boiler config, control, entity and
  test files
2026-11-30 11:52:06 +02:00

349 lines
14 KiB
C#

using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using NetDaemon.Extensions.MqttEntityManager;
using NordPool.Models;
using NordPoolManager.Interface;
using NordPoolManager.Models;
namespace NordPoolManager;
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger)
: INordPoolEntityService
{
private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time";
private const string TodayPricesEntityId = "sensor.nordpool_today_prices";
private const string TomorrowPricesEntityId = "sensor.nordpool_tomorrow_prices";
private const string TodayTomorrowPricesEntityId = "sensor.nordpool_today_tomorrow_prices";
private const string CheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
private static readonly string[] AllEntityIds =
[
LastUpdateTimeEntityId,
NordPoolConsts.CurrentPriceEntityId,
TodayPricesEntityId,
TomorrowPricesEntityId,
TodayTomorrowPricesEntityId,
CheapestIntervalsEntityId,
NordPoolConsts.FetchPricesButtonEntityId
];
public async Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var entitiesToCreate = GetInitEntitiesList(unitOfMeasurement);
var createTasks = entitiesToCreate.Select(async nordPoolEntity =>
{
try
{
await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", nordPoolEntity.EntityId);
}
});
await Task.WhenAll(createTasks).ConfigureAwait(false);
}
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.WhenAll(
ResetLastUpdateTimeAsync(),
ResetCurrentPriceAsync(),
ResetTodayPricesAsync(),
ResetTomorrowPricesAsync(),
ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync(),
ResetFetchPricesButtonAsync()
).ConfigureAwait(false);
}
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var utcNow = DateTime.UtcNow;
var timestamp = utcNow.ToString("O");
var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture);
var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0;
var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0;
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
logger.LogWarning(
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation(
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
cheapestCount, ctx.IsNowCheap);
var updateTasks = new[]
{
UpdateLastUpdateTimeAsync(updateTimeState),
UpdateCurrentPriceAsync(priceValue, ctx, timestamp),
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp)
};
await Task.WhenAll(updateTasks).ConfigureAwait(false);
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
await Task.WhenAll(removeTasks).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up NordPool entities");
throw;
}
}
private async Task ResetLastUpdateTimeAsync()
{
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(LastUpdateTimeEntityId, new
{
friendly_name = "NordPool last update time"
}).ConfigureAwait(false);
}
private async Task ResetCurrentPriceAsync()
{
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{
unit_of_measurement = (string?)null,
device_class = "monetary",
state_class = "measurement",
friendly_name = "NordPool current price",
last_updated = (string?)null,
last_api_fetch = (string?)null,
using_cached_data = false,
current_quarter_index = 0
}).ConfigureAwait(false);
}
private async Task ResetTodayPricesAsync()
{
await SetEntityStateSafe(TodayPricesEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayPricesEntityId, new
{
prices = Array.Empty<CompactNordPoolDayPrice>(),
friendly_name = "NordPool today prices",
last_updated = (string?)null
}).ConfigureAwait(false);
}
private async Task ResetTomorrowPricesAsync()
{
await SetEntityStateSafe(TomorrowPricesEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{
prices = Array.Empty<CompactNordPoolDayPrice>(),
friendly_name = "NordPool tomorrow prices",
last_updated = (string?)null
}).ConfigureAwait(false);
}
private async Task ResetTodayTomorrowPricesAsync()
{
await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = Array.Empty<CompactNordPoolDayPrice>(),
prices_count = 0,
friendly_name = "NordPool today and tomorrow prices",
last_updated = (string?)null
}).ConfigureAwait(false);
}
private async Task ResetCheapestIntervalsAsync()
{
await SetEntityStateSafe(CheapestIntervalsEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
{
intervals = Array.Empty<CheapestIntervalResult>(),
configured_hours = 0.0,
configured_interval_count = 0,
configured_price_cap = 0.0,
configured_ready_by = "",
total_heating_minutes = 0,
is_now_cheap = false,
next_cheap_interval = (string?)null,
friendly_name = "NordPool cheapest boiler intervals",
last_updated = (string?)null
}).ConfigureAwait(false);
}
private async Task ResetFetchPricesButtonAsync()
{
await SetEntityStateSafe(NordPoolConsts.FetchPricesButtonEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.FetchPricesButtonEntityId, new
{
friendly_name = "NordPool fetch prices"
}).ConfigureAwait(false);
}
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
{
await SetEntityStateSafe(LastUpdateTimeEntityId, updateTimeState).ConfigureAwait(false);
}
private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp)
{
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{
unit_of_measurement = ctx.UnitOfMeasurement,
device_class = "monetary",
state_class = "measurement",
friendly_name = "NordPool current price",
last_updated = timestamp,
last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture),
using_cached_data = ctx.UsingCachedData,
current_quarter_index = ctx.DayQuartersIndex
}).ConfigureAwait(false);
}
private async Task UpdateTodayPricesAsync(EntityUpdateContext ctx, int todayPricesCount, string timestamp)
{
await SetEntityStateSafe(TodayPricesEntityId, todayPricesCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(TodayPricesEntityId, new
{
prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(),
friendly_name = "NordPool today prices",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateTomorrowPricesAsync(EntityUpdateContext ctx, int tomorrowPricesCount, string timestamp)
{
await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{
prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(),
friendly_name = "NordPool tomorrow prices",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState,
string timestamp)
{
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = mergedPrices.ToCompact(),
prices_count = mergedPrices.Count,
friendly_name = "NordPool today and tomorrow prices",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateCheapestIntervalsAsync(EntityUpdateContext ctx, int cheapestCount, string timestamp)
{
await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
{
intervals = ctx.CheapestIntervals ?? [],
configured_hours = ctx.ConfiguredHours,
configured_interval_count = ctx.ConfiguredIntervalCount,
configured_price_cap = ctx.ConfiguredPriceCap,
skip_price_cap = ctx.SkipPriceCap,
configured_ready_by = ctx.ConfiguredReadyBy,
total_heating_minutes = cheapestCount * NordPoolConsts.MinutesPerInterval,
is_now_cheap = ctx.IsNowCheap,
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture),
friendly_name = "NordPool cheapest boiler intervals",
last_updated = timestamp
}).ConfigureAwait(false);
}
internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
{
const string currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId;
var currentPriceDomainSeparator = currentPriceEntityId.IndexOf('.', StringComparison.Ordinal);
var currentPriceDomain = currentPriceEntityId[..currentPriceDomainSeparator];
var currentPriceObjectId = currentPriceEntityId[(currentPriceDomainSeparator + 1)..];
return
[
new NordPoolEntity("sensor", "nordpool_last_update_time", "NordPool last update time"),
new NordPoolEntity(currentPriceDomain, currentPriceObjectId, "NordPool current price")
{
Options = new EntityCreationOptions
{
UniqueId = currentPriceEntityId,
Name = "NordPool current price"
},
AdditionalConfig = NordPoolEntity.CreateAdditionalConfig(new
{
unit_of_measurement = unitOfMeasurement,
state_class = "measurement"
})
},
new NordPoolEntity("sensor", "nordpool_today_prices", "NordPool today prices"),
new NordPoolEntity("sensor", "nordpool_tomorrow_prices", "NordPool tomorrow prices"),
new NordPoolEntity("sensor", "nordpool_today_tomorrow_prices", "NordPool today and tomorrow prices"),
new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals"),
new NordPoolEntity("button", "nordpool_fetch_prices", "NordPool fetch prices")
];
}
private static List<NordPoolDayPrice> MergeTodayTomorrowPrices(NordPoolPrice? today, NordPoolPrice? tomorrow)
{
var todayList = today?.Prices ?? [];
var tomorrowList = tomorrow?.Prices ?? [];
return
[
.. todayList
.Concat(tomorrowList)
.Where(p => p is { Start: not null })
.OrderBy(p => p.Start!.Value)
];
}
internal async Task SetEntityStateSafe(string entityId, string state)
{
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
}
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);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
}
}
}