Init
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
||||
{
|
||||
private const string SwitchOnState = "on";
|
||||
|
||||
public BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState)
|
||||
{
|
||||
var isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||
var shouldBeOn = isNowCheap && !waterReady;
|
||||
|
||||
if (shouldBeOn && !isCurrentlyOn)
|
||||
{
|
||||
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready (current state: {State})", currentSwitchState);
|
||||
|
||||
return BoilerAction.TurnOn;
|
||||
}
|
||||
|
||||
if (!shouldBeOn && isCurrentlyOn)
|
||||
{
|
||||
var reason = waterReady ? "water is already ready" : "not in a cheap interval";
|
||||
|
||||
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
|
||||
|
||||
return BoilerAction.TurnOff;
|
||||
}
|
||||
|
||||
logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady})", currentSwitchState, isNowCheap, waterReady);
|
||||
|
||||
return BoilerAction.NoChange;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
||||
{
|
||||
private const double WaterReadyPowerThresholdWatts = 5.0;
|
||||
private const string SwitchOnState = "on";
|
||||
|
||||
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
|
||||
{
|
||||
if (prices.Prices is not { Count: > 0 })
|
||||
{
|
||||
logger.LogWarning("No prices available for cheapest interval calculation");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
if (numberOfIntervals <= 0)
|
||||
{
|
||||
logger.LogWarning("Number of intervals requested is {Count}, returning empty", numberOfIntervals);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
var eligible = prices.Prices
|
||||
.AsParallel()
|
||||
.Where(p => p is { Start: not null, End: not null, Price: not null })
|
||||
.Where(p => p.End!.Value <= deadline)
|
||||
.Where(p => p.Price!.Value <= priceCap)
|
||||
.OrderBy(p => p.Price!.Value)
|
||||
.ThenBy(p => p.Start!.Value)
|
||||
.Take(numberOfIntervals)
|
||||
.ToList();
|
||||
|
||||
var ranked = eligible
|
||||
.Select((p, index) => new CheapestIntervalResult
|
||||
{
|
||||
Start = p.Start!.Value,
|
||||
End = p.End!.Value,
|
||||
Price = p.Price!.Value,
|
||||
Rank = index + 1
|
||||
})
|
||||
.OrderBy(r => r.Start)
|
||||
.ToList();
|
||||
|
||||
logger.LogInformation("Found {Count} cheapest intervals out of {Requested} requested (deadline: {Deadline}, price cap: {Cap})", ranked.Count, numberOfIntervals, deadline, priceCap);
|
||||
|
||||
return ranked;
|
||||
}
|
||||
|
||||
public bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow)
|
||||
{
|
||||
return cheapestIntervals.AsParallel().Any(interval => utcNow >= interval.Start && utcNow < interval.End);
|
||||
}
|
||||
|
||||
public bool IsWaterReady(string? switchState, double? powerWatts)
|
||||
{
|
||||
if (switchState == null || powerWatts == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase) && powerWatts.Value < WaterReadyPowerThresholdWatts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using NordPoolManager.Models;
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface IBoilerControlService
|
||||
{
|
||||
BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using NordPool.Models;
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface ICheapestIntervalsFinder
|
||||
{
|
||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline);
|
||||
|
||||
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
||||
|
||||
bool IsWaterReady(string? switchState, double? powerWatts);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using NordPoolManager.Models;
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface INordPoolEntityService
|
||||
{
|
||||
Task CreateEntitiesAsync(string? unitOfMeasurement);
|
||||
Task ResetEntitiesAsync();
|
||||
Task UpdateEntitiesAsync(EntityUpdateContext context);
|
||||
Task CleanupEntitiesAsync();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface INordPoolInit
|
||||
{
|
||||
Task InitializeAsync();
|
||||
Task CleanupEntitiesAsync();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using NordPool.Models;
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface INordPoolPriceService
|
||||
{
|
||||
NordPoolPrice? TodayNordPoolPrice { get; }
|
||||
NordPoolPrice? TomorrowNordPoolPrice { get; }
|
||||
double CurrentPrice { get; }
|
||||
int DayQuartersIndex { get; }
|
||||
DateTime? LastUpdatedDate { get; }
|
||||
DateOnly? LastFetchedDate { get; }
|
||||
|
||||
Task FetchPricesAsync();
|
||||
double UpdateCurrentPrice();
|
||||
bool ShouldFetchNewPrices(DateOnly today);
|
||||
void RollOverPrices(DateOnly today);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace NordPoolManager.Models;
|
||||
|
||||
public enum BoilerAction
|
||||
{
|
||||
NoChange,
|
||||
TurnOn,
|
||||
TurnOff
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace NordPoolManager.Models;
|
||||
|
||||
public class BoilerConfig
|
||||
{
|
||||
public int IntervalCount { get; set; }
|
||||
public double PriceCap { get; set; }
|
||||
public DateTime Deadline { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace NordPoolManager.Models;
|
||||
|
||||
public static class ConversionConsts
|
||||
{
|
||||
public const double MegawattToKilowattDivisor = 1000.0;
|
||||
public const double VatRate = 1.21; // 21% VAT (PVM)
|
||||
public const double EuroToCentsMultiplier = 100.0;
|
||||
public const int PriceDecimalPlaces = 2;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using NordPool.Models;
|
||||
|
||||
namespace NordPoolManager.Models;
|
||||
|
||||
public record EntityUpdateContext
|
||||
{
|
||||
public required double CurrentPrice { get; init; }
|
||||
public required string? UnitOfMeasurement { get; init; }
|
||||
public required int DayQuartersIndex { get; init; }
|
||||
public required DateTime? LastApiUpdateDate { get; init; }
|
||||
public required bool UsingCachedData { get; init; }
|
||||
public required NordPoolPrice? TodayNordPoolPrice { get; init; }
|
||||
public required NordPoolPrice? TomorrowNordPoolPrice { get; init; }
|
||||
public required IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; init; }
|
||||
public required double ConfiguredHours { get; init; }
|
||||
public required int ConfiguredIntervalCount { get; init; }
|
||||
public required double ConfiguredPriceCap { get; init; }
|
||||
public required string? ConfiguredReadyBy { get; init; }
|
||||
public required bool IsNowCheap { get; init; }
|
||||
public required DateTime? NextCheapIntervalStart { get; init; }
|
||||
public required bool WaterReady { get; init; }
|
||||
public required string? BoilerSwitchState { get; init; }
|
||||
public required double? BoilerPowerWatts { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>NordPoolManager</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>NordPool.Manager.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="16.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,292 @@
|
||||
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 CheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
|
||||
private const string BoilerWaterReadyEntityId = "sensor.nordpool_boiler_water_ready";
|
||||
|
||||
private static readonly string[] AllEntityIds =
|
||||
[
|
||||
LastUpdateTimeEntityId,
|
||||
CurrentPriceEntityId,
|
||||
TodayPricesEntityId,
|
||||
TomorrowPricesEntityId,
|
||||
CheapestIntervalsEntityId,
|
||||
BoilerWaterReadyEntityId
|
||||
];
|
||||
|
||||
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(),
|
||||
ResetCheapestIntervalsAsync(),
|
||||
ResetBoilerWaterReadyAsync()
|
||||
);
|
||||
|
||||
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 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
|
||||
});
|
||||
}
|
||||
|
||||
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 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,
|
||||
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_cheapest_intervals", "NordPool cheapest boiler intervals"),
|
||||
new NordPoolEntity("sensor", "nordpool_boiler_water_ready", "Boiler water ready")
|
||||
]);
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
using System.Reactive.Concurrency;
|
||||
using HomeAssistantGenerated;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NetDaemon.AppModel;
|
||||
using NetDaemon.Extensions.Scheduler;
|
||||
using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
using static NordPoolManager.Models.BoilerAction;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
public class NordPoolInit : INordPoolInit
|
||||
{
|
||||
private readonly ILogger<NordPoolInit> _logger;
|
||||
private readonly INordPoolPriceService _priceService;
|
||||
private readonly INordPoolEntityService _entityService;
|
||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
||||
private readonly IBoilerControlService _boilerControlService;
|
||||
private readonly IScheduler _scheduler;
|
||||
|
||||
private InputNumberEntity BoilerDailyHoursEntity { get; }
|
||||
private InputNumberEntity BoilerPriceCapEntity { get; }
|
||||
private InputDatetimeEntity BoilerReadyByEntity { get; }
|
||||
private SwitchEntity BoilerSwitchEntity { get; }
|
||||
private NumericSensorEntity BoilerPowerEntity { get; }
|
||||
private string? UnitOfMeasurement { get; }
|
||||
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
|
||||
|
||||
public NordPoolInit(
|
||||
Entities entities,
|
||||
ILogger<NordPoolInit> logger,
|
||||
INordPoolPriceService priceService,
|
||||
INordPoolEntityService entityService,
|
||||
IScheduler scheduler,
|
||||
ICheapestIntervalsFinder cheapestIntervalsFinder,
|
||||
IBoilerControlService boilerControlService)
|
||||
{
|
||||
_logger = logger;
|
||||
_priceService = priceService;
|
||||
_entityService = entityService;
|
||||
_scheduler = scheduler;
|
||||
_cheapestIntervalsFinder = cheapestIntervalsFinder;
|
||||
_boilerControlService = boilerControlService;
|
||||
|
||||
var nordPoolPriceSensor = entities.Sensor.NordpoolPrice;
|
||||
UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh";
|
||||
BoilerDailyHoursEntity = entities.InputNumber.BoilerDailyHours;
|
||||
BoilerPriceCapEntity = entities.InputNumber.BoilerPriceCap;
|
||||
BoilerReadyByEntity = entities.InputDatetime.BoilerReadyBy;
|
||||
BoilerSwitchEntity = entities.Switch.Sonoff1002230e32;
|
||||
BoilerPowerEntity = entities.Sensor.Sonoff1002230e32Power;
|
||||
|
||||
_ = InitializeAndScheduleAsync();
|
||||
}
|
||||
|
||||
private async Task InitializeAndScheduleAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await InitializeAsync();
|
||||
SchedulePeriodicUpdates();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during initialization and scheduling");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
await _priceService.FetchPricesAsync();
|
||||
|
||||
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
|
||||
|
||||
await _entityService.ResetEntitiesAsync();
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
|
||||
var currentPrice = _priceService.UpdateCurrentPrice();
|
||||
_logger.LogInformation("Retrieved current price: {Price}, DayQuartersIndex: {Index}", currentPrice, _priceService.DayQuartersIndex);
|
||||
|
||||
if (currentPrice == 0)
|
||||
{
|
||||
_logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval");
|
||||
}
|
||||
|
||||
var (intervalCount, priceCap) = UpdateCheapestIntervals();
|
||||
await UpdateEntitiesAsync(intervalCount, priceCap);
|
||||
|
||||
_logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing NordPool prices");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void SchedulePeriodicUpdates()
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
var currentMinute = now.Minute;
|
||||
var currentSecond = now.Second;
|
||||
|
||||
var minutesUntilNext15 = 15 - (currentMinute % 15);
|
||||
var delayUntilNext15 = TimeSpan.FromMinutes(minutesUntilNext15) - TimeSpan.FromSeconds(currentSecond);
|
||||
var nextUpdateTime = now.Add(delayUntilNext15);
|
||||
|
||||
_logger.LogInformation("Scheduling first NordPool update at {Time} (in {Delay})", nextUpdateTime, delayUntilNext15);
|
||||
|
||||
_scheduler.RunEvery(TimeSpan.FromMinutes(15), nextUpdateTime, async void () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await UpdatePricesAsync();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e, "Error updating NordPool prices");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async Task UpdatePricesAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Starting periodic NordPool price update");
|
||||
|
||||
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
||||
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
|
||||
var today = DateOnly.FromDateTime(nowCet);
|
||||
|
||||
_logger.LogDebug("Current CET time: {CetTime}, Today in CET: {Today}", nowCet, today);
|
||||
|
||||
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
|
||||
{
|
||||
_priceService.RollOverPrices(today);
|
||||
}
|
||||
|
||||
if (_priceService.ShouldFetchNewPrices(today))
|
||||
{
|
||||
_logger.LogInformation("Fetching new prices from NordPool API");
|
||||
await _priceService.FetchPricesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug("Using cached prices, no need to fetch from API");
|
||||
}
|
||||
|
||||
_priceService.UpdateCurrentPrice();
|
||||
|
||||
var (intervalCount, priceCap) = UpdateCheapestIntervals();
|
||||
await UpdateEntitiesAsync(intervalCount, priceCap);
|
||||
|
||||
_logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error updating NordPool prices");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CleanupEntitiesAsync()
|
||||
{
|
||||
await _entityService.CleanupEntitiesAsync();
|
||||
}
|
||||
|
||||
private (int IntervalCount, double PriceCap) UpdateCheapestIntervals()
|
||||
{
|
||||
var boilerConfig = ReadBoilerConfig();
|
||||
|
||||
try
|
||||
{
|
||||
if (_priceService.TodayNordPoolPrice?.Prices is not { Count: > 0 })
|
||||
{
|
||||
_logger.LogDebug("No today prices available, skipping cheapest intervals calculation");
|
||||
CheapestIntervals = [];
|
||||
return (boilerConfig.IntervalCount, boilerConfig.PriceCap);
|
||||
}
|
||||
|
||||
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.Deadline);
|
||||
|
||||
_logger.LogInformation("Cheapest intervals updated: {Count} intervals (config: {Hours}h / {Intervals} intervals, cap: {Cap}, deadline: {Deadline})",
|
||||
CheapestIntervals.Count, boilerConfig.IntervalCount / 4.0, boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.Deadline);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error calculating cheapest intervals");
|
||||
CheapestIntervals = [];
|
||||
}
|
||||
|
||||
return (boilerConfig.IntervalCount, boilerConfig.PriceCap);
|
||||
}
|
||||
|
||||
private BoilerConfig ReadBoilerConfig()
|
||||
{
|
||||
var boilerConfig = new BoilerConfig();
|
||||
|
||||
var dailyHours = BoilerDailyHoursEntity.State ?? 1.0;
|
||||
var intervalCount = (int)(dailyHours * 4);
|
||||
|
||||
if (intervalCount <= 0)
|
||||
{
|
||||
intervalCount = 4;
|
||||
}
|
||||
|
||||
boilerConfig.IntervalCount = intervalCount;
|
||||
|
||||
var priceCap = BoilerPriceCapEntity.State ?? double.MaxValue;
|
||||
|
||||
if (priceCap <= 0)
|
||||
{
|
||||
priceCap = double.MaxValue;
|
||||
}
|
||||
|
||||
boilerConfig.PriceCap = priceCap;
|
||||
|
||||
var deadline = DateTime.Today.AddDays(1);
|
||||
var readyByState = BoilerReadyByEntity.State;
|
||||
|
||||
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime))
|
||||
{
|
||||
deadline = DateTime.Today.Add(readyByTime);
|
||||
}
|
||||
|
||||
boilerConfig.Deadline = deadline;
|
||||
|
||||
_logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, deadline={Deadline}", boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.Deadline);
|
||||
|
||||
return boilerConfig;
|
||||
}
|
||||
|
||||
private async Task UpdateEntitiesAsync(int configuredIntervalCount, double configuredPriceCap)
|
||||
{
|
||||
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
||||
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
|
||||
var todayCet = DateOnly.FromDateTime(nowCet);
|
||||
var currentDateTime = DateTime.Now;
|
||||
|
||||
var configuredHours = BoilerDailyHoursEntity.State ?? 1.0;
|
||||
var configuredReadyBy = BoilerReadyByEntity.State ?? "";
|
||||
var isNowCheap = CheapestIntervals != null &&
|
||||
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
|
||||
var nextCheapInterval = CheapestIntervals?
|
||||
.Where(i => i.Start > currentDateTime)
|
||||
.OrderBy(i => i.Start)
|
||||
.FirstOrDefault();
|
||||
|
||||
var boilerSwitchState = BoilerSwitchEntity.State;
|
||||
var boilerPowerWatts = BoilerPowerEntity.State;
|
||||
var waterReady = _cheapestIntervalsFinder.IsWaterReady(boilerSwitchState, boilerPowerWatts);
|
||||
|
||||
var boilerAction = _boilerControlService.DetermineAction(isNowCheap, waterReady, boilerSwitchState);
|
||||
|
||||
if (boilerAction == TurnOn)
|
||||
{
|
||||
BoilerSwitchEntity.TurnOn();
|
||||
}
|
||||
else if (boilerAction == TurnOff)
|
||||
{
|
||||
BoilerSwitchEntity.TurnOff();
|
||||
}
|
||||
|
||||
var context = new EntityUpdateContext
|
||||
{
|
||||
CurrentPrice = _priceService.CurrentPrice,
|
||||
UnitOfMeasurement = UnitOfMeasurement,
|
||||
DayQuartersIndex = _priceService.DayQuartersIndex,
|
||||
LastApiUpdateDate = _priceService.LastUpdatedDate,
|
||||
UsingCachedData = !_priceService.ShouldFetchNewPrices(todayCet),
|
||||
TodayNordPoolPrice = _priceService.TodayNordPoolPrice,
|
||||
TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice,
|
||||
CheapestIntervals = CheapestIntervals,
|
||||
ConfiguredHours = configuredHours,
|
||||
ConfiguredIntervalCount = configuredIntervalCount,
|
||||
ConfiguredPriceCap = configuredPriceCap,
|
||||
ConfiguredReadyBy = configuredReadyBy,
|
||||
IsNowCheap = isNowCheap,
|
||||
NextCheapIntervalStart = nextCheapInterval?.Start,
|
||||
WaterReady = waterReady,
|
||||
BoilerSwitchState = boilerSwitchState,
|
||||
BoilerPowerWatts = boilerPowerWatts
|
||||
};
|
||||
|
||||
await _entityService.UpdateEntitiesAsync(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System.Text.Json;
|
||||
using AutoMapper;
|
||||
using HomeAssistantGenerated;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NordPool.Models;
|
||||
using NordPool.Models.Dtos;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger) : INordPoolPriceService
|
||||
{
|
||||
private readonly NordpoolServices _nordPoolServices = services.Nordpool;
|
||||
|
||||
public NordPoolPrice? TodayNordPoolPrice { get; internal set; }
|
||||
public NordPoolPrice? TomorrowNordPoolPrice { get; internal set; }
|
||||
public double CurrentPrice { get; internal set; }
|
||||
public int DayQuartersIndex { get; internal set; } = -1;
|
||||
public DateTime? LastUpdatedDate { get; private set; }
|
||||
public DateOnly? LastFetchedDate { get; internal set; }
|
||||
|
||||
public async Task FetchPricesAsync()
|
||||
{
|
||||
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
||||
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
|
||||
var today = DateOnly.FromDateTime(nowCet);
|
||||
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
|
||||
TodayNordPoolPrice = await GetNordPoolPriceAsync(today);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogDebug("Using existing today's prices (already have {Count} prices)", TodayNordPoolPrice.Prices.Count);
|
||||
}
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
|
||||
TomorrowNordPoolPrice = await GetNordPoolPriceAsync(today.AddDays(1));
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogDebug("Already have tomorrow's prices ({Count} prices)", TomorrowNordPoolPrice.Prices.Count);
|
||||
}
|
||||
|
||||
LastUpdatedDate = DateTime.UtcNow;
|
||||
LastFetchedDate = today;
|
||||
|
||||
logger.LogInformation(
|
||||
"Prices ready for today ({Today}). Today prices count: {TodayCount}, Tomorrow prices count: {TomorrowCount}",
|
||||
today, TodayNordPoolPrice?.Prices?.Count ?? 0, TomorrowNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
|
||||
public double UpdateCurrentPrice()
|
||||
{
|
||||
var index = GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
|
||||
if (DayQuartersIndex != index)
|
||||
{
|
||||
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
|
||||
{
|
||||
var price = TodayNordPoolPrice.Prices[index].Price;
|
||||
|
||||
if (price.HasValue)
|
||||
{
|
||||
CurrentPrice = price.Value;
|
||||
logger.LogInformation("Current price updated to: {Price} for quarter index {Index}", CurrentPrice, index);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Price at index {Index} is null", index);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
|
||||
DayQuartersIndex = index;
|
||||
}
|
||||
|
||||
logger.LogDebug("Returning current price: {Price}", CurrentPrice);
|
||||
|
||||
return CurrentPrice;
|
||||
}
|
||||
|
||||
public bool ShouldFetchNewPrices(DateOnly today)
|
||||
{
|
||||
if (!LastFetchedDate.HasValue)
|
||||
{
|
||||
logger.LogDebug("No cached prices, need to fetch");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (LastFetchedDate.Value < today)
|
||||
{
|
||||
logger.LogDebug("New day detected, need to fetch fresh prices");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
logger.LogDebug("Today's prices are missing, need to fetch");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
var currentHour = DateTime.Now.Hour;
|
||||
|
||||
if (currentHour >= 13)
|
||||
{
|
||||
logger.LogDebug("Checking for tomorrow's prices (after 13:00)");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void RollOverPrices(DateOnly today)
|
||||
{
|
||||
logger.LogInformation("New day detected in CET timezone! Rolling over tomorrow's prices to today. Previous date: {PreviousDate}, Current date: {CurrentDate}", LastFetchedDate, today);
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
|
||||
{
|
||||
TodayNordPoolPrice = TomorrowNordPoolPrice;
|
||||
logger.LogInformation("Moved tomorrow's prices ({Count} prices) to today", TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
TodayNordPoolPrice = new NordPoolPrice();
|
||||
logger.LogWarning("Tomorrow's prices were not available during rollover, clearing stale today's prices to trigger re-fetch");
|
||||
}
|
||||
|
||||
TomorrowNordPoolPrice = null;
|
||||
logger.LogInformation("Cleared tomorrow's prices");
|
||||
|
||||
DayQuartersIndex = -1;
|
||||
LastFetchedDate = today;
|
||||
}
|
||||
|
||||
internal async Task<NordPoolPrice> GetNordPoolPriceAsync(DateOnly date)
|
||||
{
|
||||
var nordPoolPricesDto = await _nordPoolServices.GetPricesForDateAsync(
|
||||
new NordpoolGetPricesForDateParameters
|
||||
{
|
||||
Areas = "LT",
|
||||
ConfigEntry = NordPoolConsts.ConfigEntry,
|
||||
Currency = "EUR",
|
||||
Date = date
|
||||
});
|
||||
|
||||
var nordPoolResult = ParseNordPoolResult(nordPoolPricesDto);
|
||||
|
||||
return AdjustedNordPoolPrice(nordPoolResult);
|
||||
}
|
||||
|
||||
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
||||
{
|
||||
if (element == null)
|
||||
{
|
||||
return new NordPoolPrice();
|
||||
}
|
||||
|
||||
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
||||
|
||||
return priceResult != null ? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult) : new NordPoolPrice();
|
||||
}
|
||||
|
||||
internal NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
|
||||
{
|
||||
var recalculatedPrice = new NordPoolPrice
|
||||
{
|
||||
Prices = new List<NordPoolDayPrice>()
|
||||
};
|
||||
|
||||
if (todayNordPoolPrice.Prices != null)
|
||||
{
|
||||
foreach (var price in todayNordPoolPrice.Prices)
|
||||
{
|
||||
if (price.Price != null)
|
||||
{
|
||||
recalculatedPrice.Prices.Add(new NordPoolDayPrice
|
||||
{
|
||||
Start = price.Start,
|
||||
End = price.End,
|
||||
Price = PriceCorrection(price.Price.Value)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return recalculatedPrice;
|
||||
}
|
||||
|
||||
internal static double PriceCorrection(double mwPrice)
|
||||
{
|
||||
var kwPrice = mwPrice / ConversionConsts.MegawattToKilowattDivisor;
|
||||
var kwhPrice = kwPrice * ConversionConsts.VatRate;
|
||||
var cntPrice = kwhPrice * ConversionConsts.EuroToCentsMultiplier;
|
||||
|
||||
return Math.Round(cntPrice, ConversionConsts.PriceDecimalPlaces);
|
||||
}
|
||||
|
||||
internal static int GetTimeQuarterIndex(DateTime date)
|
||||
{
|
||||
var relativeHour = (date.Hour + 1) % 24;
|
||||
var totalMinutes = (relativeHour * 60) + date.Minute;
|
||||
|
||||
return totalMinutes / 15;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user