Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests - Expand single-statement guards and loops into braced blocks - Realign wrapped method arguments, chained calls and continuations - Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty` - Flatten the boiler config expression and reindent the remaining touched files
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
||||
@@ -23,24 +27,24 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) :
|
||||
}
|
||||
|
||||
var eligible = prices.Prices
|
||||
.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();
|
||||
.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();
|
||||
.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();
|
||||
|
||||
return ranked;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
#region
|
||||
|
||||
using NordPool.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface ICheapestIntervalsFinder
|
||||
{
|
||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
|
||||
double priceCap, DateTime deadline);
|
||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices,
|
||||
int numberOfIntervals,
|
||||
double priceCap,
|
||||
DateTime deadline);
|
||||
|
||||
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface INordPoolEntityService
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using NordPool.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
public interface INordPoolPriceService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using NordPool.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager.Models;
|
||||
|
||||
public record EntityUpdateContext
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger)
|
||||
@@ -35,16 +39,16 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
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);
|
||||
}
|
||||
});
|
||||
{
|
||||
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);
|
||||
}
|
||||
@@ -54,14 +58,15 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await Task.WhenAll(
|
||||
ResetLastUpdateTimeAsync(),
|
||||
ResetCurrentPriceAsync(),
|
||||
ResetTodayPricesAsync(),
|
||||
ResetTomorrowPricesAsync(),
|
||||
ResetTodayTomorrowPricesAsync(),
|
||||
ResetCheapestIntervalsAsync(),
|
||||
ResetFetchPricesButtonAsync()
|
||||
).ConfigureAwait(false);
|
||||
ResetLastUpdateTimeAsync(),
|
||||
ResetCurrentPriceAsync(),
|
||||
ResetTodayPricesAsync(),
|
||||
ResetTomorrowPricesAsync(),
|
||||
ResetTodayTomorrowPricesAsync(),
|
||||
ResetCheapestIntervalsAsync(),
|
||||
ResetFetchPricesButtonAsync()
|
||||
)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||
@@ -79,8 +84,8 @@ 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",
|
||||
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
||||
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||
}
|
||||
|
||||
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
|
||||
@@ -88,8 +93,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
|
||||
cheapestCount, ctx.IsNowCheap);
|
||||
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
|
||||
cheapestCount, ctx.IsNowCheap);
|
||||
}
|
||||
|
||||
var updateTasks = new[]
|
||||
@@ -117,6 +122,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up NordPool entities");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -124,87 +130,101 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
private async Task ResetLastUpdateTimeAsync()
|
||||
{
|
||||
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(LastUpdateTimeEntityId, new
|
||||
{
|
||||
friendly_name = "NordPool last update time"
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
intervals = Array.Empty<CheapestIntervalResult>(),
|
||||
configured_hours = 0.0,
|
||||
configured_interval_count = 0,
|
||||
configured_price_cap = 0.0,
|
||||
configured_ready_by = string.Empty,
|
||||
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);
|
||||
{
|
||||
friendly_name = "NordPool fetch prices"
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
|
||||
@@ -215,71 +235,82 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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)
|
||||
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);
|
||||
{
|
||||
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);
|
||||
{
|
||||
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)
|
||||
@@ -321,9 +352,9 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
return
|
||||
[
|
||||
.. todayList
|
||||
.Concat(tomorrowList)
|
||||
.Where(p => p is { Start: not null })
|
||||
.OrderBy(p => p.Start!.Value)
|
||||
.Concat(tomorrowList)
|
||||
.Where(p => p is { Start: not null })
|
||||
.OrderBy(p => p.Start!.Value)
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Reactive.Concurrency;
|
||||
using BoilerMonitor.Models;
|
||||
@@ -12,6 +14,8 @@ using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -67,7 +71,10 @@ public class NordPoolInit
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync();
|
||||
if (_options.CleanupEntitiesOnStartup)
|
||||
{
|
||||
await _entityService.CleanupEntitiesAsync();
|
||||
}
|
||||
|
||||
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
|
||||
await _entityService.ResetEntitiesAsync();
|
||||
@@ -78,6 +85,7 @@ public class NordPoolInit
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing NordPool prices");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -123,7 +131,7 @@ public class NordPoolInit
|
||||
}
|
||||
|
||||
await _priceService.FetchPricesAsync(FetchPricesForDateAsync);
|
||||
|
||||
|
||||
_priceService.UpdateCurrentPrice();
|
||||
|
||||
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
|
||||
@@ -139,13 +147,13 @@ public class NordPoolInit
|
||||
private async Task<NordPoolPrice> FetchPricesForDateAsync(DateOnly date)
|
||||
{
|
||||
var nordPoolPricesDto = await _services.Nordpool.GetPricesForDateAsync(
|
||||
new NordpoolGetPricesForDateParameters
|
||||
{
|
||||
Areas = "LT",
|
||||
ConfigEntry = NordPoolConsts.ConfigEntry,
|
||||
Currency = "EUR",
|
||||
Date = date
|
||||
});
|
||||
new NordpoolGetPricesForDateParameters
|
||||
{
|
||||
Areas = "LT",
|
||||
ConfigEntry = NordPoolConsts.ConfigEntry,
|
||||
Currency = "EUR",
|
||||
Date = date
|
||||
});
|
||||
|
||||
return _priceService.ParseAndAdjust(nordPoolPricesDto);
|
||||
}
|
||||
@@ -153,12 +161,13 @@ public class NordPoolInit
|
||||
private void SubscribeToFetchPricesButton()
|
||||
{
|
||||
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
|
||||
|
||||
button.StateChanges()
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update");
|
||||
Task.Run(UpdatePricesAsync);
|
||||
});
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update");
|
||||
Task.Run(UpdatePricesAsync);
|
||||
});
|
||||
}
|
||||
|
||||
private void UpdateCheapestIntervals(BoilerConfig config)
|
||||
@@ -198,9 +207,9 @@ public class NordPoolInit
|
||||
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
|
||||
|
||||
var nextCheapInterval = CheapestIntervals?
|
||||
.Where(i => i.Start > currentDateTime)
|
||||
.OrderBy(i => i.Start)
|
||||
.FirstOrDefault();
|
||||
.Where(i => i.Start > currentDateTime)
|
||||
.OrderBy(i => i.Start)
|
||||
.FirstOrDefault();
|
||||
|
||||
var context = new EntityUpdateContext
|
||||
{
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using AutoMapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -6,6 +8,8 @@ using NordPool.Models.Dtos;
|
||||
using NordPoolManager.Interface;
|
||||
using NordPoolManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
/// <summary>
|
||||
@@ -61,7 +65,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
|
||||
if (DayQuartersIndex == index) return;
|
||||
if (DayQuartersIndex == index)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
|
||||
{
|
||||
@@ -91,13 +98,25 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
|
||||
public bool ShouldFetchNewPrices(DateOnly date)
|
||||
{
|
||||
if (!LastFetchedDate.HasValue) return true;
|
||||
if (!LastFetchedDate.HasValue)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (LastFetchedDate.Value < date) return true;
|
||||
if (LastFetchedDate.Value < date)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true;
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false;
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var currentHour = DateTime.Now.Hour;
|
||||
|
||||
@@ -107,8 +126,8 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
public void RollOverPrices(DateOnly date)
|
||||
{
|
||||
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 }
|
||||
? TomorrowNordPoolPrice
|
||||
: new NordPoolPrice();
|
||||
? TomorrowNordPoolPrice
|
||||
: new NordPoolPrice();
|
||||
|
||||
TomorrowNordPoolPrice = null;
|
||||
|
||||
@@ -125,13 +144,16 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
|
||||
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
||||
{
|
||||
if (!element.HasValue) return new NordPoolPrice();
|
||||
if (!element.HasValue)
|
||||
{
|
||||
return new NordPoolPrice();
|
||||
}
|
||||
|
||||
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
||||
|
||||
return priceResult != null
|
||||
? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult)
|
||||
: new NordPoolPrice();
|
||||
? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult)
|
||||
: new NordPoolPrice();
|
||||
}
|
||||
|
||||
internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
|
||||
@@ -141,11 +163,17 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
Prices = new List<NordPoolDayPrice>()
|
||||
};
|
||||
|
||||
if (todayNordPoolPrice.Prices is null) return recalculatedPrice;
|
||||
if (todayNordPoolPrice.Prices is null)
|
||||
{
|
||||
return recalculatedPrice;
|
||||
}
|
||||
|
||||
foreach (var price in todayNordPoolPrice.Prices)
|
||||
{
|
||||
if (price.Price is null) continue;
|
||||
if (price.Price is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
recalculatedPrice.Prices.Add(new NordPoolDayPrice
|
||||
{
|
||||
@@ -179,6 +207,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
|
||||
{
|
||||
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await fetchPricesForDate(date);
|
||||
@@ -193,8 +222,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date);
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public static class NordPoolServiceRegistration
|
||||
@@ -9,13 +13,14 @@ public static class NordPoolServiceRegistration
|
||||
public static IServiceCollection AddNordPool(this IServiceCollection services)
|
||||
{
|
||||
services
|
||||
.AddNetDaemonApp<NordPoolInit>()
|
||||
.AddNetDaemonApp<NordPoolInit>()
|
||||
|
||||
// Singleton is safe: NordPoolPriceService holds no IHaContext/generated
|
||||
// entity dependency. The HA price fetch call lives in NordPoolInit.
|
||||
.AddSingleton<INordPoolPriceService, NordPoolPriceService>()
|
||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||
.AddTransient<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>();
|
||||
.AddSingleton<INordPoolPriceService, NordPoolPriceService>()
|
||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||
.AddTransient<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user