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