Files
HomeAssistant/NordPool.Manager/NordPoolEntityService.cs
T

352 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 class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger) : INordPoolEntityService
{
private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time";
private const string CurrentPriceEntityId = "sensor.nordpool_current_price";
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 const string BoilerWaterReadyEntityId = "sensor.nordpool_boiler_water_ready";
private const string BoilerSkipPriceCapEntityId = "switch.nordpool_boiler_skip_price_cap";
private static readonly string[] AllEntityIds =
[
LastUpdateTimeEntityId,
CurrentPriceEntityId,
TodayPricesEntityId,
TomorrowPricesEntityId,
TodayTomorrowPricesEntityId,
CheapestIntervalsEntityId,
BoilerWaterReadyEntityId,
BoilerSkipPriceCapEntityId
];
public async Task CreateEntitiesAsync(string? unitOfMeasurement)
{
var entitiesToCreate = GetInitEntitiesList(unitOfMeasurement);
foreach (var nordPoolEntity in entitiesToCreate)
{
try
{
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", nordPoolEntity.EntityId);
await entityManager.CreateEntityAsync(nordPoolEntity);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", nordPoolEntity.EntityId);
}
}
}
public async Task ResetEntitiesAsync()
{
logger.LogInformation("Resetting all NordPool entity states to defaults");
await Task.WhenAll(
ResetLastUpdateTimeAsync(),
ResetCurrentPriceAsync(),
ResetTodayPricesAsync(),
ResetTomorrowPricesAsync(),
ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync(),
ResetBoilerWaterReadyAsync(),
ResetBoilerSkipPriceCapAsync()
);
logger.LogInformation("All NordPool entity states reset to defaults");
}
private async Task ResetLastUpdateTimeAsync()
{
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown");
await SetEntityAttributesSafe(LastUpdateTimeEntityId, new
{
friendly_name = "NordPool last update time"
});
}
private async Task ResetCurrentPriceAsync()
{
await SetEntityStateSafe(CurrentPriceEntityId, "0");
await SetEntityAttributesSafe(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
});
}
private async Task ResetTodayPricesAsync()
{
await SetEntityStateSafe(TodayPricesEntityId, "0");
await SetEntityAttributesSafe(TodayPricesEntityId, new
{
prices = Array.Empty<NordPoolDayPrice>(),
friendly_name = "NordPool today prices",
last_updated = (string?)null
});
}
private async Task ResetTomorrowPricesAsync()
{
await SetEntityStateSafe(TomorrowPricesEntityId, "0");
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{
prices = Array.Empty<NordPoolDayPrice>(),
friendly_name = "NordPool tomorrow prices",
last_updated = (string?)null
});
}
private async Task ResetTodayTomorrowPricesAsync()
{
await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown");
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = Array.Empty<NordPoolDayPrice>(),
prices_count = 0,
friendly_name = "NordPool today and tomorrow prices",
last_updated = (string?)null
});
}
private async Task ResetCheapestIntervalsAsync()
{
await SetEntityStateSafe(CheapestIntervalsEntityId, "0");
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
});
}
private async Task ResetBoilerWaterReadyAsync()
{
await SetEntityStateSafe(BoilerWaterReadyEntityId, "unknown");
await SetEntityAttributesSafe(BoilerWaterReadyEntityId, new
{
boiler_switch_state = "unknown",
boiler_power_watts = 0.0,
power_threshold_watts = 5.0,
friendly_name = "Boiler water ready",
last_updated = (string?)null
});
}
private async Task ResetBoilerSkipPriceCapAsync()
{
await SetEntityStateSafe(BoilerSkipPriceCapEntityId, "OFF");
}
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx)
{
var utcNow = DateTime.UtcNow;
var timestamp = utcNow.ToString("O");
await SetEntityStateSafe(LastUpdateTimeEntityId, utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"));
var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture);
logger.LogInformation("Updating nordpool_current_price with value: {Price} {Unit}", priceValue, ctx.UnitOfMeasurement);
await SetEntityStateSafe(CurrentPriceEntityId, priceValue);
await SetEntityAttributesSafe(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"),
using_cached_data = ctx.UsingCachedData,
current_quarter_index = ctx.DayQuartersIndex
});
var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0;
logger.LogInformation("Updating sensor.nordpool_today_prices with {Count} prices", todayPricesCount);
await SetEntityStateSafe(TodayPricesEntityId, todayPricesCount.ToString());
await SetEntityAttributesSafe(TodayPricesEntityId, new
{
prices = ctx.TodayNordPoolPrice?.Prices ?? Array.Empty<NordPoolDayPrice>(),
friendly_name = "NordPool today prices",
last_updated = timestamp
});
var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0;
logger.LogInformation("Updating sensor.nordpool_tomorrow_prices with {Count} prices", tomorrowPricesCount);
await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString());
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{
prices = ctx.TomorrowNordPoolPrice?.Prices ?? Array.Empty<NordPoolDayPrice>(),
friendly_name = "NordPool tomorrow prices",
last_updated = timestamp
});
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
logger.LogInformation("Updating sensor.nordpool_today_tomorrow_prices with {Count} merged prices", mergedPrices.Count);
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = mergedPrices,
prices_count = mergedPrices.Count,
friendly_name = "NordPool today and tomorrow prices",
last_updated = timestamp
});
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap);
await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString());
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 * 15,
is_now_cheap = ctx.IsNowCheap,
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O"),
friendly_name = "NordPool cheapest boiler intervals",
last_updated = timestamp
});
logger.LogInformation("Updating sensor.nordpool_boiler_water_ready: {WaterReady} (switch={Switch}, power={Power}W)", ctx.WaterReady, ctx.BoilerSwitchState, ctx.BoilerPowerWatts);
await SetEntityStateSafe(BoilerWaterReadyEntityId, ctx.WaterReady ? "yes" : "no");
await SetEntityAttributesSafe(BoilerWaterReadyEntityId, new
{
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
boiler_power_watts = ctx.BoilerPowerWatts,
power_threshold_watts = 5.0,
friendly_name = "Boiler water ready",
last_updated = timestamp
});
logger.LogInformation("NordPool entities updated successfully. Today prices count: {TodayCount}, Tomorrow prices count: {TomorrowCount}", todayPricesCount, tomorrowPricesCount);
}
public async Task CleanupEntitiesAsync()
{
try
{
foreach (var entityId in AllEntityIds)
{
await entityManager.RemoveEntity(entityId);
}
logger.LogInformation("NordPool entities cleaned up successfully");
}
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up NordPool entities");
throw;
}
}
internal ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
{
var entries = new List<NordPoolEntity>();
entries.AddRange([
new NordPoolEntity("sensor", "nordpool_last_update_time", "NordPool last update time"),
new NordPoolEntity("sensor", "nordpool_current_price", "NordPool current price")
{
Options = new EntityCreationOptions
{
UniqueId = CurrentPriceEntityId,
Name = "NordPool current price"
},
AdditionalConfig = 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("sensor", "nordpool_boiler_water_ready", "Boiler water ready"),
new NordPoolEntity("switch", "nordpool_boiler_skip_price_cap", "Skip price cap, heat until ready")
{
AdditionalConfig = new
{
optimistic = true,
icon = "mdi:water-thermometer-outline"
}
}
]);
return entries;
}
private static List<NordPoolDayPrice> MergeTodayTomorrowPrices(NordPoolPrice? today, NordPoolPrice? tomorrow)
{
var todayList = today?.Prices ?? [];
var tomorrowList = tomorrow?.Prices ?? [];
return todayList
.Concat(tomorrowList)
.Where(p => p?.Start != null)
.OrderBy(p => p!.Start!.Value)
.ToList();
}
internal async Task SetEntityStateSafe(string entityId, string state)
{
try
{
await entityManager.SetEntityState(entityId, state);
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);
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
}
}
}