Add braces to single-statement guards and refactor NordPool price fetching

- Expand inline guard, return and logger blocks across the monitor services, init classes and tests
- Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton
- Record the NordPool and boiler service lifetimes in AGENTS.md
- Drop the unused persisted-state argument from the boiler test data helper
This commit is contained in:
2026-12-01 11:59:31 +02:00
parent 24729ee267
commit 77458383d1
34 changed files with 336 additions and 93 deletions
+4 -2
View File
@@ -88,14 +88,16 @@ collections) must be registered **scoped or transient**, never singleton,
or app load fails with:
`Cannot resolve scoped service … from root provider`.
Verified-livable registrations (do not regress these to singleton):
Verified-livable registrations (do not regress these lifetimes; re-check
scoped dependencies if changing one):
- `Boiler`: `IBoilerMonitorEntityService` transient,
`IBoilerControlService`/`IBoilerRunTimeTracker`/`IWaterReadyService`
singleton (no HA dep), `IBoilerConfigReader` scoped (registered directly
in `program.cs`, the only monitor service outside its
`*ServiceRegistration.cs`).
- `NordPool`: `INordPoolEntityService` transient, `INordPoolPriceService`
scoped, `INordPoolBoilerConfigProvider` scoped,
singleton (pure state/math, no HA dep — HA fetch call lives in
`NordPoolInit`), `INordPoolBoilerConfigProvider` scoped,
`ICheapestIntervalsFinder` singleton (no HA dep).
- `Power`: `IPowerMonitorEntityService` + `IPowerNotificationService`
transient, `IPowerSensorDiscoveryService` scoped. `IOtherPowerCalculationService`
@@ -56,8 +56,10 @@ public sealed class BatteryMonitorInit
CheckAndNotify();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
_options.BatteryThresholdPercent);
}
}
catch (Exception ex)
{
@@ -27,9 +27,11 @@ public sealed class BatteryNotificationService(
});
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Sent low battery notification for {Count} device(s)",
lowBatteryDevices.Count);
}
}
public void DismissNotification()
@@ -24,9 +24,11 @@ public sealed class BatterySensorDiscoveryService(
.ToList();
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Battery check: found {Count} sensors below {Threshold}%",
lowBatterySensors.Count, thresholdPercent);
}
return lowBatterySensors!;
}
@@ -34,7 +36,9 @@ public sealed class BatterySensorDiscoveryService(
internal static bool IsBatterySensor(Entity entity)
{
if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class");
@@ -56,8 +60,10 @@ public sealed class BatterySensorDiscoveryService(
if (state is null or "unavailable" or "unknown")
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
state ?? "null");
}
return null;
}
@@ -65,8 +71,10 @@ public sealed class BatterySensorDiscoveryService(
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
state);
}
return null;
}
@@ -105,7 +105,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
{
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
"7200", "3", "ON", "OFF"));
"7200", "3", "ON"));
var result = CreateSut().ReadPersistedState();
@@ -33,15 +33,19 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
if (!string.IsNullOrEmpty(readyByState) &&
TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
{
deadline = DateTime.Today.Add(readyByTime);
}
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
intervalCount, priceCap, skipPriceCap, deadline);
}
var config = new BoilerConfig
{
@@ -23,9 +23,11 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
{
case (true, false):
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
currentSwitchState);
}
return BoilerAction.TurnOn;
@@ -34,17 +36,21 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
var reason = GetTurnOffReason(waterReady, effectiveBudgetExhausted);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason,
currentSwitchState);
}
return BoilerAction.TurnOff;
}
default:
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
}
return BoilerAction.NoChange;
}
@@ -45,7 +45,10 @@ public sealed class BoilerMonitorEntityService(
try
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
}
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
@@ -144,9 +147,12 @@ public sealed class BoilerMonitorEntityService(
!TryParseEntityInt(sessionCountState, out var sessionCount))
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
}
return null;
}
@@ -159,10 +165,12 @@ public sealed class BoilerMonitorEntityService(
};
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
persisted.BudgetOverrideState);
}
return persisted;
}
@@ -200,7 +208,10 @@ public sealed class BoilerMonitorEntityService(
DateTimeStyles.RoundtripKind, out var parsed))
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
}
return parsed;
}
}
@@ -500,7 +511,9 @@ public sealed class BoilerMonitorEntityService(
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
}
catch (Exception ex)
{
@@ -514,7 +527,9 @@ public sealed class BoilerMonitorEntityService(
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
}
catch (Exception ex)
{
+25 -3
View File
@@ -134,9 +134,11 @@ public sealed class BoilerMonitorInit
await _entityService.ResetTransientEntitiesAsync();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation(
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
}
}
else
{
@@ -167,8 +169,10 @@ public sealed class BoilerMonitorInit
var nextPollTime = now.Add(delayUntilNext);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
DefaultPollIntervalSeconds, nextPollTime);
}
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
() => _ = PollAndUpdateAsync());
@@ -290,7 +294,10 @@ public sealed class BoilerMonitorInit
try
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
}
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
}
catch (Exception e)
@@ -320,7 +327,10 @@ public sealed class BoilerMonitorInit
try
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
}
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
}
catch (Exception e)
@@ -428,12 +438,16 @@ public sealed class BoilerMonitorInit
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
if (autoManagementEnabled)
{
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
}
else if (boilerAction is not BoilerAction.NoChange)
{
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation(
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
boilerAction);
{
_logger.LogInformation("Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", boilerAction);
}
}
var context = new BoilerMonitorUpdateContext
{
@@ -452,9 +466,11 @@ public sealed class BoilerMonitorInit
await _entityService.UpdateEntitiesAsync(context);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
}
}
catch (Exception ex)
{
@@ -491,7 +507,9 @@ public sealed class BoilerMonitorInit
if (!string.IsNullOrWhiteSpace(pollIntervalState)
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
&& pollIntervalValue > 0)
{
pollInterval = (int)pollIntervalValue;
}
double? heatingThreshold = null;
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
@@ -499,7 +517,9 @@ public sealed class BoilerMonitorInit
if (!string.IsNullOrWhiteSpace(thresholdState)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
&& thresholdValue > 0)
{
heatingThreshold = thresholdValue;
}
return new BoilerMonitorConfig
{
@@ -526,6 +546,7 @@ public sealed class BoilerMonitorInit
try
{
if (attributes.TryGetValue(attributeName, out var value))
{
return value switch
{
bool b => b,
@@ -536,6 +557,7 @@ public sealed class BoilerMonitorInit
bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed,
_ => false
};
}
}
catch
{
@@ -41,8 +41,11 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (IsWithinCooldownPeriod())
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
_waterReadySince);
}
return true;
}
}
@@ -56,8 +59,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (!_hasObservedHeating)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
powerWatts.Value);
}
return false;
}
@@ -73,10 +78,12 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
powerWatts.Value);
}
return false;
}
@@ -84,9 +91,11 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
_waterReadySince ??= timeProvider.GetUtcNow();
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
_consecutiveBelowThresholdCount);
}
return true;
}
@@ -135,15 +144,19 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (waterReadySince < todayMidnightUtc)
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
waterReadySince);
}
return;
}
_waterReadySince = waterReadySince;
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
}
}
}
+4
View File
@@ -23,7 +23,9 @@ public class EntityManager(
public async Task CreateEntityAsync(EntityCreateModel createModel)
{
if (createModel.EntityId != null)
{
await entityManager.CreateAsync(createModel.EntityId, createModel.Options, createModel.AdditionalConfig);
}
}
public async Task SetEntityState(string entityId, string state)
@@ -66,9 +68,11 @@ public class EntityManager(
{
var separatorIndex = entityId.IndexOf('.');
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
{
throw new ArgumentException(
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
nameof(entityId));
}
var domain = entityId[..separatorIndex];
var objectId = entityId[(separatorIndex + 1)..];
+6
View File
@@ -69,7 +69,9 @@ public sealed class MqttRecreateApp
}).ConfigureAwait(false);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId);
}
var button = new Entity(_haContext, RecreateButtonEntityId);
button.StateChanges()
@@ -202,17 +204,21 @@ public sealed class MqttRecreateApp
var state = _haContext.GetState(NordPoolPriceEntityId);
if (state?.Attributes is IDictionary<string, object> attributes &&
attributes.TryGetValue("unit_of_measurement", out var value))
{
return value switch
{
string s => s,
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
_ => null
};
}
}
catch (Exception ex)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId);
}
}
return null;
+6
View File
@@ -45,8 +45,10 @@ public sealed class LeakMonitorInit
foreach (var sensorEntityId in _options.SensorEntityIds) SubscribeToLeakSensor(sensorEntityId);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)",
_options.SensorEntityIds.Length);
}
}
catch (Exception ex)
{
@@ -74,7 +76,9 @@ public sealed class LeakMonitorInit
});
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId);
}
}
internal void HandleStateChange(string sensorEntityId, StateChange change)
@@ -90,7 +94,9 @@ public sealed class LeakMonitorInit
else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase))
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId);
}
_notificationService.DismissLeakAlert(sensorEntityId);
}
@@ -22,9 +22,11 @@ public sealed class LeakNotificationService(
if (IsWithinCooldown(sensorEntityId))
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Skipping leak notification for {SensorId} -- within cooldown period",
sensorEntityId);
}
return;
}
@@ -50,7 +52,9 @@ public sealed class LeakNotificationService(
data: new { notification_id = notificationId });
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId);
}
}
private void SendMobilePushNotification(string message)
@@ -26,11 +26,15 @@ public class LightMonitorInitTests
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
{
if (subscriptionException is null)
{
_haContextMock.Setup(x => x.StateAllChanges())
.Returns(_stateChangesSubject);
}
else
{
_haContextMock.Setup(x => x.StateAllChanges())
.Throws(subscriptionException);
}
return new LightMonitorInit(
_haContextMock.Object,
@@ -53,9 +57,13 @@ public class LightMonitorInitTests
private void VerifyTurnOn(bool shouldTurnOn)
{
if (shouldTurnOn)
{
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
}
else
{
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
}
[Theory]
@@ -22,7 +22,9 @@ public sealed class LightControlService(
if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState);
}
return;
}
@@ -32,7 +34,9 @@ public sealed class LightControlService(
if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase))
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId);
}
return;
}
@@ -40,6 +44,8 @@ public sealed class LightControlService(
haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId));
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId);
}
}
}
+16 -2
View File
@@ -41,8 +41,10 @@ public sealed class LightMonitorInit
SubscribeToPersonStateChanges();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons",
_options.PersonEntityIds.Length);
}
}
catch (Exception ex)
{
@@ -61,12 +63,17 @@ public sealed class LightMonitorInit
try
{
if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon,
StringComparison.OrdinalIgnoreCase)) return;
StringComparison.OrdinalIgnoreCase))
{
return;
}
if (IsRecoveryTransition(e.Old?.State))
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State);
}
return;
}
@@ -93,20 +100,27 @@ public sealed class LightMonitorInit
try
{
if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState,
StringComparison.OrdinalIgnoreCase)) return;
StringComparison.OrdinalIgnoreCase))
{
return;
}
if (IsRecoveryTransition(e.Old?.State))
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring",
personEntityId, e.Old?.State);
}
return;
}
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Person {EntityId} arrived home, checking if it is dark",
personEntityId);
}
_lightControlService.TurnOnLight();
}
+6 -1
View File
@@ -20,10 +20,15 @@ public sealed class PresenceService(
var state = haContext.GetState(personEntityId);
if (state?.State is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState)
{
continue;
}
if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState,
StringComparison.OrdinalIgnoreCase)) continue;
StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Person {EntityId} is home", personEntityId);
+6 -1
View File
@@ -23,6 +23,7 @@ public class NordPoolInitTests
private readonly Mock<ILogger<NordPoolInit>> _loggerMock;
private readonly Mock<INordPoolPriceService> _priceServiceMock;
private readonly Mock<IScheduler> _schedulerMock;
private readonly Services _services;
public NordPoolInitTests()
{
@@ -35,8 +36,11 @@ public class NordPoolInitTests
_boilerConfigProviderMock = new Mock<INordPoolBoilerConfigProvider>();
_haContextMock = new Mock<IHaContext>();
_entities = new Entities(_haContextMock.Object);
_services = new Services(_haContextMock.Object);
_priceServiceMock.Setup(p => p.FetchPricesAsync()).Returns(Task.CompletedTask);
_priceServiceMock
.Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>()))
.Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny<string>())).Returns(Task.CompletedTask);
@@ -70,6 +74,7 @@ public class NordPoolInitTests
return new NordPoolInit(
_entities,
_services,
_haContextMock.Object,
_loggerMock.Object,
_priceServiceMock.Object,
@@ -2,10 +2,8 @@
using System.Text.Json;
using AutoMapper;
using FluentAssertions;
using HomeAssistantGenerated;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NordPool.Models;
using NordPool.Models.Dtos;
using NordPoolManager;
@@ -20,11 +18,9 @@ public class NordPoolPriceServiceTests
public NordPoolPriceServiceTests()
{
_mapperMock = new Mock<IMapper>();
var haContextMock = new Mock<IHaContext>();
var loggerMock = new Mock<ILogger<NordPoolPriceService>>();
var services = new Services(haContextMock.Object);
_sut = new NordPoolPriceService(services, _mapperMock.Object, loggerMock.Object);
_sut = new NordPoolPriceService(_mapperMock.Object, loggerMock.Object);
}
#region GetTimeQuarterIndex
@@ -680,6 +676,61 @@ public class NordPoolPriceServiceTests
#endregion
#region FetchPricesAsync
[Fact]
public async Task FetchPricesAsync_WhenNoCachedPrices_ShouldFetchTodayAndTomorrowViaDelegate()
{
// Arrange
var requestedDates = new List<DateOnly>();
Task<NordPoolPrice> Fetch(DateOnly date)
{
requestedDates.Add(date);
return Task.FromResult(CreatePrices(1.5));
}
// Act
await _sut.FetchPricesAsync(Fetch);
// Assert
requestedDates.Should().HaveCount(2);
requestedDates[1].Should().Be(requestedDates[0].AddDays(1));
_sut.TodayNordPoolPrice.Should().NotBeNull();
_sut.TomorrowNordPoolPrice.Should().NotBeNull();
_sut.TodayNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.TomorrowNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.LastFetchedDate.Should().Be(requestedDates[0]);
_sut.LastUpdatedDate.Should().NotBeNull();
}
[Fact]
public async Task FetchPricesAsync_WhenCachedPricesAlreadyPresent_ShouldNotCallDelegate()
{
// Arrange
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var todayCet = DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone));
_sut.TodayNordPoolPrice = CreatePrices(1.0);
_sut.TomorrowNordPoolPrice = CreatePrices(2.0);
_sut.LastFetchedDate = todayCet;
var delegateCalled = false;
// Act
await _sut.FetchPricesAsync(_ =>
{
delegateCalled = true;
return Task.FromResult(CreatePrices(3.0));
});
// Assert
delegateCalled.Should().BeFalse();
_sut.TodayNordPoolPrice!.Prices![0].Price.Should().Be(1.0);
_sut.TomorrowNordPoolPrice!.Prices![0].Price.Should().Be(2.0);
}
#endregion
#region ShouldFetchNewPrices
private static NordPoolPrice CreatePrices(params double?[] values)
+1 -2
View File
@@ -6,8 +6,7 @@ namespace NordPoolManager;
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
{
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
double priceCap, DateTime deadline)
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
{
if (prices.Prices is not { Count: > 0 })
{
@@ -1,3 +1,4 @@
using System.Text.Json;
using NordPool.Models;
namespace NordPoolManager.Interface;
@@ -11,9 +12,10 @@ public interface INordPoolPriceService
DateTime? LastUpdatedDate { get; }
DateOnly? LastFetchedDate { get; }
Task FetchPricesAsync();
Task FetchPricesAsync(Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate);
NordPoolPrice ParseAndAdjust(JsonElement? element);
void UpdateCurrentPrice();
double GetCurrentPrice();
bool ShouldFetchNewPrices(DateOnly today);
void RollOverPrices(DateOnly today);
bool ShouldFetchNewPrices(DateOnly dateOnly);
void RollOverPrices(DateOnly date);
}
@@ -77,16 +77,20 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
{
logger.LogWarning(
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
}
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
cheapestCount, ctx.IsNowCheap);
}
var updateTasks = new[]
{
+22 -4
View File
@@ -25,10 +25,12 @@ public class NordPoolInit
private readonly NordPoolOptions _options;
private readonly INordPoolPriceService _priceService;
private readonly IScheduler _scheduler;
private readonly Services _services;
private readonly TimeProvider _timeProvider;
public NordPoolInit(
Entities entities,
Services services,
IHaContext haContext,
ILogger<NordPoolInit> logger,
INordPoolPriceService priceService,
@@ -44,6 +46,7 @@ public class NordPoolInit
_priceService = priceService;
_entityService = entityService;
_scheduler = scheduler;
_services = services;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_boilerConfigProvider = boilerConfigProvider;
_options = options.Value;
@@ -115,10 +118,12 @@ public class NordPoolInit
var today = DateOnly.FromDateTime(nowCet);
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
{
_priceService.RollOverPrices(today);
}
if (_priceService.ShouldFetchNewPrices(today)) await _priceService.FetchPricesAsync();
await _priceService.FetchPricesAsync(FetchPricesForDateAsync);
_priceService.UpdateCurrentPrice();
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
@@ -131,6 +136,20 @@ 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
});
return _priceService.ParseAndAdjust(nordPoolPricesDto);
}
private void SubscribeToFetchPricesButton()
{
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
@@ -157,8 +176,7 @@ public class NordPoolInit
return;
}
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice,
effectiveIntervalCount, effectivePriceCap, config.Deadline);
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline);
}
catch (Exception ex)
{
+60 -67
View File
@@ -1,6 +1,5 @@
using System.Text.Json;
using AutoMapper;
using HomeAssistantGenerated;
using Microsoft.Extensions.Logging;
using NordPool.Models;
using NordPool.Models.Dtos;
@@ -9,11 +8,13 @@ using NordPoolManager.Models.Consts;
namespace NordPoolManager;
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger)
: INordPoolPriceService
/// <summary>
/// Holds NordPool price state and performs price math. Must stay free of
/// <c>IHaContext</c>/generated entity dependencies so it can be a singleton.
/// Fetching prices from Home Assistant lives in <see cref="NordPoolInit" />.
/// </summary>
public class NordPoolPriceService(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; }
@@ -21,31 +22,34 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
public DateTime? LastUpdatedDate { get; private set; }
public DateOnly? LastFetchedDate { get; internal set; }
public async Task FetchPricesAsync()
public async Task FetchPricesAsync(Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
{
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
var today = DateOnly.FromDateTime(nowCet);
var dateNow = DateOnly.FromDateTime(nowCet);
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today))
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow))
{
if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
{
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", dateNow);
}
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow, fetchPricesForDate);
}
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) &&
ShouldFetchNewPrices(today.AddDays(1)))
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow.AddDays(1)))
{
if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
{
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", dateNow.AddDays(1));
}
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow.AddDays(1), fetchPricesForDate);
}
LastUpdatedDate = DateTime.UtcNow;
LastFetchedDate = today;
LastFetchedDate = dateNow;
}
public void UpdateCurrentPrice()
@@ -53,8 +57,9 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
var index = GetTimeQuarterIndex(DateTime.UtcNow);
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index,
TodayNordPoolPrice?.Prices?.Count ?? 0);
{
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
}
if (DayQuartersIndex == index) return;
@@ -63,14 +68,17 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
var price = TodayNordPoolPrice.Prices[index].Price;
if (price.HasValue)
{
CurrentPrice = price.Value;
}
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);
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;
@@ -81,11 +89,11 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
return CurrentPrice;
}
public bool ShouldFetchNewPrices(DateOnly today)
public bool ShouldFetchNewPrices(DateOnly date)
{
if (!LastFetchedDate.HasValue) return true;
if (LastFetchedDate.Value < today) return true;
if (LastFetchedDate.Value < date) return true;
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true;
@@ -96,7 +104,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
return currentHour >= 13;
}
public void RollOverPrices(DateOnly today)
public void RollOverPrices(DateOnly date)
{
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 }
? TomorrowNordPoolPrice
@@ -105,59 +113,19 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
TomorrowNordPoolPrice = null;
DayQuartersIndex = -1;
LastFetchedDate = today;
LastFetchedDate = date;
}
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, string label)
public NordPoolPrice ParseAndAdjust(JsonElement? element)
{
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
try
{
return await GetNordPoolPriceAsync(date);
}
catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts)
{
var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1));
logger.LogWarning(ex,
"Attempt {Attempt}/{MaxAttempts} to fetch {Label} prices for {Date} failed. Retrying in {Delay}",
attempt, NordPoolConsts.MaxFetchRetryAttempts, label, date, delay);
var todayNordPoolPrice = ParseNordPoolResult(element);
await Task.Delay(delay);
}
catch (Exception ex)
{
logger.LogError(ex,
"Failed to fetch {Label} prices for {Date} on attempt {Attempt} with unexpected error", label, date,
attempt);
break;
}
logger.LogWarning(
"All {MaxAttempts} attempts to fetch {Label} prices for {Date} exhausted; returning empty prices",
NordPoolConsts.MaxFetchRetryAttempts, label, date);
return new NordPoolPrice();
}
private 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);
return AdjustedNordPoolPrice(todayNordPoolPrice);
}
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
{
if (element == null) return new NordPoolPrice();
if (!element.HasValue) return new NordPoolPrice();
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
@@ -207,4 +175,29 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
return totalMinutes / NordPoolConsts.MinutesPerInterval;
}
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);
}
catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts)
{
var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1));
logger.LogWarning(ex, "Attempt {Attempt}/{MaxAttempts} to fetch prices for {Date} failed. Retrying in {Delay}", attempt, NordPoolConsts.MaxFetchRetryAttempts, date, delay);
await Task.Delay(delay);
}
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);
return new NordPoolPrice();
}
}
@@ -10,9 +10,11 @@ public static class NordPoolServiceRegistration
{
services
.AddNetDaemonApp<NordPoolInit>()
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
// Singleton is safe: NordPoolPriceService holds no IHaContext/generated
// entity dependency. The HA price fetch call lives in NordPoolInit.
.AddSingleton<INordPoolPriceService, NordPoolPriceService>()
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
.AddTransient<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>();
return services;
@@ -46,17 +46,23 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNo
if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("Expected start of array.");
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
{
throw new JsonException("Expected number for Start at position 0.");
}
var start = reader.GetInt64();
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
{
throw new JsonException("Expected number for End at position 1.");
}
var end = reader.GetInt64();
if (!reader.Read() || (reader.TokenType != JsonTokenType.Number && reader.TokenType != JsonTokenType.Null))
{
throw new JsonException("Expected number or null for Price at position 2.");
}
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
@@ -74,9 +80,13 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNo
writer.WriteNumberValue(value.End);
if (value.Price.HasValue)
{
writer.WriteNumberValue(value.Price.Value);
}
else
{
writer.WriteNullValue();
}
writer.WriteEndArray();
}
@@ -93,9 +93,11 @@ public sealed class PowerLimitEnforcementService(
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping",
currentPowerWatts, _options.PowerLimitWatts);
}
return;
}
@@ -122,9 +124,11 @@ public sealed class PowerLimitEnforcementService(
}
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors",
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
}
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
@@ -49,7 +49,9 @@ public sealed class PowerMonitorEntityService(
try
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
}
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
@@ -73,7 +75,9 @@ public sealed class PowerMonitorEntityService(
try
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
}
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
+14
View File
@@ -99,7 +99,9 @@ public sealed class PowerMonitorInit
await _entityService.CreateDeviceEntitiesAsync(sensors);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count);
}
await PollAndUpdateAsync();
}
@@ -140,7 +142,9 @@ public sealed class PowerMonitorInit
});
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
}
}
private void SubscribeToRediscoverButton()
@@ -190,14 +194,18 @@ public sealed class PowerMonitorInit
{
await _entityService.CreateDeviceEntitiesAsync(added);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
}
}
if (removed.Count > 0) await RemoreDevicePriceEntities(removed);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)",
newSensors.Count, added.Count, removed.Count);
}
}
catch (Exception ex)
{
@@ -211,7 +219,9 @@ public sealed class PowerMonitorInit
await _entityService.RemoveDeviceEntitiesAsync(removedNames);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
}
}
private async Task PollAndUpdateAsync()
@@ -288,10 +298,12 @@ public sealed class PowerMonitorInit
_enforcementService.EnforceLimit(calculation.TotalPowerWatts);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count,
effectivePrice);
}
}
catch (Exception ex)
{
@@ -312,7 +324,9 @@ public sealed class PowerMonitorInit
if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) return price;
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
}
return 0;
}
@@ -53,9 +53,11 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
_currentDeviceSensors = powerSensors;
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation(
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
}
return powerSensors;
}
@@ -55,7 +55,9 @@ public sealed class ExhaustFanControlService(
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
{
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
}
}
_fanTurnedOnByUs = false;
@@ -140,7 +140,9 @@ public sealed class ShowerDetectionService(
if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow
&& humidity >= _options.PeakHumidityThreshold
&& differential >= _options.MinDifferentialHumidity)
{
return ShowerState.Active;
}
var showerAbandoned = rate < 0 && differential < _options.MinDifferentialHumidity;
if (!showerAbandoned) return ShowerState.Suspected;
@@ -155,8 +155,10 @@ public sealed class ShowerMonitorInit
if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})",
bathroomHumidity, mainHomeHumidity);
}
return;
}
@@ -179,8 +181,10 @@ public sealed class ShowerMonitorInit
await _entityService.UpdateEntitiesAsync(context);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}",
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state);
}
}
catch (Exception ex)
{