feat: migrate boiler control implementation to BoilerMonitor namespace and add budget handling logic

This commit is contained in:
Marius
2026-03-24 15:29:59 +02:00
parent c4015277a3
commit 11c2574235
61 changed files with 3250 additions and 728 deletions
-36
View File
@@ -1,36 +0,0 @@
using Microsoft.Extensions.Logging;
using NordPoolManager.Interface;
using NordPoolManager.Models.Enums;
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;
}
}
@@ -6,8 +6,6 @@ namespace NordPoolManager;
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
{
private const string SwitchOnState = "on";
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
{
if (prices.Prices is not { Count: > 0 })
@@ -54,14 +52,4 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) :
{
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 < NordPoolConsts.WaterReadyPowerThresholdWatts;
}
}
@@ -1,8 +0,0 @@
using NordPoolManager.Models.Enums;
namespace NordPoolManager.Interface;
public interface IBoilerControlService
{
BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState);
}
@@ -7,6 +7,4 @@ 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);
}
-9
View File
@@ -1,9 +0,0 @@
namespace NordPoolManager.Models;
public class BoilerConfig
{
public int IntervalCount { get; set; }
public double PriceCap { get; set; }
public DateTime Deadline { get; set; }
public bool SkipPriceCap { get; set; }
}
@@ -1,7 +0,0 @@
namespace NordPoolManager.Models.Consts;
public static class PriceConsts
{
public const int MaxDailyIntervals = 96;
public const int IntervalsPerHour = 4;
}
@@ -19,7 +19,4 @@ public record EntityUpdateContext
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; }
}
@@ -1,8 +0,0 @@
namespace NordPoolManager.Models.Enums;
public enum BoilerAction
{
NoChange,
TurnOn,
TurnOff
}
@@ -0,0 +1,11 @@
namespace NordPoolManager.Models;
public sealed class NordPoolOptions
{
public const string SectionName = "NordPool";
/// <summary>
/// When true, removes existing NordPool MQTT entities before recreating them on app startup.
/// </summary>
public bool CleanupEntitiesOnStartup { get; init; } = true;
}
+3
View File
@@ -14,12 +14,15 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.2" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
</ItemGroup>
</Project>
+22 -70
View File
@@ -11,24 +11,19 @@ namespace NordPoolManager;
public sealed 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,
NordPoolConsts.CurrentPriceEntityId,
TodayPricesEntityId,
TomorrowPricesEntityId,
TodayTomorrowPricesEntityId,
CheapestIntervalsEntityId,
BoilerWaterReadyEntityId,
BoilerSkipPriceCapEntityId
CheapestIntervalsEntityId
];
public async Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default)
@@ -65,9 +60,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
ResetTodayPricesAsync(),
ResetTomorrowPricesAsync(),
ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync(),
ResetBoilerWaterReadyAsync(),
ResetBoilerSkipPriceCapAsync()
ResetCheapestIntervalsAsync()
).ConfigureAwait(false);
logger.LogInformation("All NordPool entity states reset to defaults");
@@ -84,8 +77,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
private async Task ResetCurrentPriceAsync()
{
await SetEntityStateSafe(CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
await SetEntityAttributesSafe(CurrentPriceEntityId, new
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{
unit_of_measurement = (string?)null,
device_class = "monetary",
@@ -150,24 +143,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
}).ConfigureAwait(false);
}
private async Task ResetBoilerWaterReadyAsync()
{
await SetEntityStateSafe(BoilerWaterReadyEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(BoilerWaterReadyEntityId, new
{
boiler_switch_state = "unknown",
boiler_power_watts = 0.0,
power_threshold_watts = NordPoolConsts.WaterReadyPowerThresholdWatts,
friendly_name = "Boiler water ready",
last_updated = (string?)null
}).ConfigureAwait(false);
}
private async Task ResetBoilerSkipPriceCapAsync()
{
await SetEntityStateSafe(BoilerSkipPriceCapEntityId, "OFF").ConfigureAwait(false);
}
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -182,8 +157,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
{
logger.LogWarning(
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
}
@@ -194,7 +168,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
logger.LogInformation("Updating sensor.nordpool_tomorrow_prices with {Count} prices", tomorrowPricesCount);
logger.LogInformation("Updating sensor.nordpool_today_tomorrow_prices with {Count} merged prices", mergedPrices.Count);
logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap);
logger.LogInformation("Updating sensor.nordpool_boiler_water_ready: {WaterReady} (switch={Switch}, power={Power}W)", ctx.WaterReady, ctx.BoilerSwitchState, ctx.BoilerPowerWatts);
var updateTasks = new[]
{
@@ -203,8 +176,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp),
UpdateBoilerWaterReadyAsync(ctx, timestamp)
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp)
};
await Task.WhenAll(updateTasks).ConfigureAwait(false);
@@ -219,8 +191,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp)
{
await SetEntityStateSafe(CurrentPriceEntityId, priceValue).ConfigureAwait(false);
await SetEntityAttributesSafe(CurrentPriceEntityId, new
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{
unit_of_measurement = ctx.UnitOfMeasurement,
device_class = "monetary",
@@ -286,26 +258,13 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
}).ConfigureAwait(false);
}
private async Task UpdateBoilerWaterReadyAsync(EntityUpdateContext ctx, string timestamp)
{
await SetEntityStateSafe(BoilerWaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
await SetEntityAttributesSafe(BoilerWaterReadyEntityId, new
{
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
boiler_power_watts = ctx.BoilerPowerWatts,
power_threshold_watts = NordPoolConsts.WaterReadyPowerThresholdWatts,
friendly_name = "Boiler water ready",
last_updated = timestamp
}).ConfigureAwait(false);
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var removeTasks = AllEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("NordPool entities cleaned up successfully");
@@ -319,39 +278,32 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
internal ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
{
var entries = new List<NordPoolEntity>();
var currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId;
var currentPriceDomainSeparator = currentPriceEntityId.IndexOf('.', StringComparison.Ordinal);
var currentPriceDomain = currentPriceEntityId[..currentPriceDomainSeparator];
var currentPriceObjectId = currentPriceEntityId[(currentPriceDomainSeparator + 1)..];
entries.AddRange([
return
[
new NordPoolEntity("sensor", "nordpool_last_update_time", "NordPool last update time"),
new NordPoolEntity("sensor", "nordpool_current_price", "NordPool current price")
new NordPoolEntity(currentPriceDomain, currentPriceObjectId, "NordPool current price")
{
Options = new EntityCreationOptions
{
UniqueId = CurrentPriceEntityId,
UniqueId = currentPriceEntityId,
Name = "NordPool current price"
},
AdditionalConfig = new
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("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;
new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals")
];
}
private static List<NordPoolDayPrice> MergeTodayTomorrowPrices(NordPoolPrice? today, NordPoolPrice? tomorrow)
+46 -183
View File
@@ -1,14 +1,14 @@
using System.Globalization;
using System.Reactive.Concurrency;
using BoilerMonitor.Models;
using HomeAssistantGenerated;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using Microsoft.Extensions.Options;
using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler;
using NordPool.Models;
using NordPoolManager.Interface;
using NordPoolManager.Models;
using NordPoolManager.Models.Consts;
using static NordPoolManager.Models.Enums.BoilerAction;
namespace NordPoolManager;
@@ -19,46 +19,33 @@ public class NordPoolInit : INordPoolInit
private readonly INordPoolPriceService _priceService;
private readonly INordPoolEntityService _entityService;
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly IBoilerControlService _boilerControlService;
private readonly IBoilerConfigReader _boilerConfigReader;
private readonly IScheduler _scheduler;
private readonly IHaContext _haContext;
private readonly NordPoolOptions _options;
private InputNumberEntity BoilerDailyHoursEntity { get; }
private InputNumberEntity BoilerPriceCapEntity { get; }
private SwitchEntity BoilerSkipPriceCapEntity { get; }
private InputDatetimeEntity BoilerReadyByEntity { get; }
private SwitchEntity BoilerSwitchEntity { get; }
private NumericSensorEntity BoilerPowerEntity { get; }
private string? UnitOfMeasurement { get; }
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
private bool _lastWaterReady;
public NordPoolInit(
Entities entities,
IHaContext haContext,
ILogger<NordPoolInit> logger,
INordPoolPriceService priceService,
INordPoolEntityService entityService,
IScheduler scheduler,
ICheapestIntervalsFinder cheapestIntervalsFinder,
IBoilerControlService boilerControlService)
IBoilerConfigReader boilerConfigReader,
IOptions<NordPoolOptions> options)
{
_logger = logger;
_haContext = haContext;
_priceService = priceService;
_entityService = entityService;
_scheduler = scheduler;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_boilerControlService = boilerControlService;
_boilerConfigReader = boilerConfigReader;
_options = options.Value;
var nordPoolPriceSensor = entities.Sensor.NordpoolPrice;
UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh";
BoilerDailyHoursEntity = entities.InputNumber.BoilerDailyHours;
BoilerPriceCapEntity = entities.InputNumber.BoilerPriceCap;
BoilerSkipPriceCapEntity = new SwitchEntity(_haContext, "switch.nordpool_boiler_skip_price_cap");
BoilerReadyByEntity = entities.InputDatetime.BoilerReadyBy;
BoilerSwitchEntity = entities.Switch.Sonoff1002230e32;
BoilerPowerEntity = entities.Sensor.Sonoff1002230e32Power;
_ = InitializeAndScheduleAsync();
}
@@ -69,8 +56,6 @@ public class NordPoolInit : INordPoolInit
{
await InitializeAsync();
SchedulePeriodicUpdates();
ScheduleEndOfDayReminder();
SubscribeToSkipPriceCapChanges();
}
catch (Exception ex)
{
@@ -78,60 +63,6 @@ public class NordPoolInit : INordPoolInit
}
}
private void ScheduleEndOfDayReminder()
{
_scheduler.ScheduleCron("0 20 * * *", CheckSkipPriceCapReminderAsync);
}
private void CheckSkipPriceCapReminderAsync()
{
try
{
var switchState = BoilerSkipPriceCapEntity.State;
if (string.Equals(switchState, "on", StringComparison.OrdinalIgnoreCase))
{
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
{
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
title = "Boiler reminder"
});
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error checking skip price cap reminder");
}
}
private void SubscribeToSkipPriceCapChanges()
{
BoilerSkipPriceCapEntity.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State)
{
return;
}
_logger.LogInformation("Skip price cap switch changed, recalculating cheapest intervals");
_ = RecalculateOnConfigChangeAsync();
});
}
private async Task RecalculateOnConfigChangeAsync()
{
try
{
var result = UpdateCheapestIntervals();
await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recalculating on skip price cap switch change");
}
}
public async Task InitializeAsync()
{
try
@@ -140,6 +71,15 @@ public class NordPoolInit : INordPoolInit
await _priceService.FetchPricesAsync();
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
else
{
_logger.LogInformation("Skipping NordPool entity cleanup on startup (CleanupEntitiesOnStartup is false)");
}
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
await _entityService.ResetEntitiesAsync();
@@ -154,8 +94,8 @@ public class NordPoolInit : INordPoolInit
_logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval");
}
var result = UpdateCheapestIntervals();
await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap);
var (_, boilerConfig) = UpdateCheapestIntervals();
await UpdateEntitiesAsync(boilerConfig);
_logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
}
@@ -220,8 +160,8 @@ public class NordPoolInit : INordPoolInit
_priceService.UpdateCurrentPrice();
var result = UpdateCheapestIntervals();
await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap);
var (_, boilerConfig) = UpdateCheapestIntervals();
await UpdateEntitiesAsync(boilerConfig);
_logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
}
@@ -236,11 +176,11 @@ public class NordPoolInit : INordPoolInit
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private CheapestIntervalsUpdateResult UpdateCheapestIntervals()
private (CheapestIntervalsUpdateResult Result, BoilerConfig Config) UpdateCheapestIntervals()
{
var boilerConfig = ReadBoilerConfig();
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
var effectiveIntervalCount = boilerConfig.SkipPriceCap ? PriceConsts.MaxDailyIntervals : boilerConfig.IntervalCount;
var config = _boilerConfigReader.ReadConfig();
var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap;
var effectiveIntervalCount = config.SkipPriceCap ? NordPoolConsts.MaxDailyIntervals : config.IntervalCount;
try
{
@@ -248,18 +188,18 @@ public class NordPoolInit : INordPoolInit
{
_logger.LogDebug("No today prices available, skipping cheapest intervals calculation");
CheapestIntervals = [];
return new CheapestIntervalsUpdateResult
return (new CheapestIntervalsUpdateResult
{
IntervalCount = boilerConfig.IntervalCount,
PriceCap = boilerConfig.PriceCap,
SkipPriceCap = boilerConfig.SkipPriceCap
};
IntervalCount = config.IntervalCount,
PriceCap = config.PriceCap,
SkipPriceCap = config.SkipPriceCap
}, config);
}
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline);
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline);
_logger.LogInformation("Cheapest intervals updated: {Count} intervals (config: {Hours}h / {Intervals} intervals, cap: {Cap}, skipPriceCap: {Skip}, deadline: {Deadline})",
CheapestIntervals.Count, boilerConfig.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, boilerConfig.SkipPriceCap, boilerConfig.Deadline);
CheapestIntervals.Count, config.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, config.SkipPriceCap, config.Deadline);
}
catch (Exception ex)
{
@@ -267,65 +207,24 @@ public class NordPoolInit : INordPoolInit
CheapestIntervals = [];
}
return new CheapestIntervalsUpdateResult
return (new CheapestIntervalsUpdateResult
{
IntervalCount = boilerConfig.IntervalCount,
PriceCap = boilerConfig.PriceCap,
SkipPriceCap = boilerConfig.SkipPriceCap
};
IntervalCount = config.IntervalCount,
PriceCap = config.PriceCap,
SkipPriceCap = config.SkipPriceCap
}, config);
}
private BoilerConfig ReadBoilerConfig()
{
var boilerConfig = new BoilerConfig();
var dailyHours = BoilerDailyHoursEntity.State ?? 1.0;
var intervalCount = (int)(dailyHours * PriceConsts.IntervalsPerHour);
if (intervalCount <= 0)
{
intervalCount = PriceConsts.IntervalsPerHour;
}
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;
var skipPriceCapState = BoilerSkipPriceCapEntity.State;
boilerConfig.SkipPriceCap = string.Equals(skipPriceCapState, "on", StringComparison.OrdinalIgnoreCase);
_logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.SkipPriceCap, boilerConfig.Deadline);
return boilerConfig;
}
private async Task UpdateEntitiesAsync(int configuredIntervalCount, double configuredPriceCap, bool skipPriceCap)
private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig)
{
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 configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour;
var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
var isNowCheap = CheapestIntervals != null &&
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
var nextCheapInterval = CheapestIntervals?
@@ -333,39 +232,6 @@ public class NordPoolInit : INordPoolInit
.OrderBy(i => i.Start)
.FirstOrDefault();
var boilerSwitchState = BoilerSwitchEntity.State;
var boilerPowerWatts = BoilerPowerEntity.State;
var waterReady = _cheapestIntervalsFinder.IsWaterReady(boilerSwitchState, boilerPowerWatts);
if (!_lastWaterReady && waterReady)
{
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
{
message = "Hot water is ready.",
title = "Boiler"
});
_logger.LogInformation("Water ready notification sent to mobile_app_marius_phone");
}
_lastWaterReady = waterReady;
var boilerAction = _boilerControlService.DetermineAction(isNowCheap, waterReady, boilerSwitchState);
switch (boilerAction)
{
case TurnOn:
BoilerSwitchEntity.TurnOn();
break;
case TurnOff:
BoilerSwitchEntity.TurnOff();
break;
case NoChange:
break;
default:
throw new ArgumentOutOfRangeException();
}
var context = new EntityUpdateContext
{
CurrentPrice = _priceService.CurrentPrice,
@@ -377,15 +243,12 @@ public class NordPoolInit : INordPoolInit
TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice,
CheapestIntervals = CheapestIntervals,
ConfiguredHours = configuredHours,
ConfiguredIntervalCount = configuredIntervalCount,
ConfiguredPriceCap = configuredPriceCap,
SkipPriceCap = skipPriceCap,
ConfiguredIntervalCount = boilerConfig.IntervalCount,
ConfiguredPriceCap = boilerConfig.PriceCap,
SkipPriceCap = boilerConfig.SkipPriceCap,
ConfiguredReadyBy = configuredReadyBy,
IsNowCheap = isNowCheap,
NextCheapIntervalStart = nextCheapInterval?.Start,
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts
NextCheapIntervalStart = nextCheapInterval?.Start
};
await _entityService.UpdateEntitiesAsync(context);