295 lines
11 KiB
C#
295 lines
11 KiB
C#
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);
|
|
}
|
|
}
|