From 77458383d1a83ede291d7282a1e5e807e25acc38 Mon Sep 17 00:00:00 2001 From: ExQz Date: Tue, 1 Dec 2026 11:59:31 +0200 Subject: [PATCH] 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 --- AGENTS.md | 6 +- BatteryMonitor.Manager/BatteryMonitorInit.cs | 2 + .../BatteryNotificationService.cs | 2 + .../BatterySensorDiscoveryService.cs | 8 ++ .../BoilerMonitorEntityServiceTests.cs | 2 +- BoilerMonitor.Manager/BoilerConfigReader.cs | 4 + BoilerMonitor.Manager/BoilerControlService.cs | 6 + .../BoilerMonitorEntityService.cs | 15 +++ BoilerMonitor.Manager/BoilerMonitorInit.cs | 28 +++- BoilerMonitor.Manager/WaterReadyService.cs | 13 ++ HomeAssistant.Entities/EntityManager.cs | 4 + HomeAssistant.Server/MqttRecreateApp.cs | 6 + LeakMonitor.Manager/LeakMonitorInit.cs | 6 + .../LeakNotificationService.cs | 4 + .../LightMonitorInitTests.cs | 8 ++ LightMonitor.Manager/LightControlService.cs | 6 + LightMonitor.Manager/LightMonitorInit.cs | 18 ++- LightMonitor.Manager/PresenceService.cs | 7 +- NordPool.Manager.Tests/NordPoolInitTests.cs | 7 +- .../NordPoolPriceServiceTests.cs | 61 ++++++++- NordPool.Manager/CheapestIntervalsFinder.cs | 3 +- .../Interface/INordPoolPriceService.cs | 8 +- NordPool.Manager/NordPoolEntityService.cs | 4 + NordPool.Manager/NordPoolInit.cs | 26 +++- NordPool.Manager/NordPoolPriceService.cs | 127 +++++++++--------- .../NordPoolServiceRegistration.cs | 6 +- NordPool.Models/CompactNordPoolDayPrice.cs | 10 ++ .../PowerLimitEnforcementService.cs | 4 + .../PowerMonitorEntityService.cs | 4 + PowerMonitor.Manager/PowerMonitorInit.cs | 14 ++ .../PowerSensorDiscoveryService.cs | 2 + .../ExhaustFanControlService.cs | 2 + .../ShowerDetectionService.cs | 2 + ShowerMonitor.Manager/ShowerMonitorInit.cs | 4 + 34 files changed, 336 insertions(+), 93 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 011c9b4..26ac7d0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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` diff --git a/BatteryMonitor.Manager/BatteryMonitorInit.cs b/BatteryMonitor.Manager/BatteryMonitorInit.cs index a72d22b..56fcec8 100644 --- a/BatteryMonitor.Manager/BatteryMonitorInit.cs +++ b/BatteryMonitor.Manager/BatteryMonitorInit.cs @@ -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) { diff --git a/BatteryMonitor.Manager/BatteryNotificationService.cs b/BatteryMonitor.Manager/BatteryNotificationService.cs index 45deb32..4566dc2 100644 --- a/BatteryMonitor.Manager/BatteryNotificationService.cs +++ b/BatteryMonitor.Manager/BatteryNotificationService.cs @@ -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() diff --git a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs index 0a6f644..85b5cdd 100644 --- a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs +++ b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs @@ -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; } diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs index 50635fd..49bfa5a 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs @@ -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(); diff --git a/BoilerMonitor.Manager/BoilerConfigReader.cs b/BoilerMonitor.Manager/BoilerConfigReader.cs index 16f17f4..99c0a94 100644 --- a/BoilerMonitor.Manager/BoilerConfigReader.cs +++ b/BoilerMonitor.Manager/BoilerConfigReader.cs @@ -33,15 +33,19 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger 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 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; } diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs index 3f06b52..53acd84 100644 --- a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -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) { diff --git a/BoilerMonitor.Manager/BoilerMonitorInit.cs b/BoilerMonitor.Manager/BoilerMonitorInit.cs index 04bf3ff..64e89b6 100644 --- a/BoilerMonitor.Manager/BoilerMonitorInit.cs +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -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 { diff --git a/BoilerMonitor.Manager/WaterReadyService.cs b/BoilerMonitor.Manager/WaterReadyService.cs index 6090fb6..829e91c 100644 --- a/BoilerMonitor.Manager/WaterReadyService.cs +++ b/BoilerMonitor.Manager/WaterReadyService.cs @@ -41,8 +41,11 @@ public sealed class WaterReadyService(ILogger 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 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 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 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 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); + } } } diff --git a/HomeAssistant.Entities/EntityManager.cs b/HomeAssistant.Entities/EntityManager.cs index a7e60df..baa435c 100644 --- a/HomeAssistant.Entities/EntityManager.cs +++ b/HomeAssistant.Entities/EntityManager.cs @@ -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)..]; diff --git a/HomeAssistant.Server/MqttRecreateApp.cs b/HomeAssistant.Server/MqttRecreateApp.cs index dbd468b..b6c4683 100644 --- a/HomeAssistant.Server/MqttRecreateApp.cs +++ b/HomeAssistant.Server/MqttRecreateApp.cs @@ -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 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; diff --git a/LeakMonitor.Manager/LeakMonitorInit.cs b/LeakMonitor.Manager/LeakMonitorInit.cs index b2a5946..cba4f9b 100644 --- a/LeakMonitor.Manager/LeakMonitorInit.cs +++ b/LeakMonitor.Manager/LeakMonitorInit.cs @@ -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); } diff --git a/LeakMonitor.Manager/LeakNotificationService.cs b/LeakMonitor.Manager/LeakNotificationService.cs index 5a64bb6..c39c65e 100644 --- a/LeakMonitor.Manager/LeakNotificationService.cs +++ b/LeakMonitor.Manager/LeakNotificationService.cs @@ -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) diff --git a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs index 67c7692..fea24db 100644 --- a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs +++ b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs @@ -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] diff --git a/LightMonitor.Manager/LightControlService.cs b/LightMonitor.Manager/LightControlService.cs index 03a3378..289204b 100644 --- a/LightMonitor.Manager/LightControlService.cs +++ b/LightMonitor.Manager/LightControlService.cs @@ -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); + } } } \ No newline at end of file diff --git a/LightMonitor.Manager/LightMonitorInit.cs b/LightMonitor.Manager/LightMonitorInit.cs index 100dc4e..d259f85 100644 --- a/LightMonitor.Manager/LightMonitorInit.cs +++ b/LightMonitor.Manager/LightMonitorInit.cs @@ -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(); } diff --git a/LightMonitor.Manager/PresenceService.cs b/LightMonitor.Manager/PresenceService.cs index 31dabd0..1022f82 100644 --- a/LightMonitor.Manager/PresenceService.cs +++ b/LightMonitor.Manager/PresenceService.cs @@ -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); diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index bc9208b..e6da622 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -23,6 +23,7 @@ public class NordPoolInitTests private readonly Mock> _loggerMock; private readonly Mock _priceServiceMock; private readonly Mock _schedulerMock; + private readonly Services _services; public NordPoolInitTests() { @@ -35,8 +36,11 @@ public class NordPoolInitTests _boilerConfigProviderMock = new Mock(); _haContextMock = new Mock(); _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>>())) + .Returns(Task.CompletedTask); _entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny())) .Returns(Task.CompletedTask); _entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); @@ -70,6 +74,7 @@ public class NordPoolInitTests return new NordPoolInit( _entities, + _services, _haContextMock.Object, _loggerMock.Object, _priceServiceMock.Object, diff --git a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs index 2047344..ebdd8cf 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -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(); - var haContextMock = new Mock(); var loggerMock = new Mock>(); - 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(); + + Task 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) diff --git a/NordPool.Manager/CheapestIntervalsFinder.cs b/NordPool.Manager/CheapestIntervalsFinder.cs index 54e5a00..f205cdf 100644 --- a/NordPool.Manager/CheapestIntervalsFinder.cs +++ b/NordPool.Manager/CheapestIntervalsFinder.cs @@ -6,8 +6,7 @@ namespace NordPoolManager; public class CheapestIntervalsFinder(ILogger logger) : ICheapestIntervalsFinder { - public IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, - double priceCap, DateTime deadline) + public IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline) { if (prices.Prices is not { Count: > 0 }) { diff --git a/NordPool.Manager/Interface/INordPoolPriceService.cs b/NordPool.Manager/Interface/INordPoolPriceService.cs index 2fa1df3..97195d1 100644 --- a/NordPool.Manager/Interface/INordPoolPriceService.cs +++ b/NordPool.Manager/Interface/INordPoolPriceService.cs @@ -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> 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); } \ No newline at end of file diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index 641d478..916383c 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -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[] { diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index bfb3001..133c2f8 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -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 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 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) { diff --git a/NordPool.Manager/NordPoolPriceService.cs b/NordPool.Manager/NordPoolPriceService.cs index b63de5b..bc573fb 100644 --- a/NordPool.Manager/NordPoolPriceService.cs +++ b/NordPool.Manager/NordPoolPriceService.cs @@ -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 logger) - : INordPoolPriceService +/// +/// Holds NordPool price state and performs price math. Must stay free of +/// IHaContext/generated entity dependencies so it can be a singleton. +/// Fetching prices from Home Assistant lives in . +/// +public class NordPoolPriceService(IMapper mapper, ILogger 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> 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= 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 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 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(); @@ -207,4 +175,29 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger FetchPricesForDateWithRetryAsync(DateOnly date, Func> 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(); + } } \ No newline at end of file diff --git a/NordPool.Manager/NordPoolServiceRegistration.cs b/NordPool.Manager/NordPoolServiceRegistration.cs index da6d66b..1814adb 100644 --- a/NordPool.Manager/NordPoolServiceRegistration.cs +++ b/NordPool.Manager/NordPoolServiceRegistration.cs @@ -10,9 +10,11 @@ public static class NordPoolServiceRegistration { services .AddNetDaemonApp() - .AddScoped() + // Singleton is safe: NordPoolPriceService holds no IHaContext/generated + // entity dependency. The HA price fetch call lives in NordPoolInit. + .AddSingleton() .AddTransient() - .AddSingleton() + .AddTransient() .AddScoped(); return services; diff --git a/NordPool.Models/CompactNordPoolDayPrice.cs b/NordPool.Models/CompactNordPoolDayPrice.cs index 7047aa9..57f96e1 100644 --- a/NordPool.Models/CompactNordPoolDayPrice.cs +++ b/NordPool.Models/CompactNordPoolDayPrice.cs @@ -46,17 +46,23 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter {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); diff --git a/PowerMonitor.Manager/PowerMonitorEntityService.cs b/PowerMonitor.Manager/PowerMonitorEntityService.cs index e16183a..3bbded1 100644 --- a/PowerMonitor.Manager/PowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/PowerMonitorEntityService.cs @@ -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); } diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index a17b325..1cdf6b1 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -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; } diff --git a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs index 2027375..354057b 100644 --- a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs +++ b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs @@ -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; } diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs index 8eafb8f..1c7866a 100644 --- a/ShowerMonitor.Manager/ExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -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; diff --git a/ShowerMonitor.Manager/ShowerDetectionService.cs b/ShowerMonitor.Manager/ShowerDetectionService.cs index 86774ef..c67164a 100644 --- a/ShowerMonitor.Manager/ShowerDetectionService.cs +++ b/ShowerMonitor.Manager/ShowerDetectionService.cs @@ -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; diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs index 7271817..a4def7b 100644 --- a/ShowerMonitor.Manager/ShowerMonitorInit.cs +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -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) {