diff --git a/AGENTS.md b/AGENTS.md index 40b830a..011c9b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,12 +43,15 @@ before editing; it only records things that are easy to get wrong. `*ServiceRegistration.cs`, reference the projects from `HomeAssistant.Server`, and wire `Add` + `Configure<*Options>` in `program.cs`. **NordPool breaks the naming convention**: its extension is - `AddNordPool`, not `AddNordPoolMonitor`. + `AddNordPool`, not `AddNordPoolMonitor`. `AddNordPool` and `AddPowerMonitor` + take no `IConfiguration` parameter — neither registration reads options + (PowerMonitor checks `Enabled` inside `PowerMonitorInit` instead). - `*ServiceRegistration.cs` honors an `Enabled` flag in the options and no-ops (skips `AddNetDaemonApp`) when disabled — for every monitor - **except NordPool**, which has no `Enabled` option and always registers. - `PowerMonitor` ships disabled by default in `appsettings.json`; all - others ship enabled. + **except NordPool** (no `Enabled` option, always registers) and + **PowerMonitor** (registers unconditionally; `PowerMonitorInit` reads + `Enabled` itself). `PowerMonitor` ships disabled by default in + `appsettings.json`; all others ship enabled. - `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated` code (entity metadata sourced from `HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`). diff --git a/BatteryMonitor.Manager/BatteryMonitorInit.cs b/BatteryMonitor.Manager/BatteryMonitorInit.cs index 08013b7..7b0e386 100644 --- a/BatteryMonitor.Manager/BatteryMonitorInit.cs +++ b/BatteryMonitor.Manager/BatteryMonitorInit.cs @@ -9,7 +9,7 @@ using BatteryMonitorManager.Models; namespace BatteryMonitorManager; [NetDaemonApp] -public sealed class BatteryMonitorInit : IBatteryMonitorInit +public sealed class BatteryMonitorInit { private readonly ILogger _logger; private readonly IScheduler _scheduler; @@ -46,7 +46,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit } } - public async Task InitializeAsync() + private async Task InitializeAsync() { try { @@ -54,7 +54,10 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit CheckAndNotify(); - _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent); + } } catch (Exception ex) { @@ -81,7 +84,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit _logger.LogInformation("Scheduled daily battery check at 08:00"); } - internal void CheckAndNotify() + private void CheckAndNotify() { var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent); diff --git a/BatteryMonitor.Manager/BatteryNotificationService.cs b/BatteryMonitor.Manager/BatteryNotificationService.cs index 558255e..ca42119 100644 --- a/BatteryMonitor.Manager/BatteryNotificationService.cs +++ b/BatteryMonitor.Manager/BatteryNotificationService.cs @@ -6,19 +6,10 @@ using BatteryMonitorManager.Interface; namespace BatteryMonitorManager; -public sealed class BatteryNotificationService : IBatteryNotificationService +public sealed class BatteryNotificationService( + IHaContext haContext, + ILogger logger) : IBatteryNotificationService { - private readonly IHaContext _haContext; - private readonly ILogger _logger; - - public BatteryNotificationService( - IHaContext haContext, - ILogger logger) - { - _haContext = haContext; - _logger = logger; - } - public void NotifyLowBattery(IReadOnlyList lowBatteryDevices) { if (lowBatteryDevices.Count == 0) @@ -28,7 +19,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService var message = BuildNotificationMessage(lowBatteryDevices); - _haContext.CallService( + haContext.CallService( BatteryMonitorConsts.PersistentNotificationDomain, BatteryMonitorConsts.PersistentNotificationCreateService, data: new @@ -38,14 +29,17 @@ public sealed class BatteryNotificationService : IBatteryNotificationService notification_id = BatteryMonitorConsts.NotificationId }); - _logger.LogInformation( - "Sent low battery notification for {Count} device(s)", - lowBatteryDevices.Count); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation( + "Sent low battery notification for {Count} device(s)", + lowBatteryDevices.Count); + } } public void DismissNotification() { - _haContext.CallService( + haContext.CallService( BatteryMonitorConsts.PersistentNotificationDomain, BatteryMonitorConsts.PersistentNotificationDismissService, data: new @@ -53,7 +47,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService notification_id = BatteryMonitorConsts.NotificationId }); - _logger.LogDebug("Dismissed low battery notification"); + logger.LogDebug("Dismissed low battery notification"); } internal static string BuildNotificationMessage(IReadOnlyList devices) diff --git a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs index 9d1553c..8819e9a 100644 --- a/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs +++ b/BatteryMonitor.Manager/BatterySensorDiscoveryService.cs @@ -8,22 +8,13 @@ using BatteryMonitorManager.Interface; namespace BatteryMonitorManager; -public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryService +public sealed class BatterySensorDiscoveryService( + IHaContext haContext, + ILogger logger) : IBatterySensorDiscoveryService { - private readonly IHaContext _haContext; - private readonly ILogger _logger; - - public BatterySensorDiscoveryService( - IHaContext haContext, - ILogger logger) - { - _haContext = haContext; - _logger = logger; - } - public IReadOnlyList DiscoverLowBatterySensors(int thresholdPercent) { - var allEntities = _haContext.GetAllEntities(); + var allEntities = haContext.GetAllEntities(); var lowBatterySensors = allEntities .Where(IsBatterySensor) @@ -32,9 +23,12 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi .Where(info => info is not null) .ToList(); - _logger.LogInformation( - "Battery check: found {Count} sensors below {Threshold}%", - lowBatterySensors.Count, thresholdPercent); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation( + "Battery check: found {Count} sensors below {Threshold}%", + lowBatterySensors.Count, thresholdPercent); + } return lowBatterySensors!; } @@ -65,13 +59,21 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi if (state is null or "unavailable" or "unknown") { - _logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null"); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null"); + } + return null; } if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel)) { - _logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state); + } + return null; } @@ -91,7 +93,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi }; } - internal static string? GetJsonStringProperty(JsonElement? element, string propertyName) + private static string? GetJsonStringProperty(JsonElement? element, string propertyName) { if (element is null) { diff --git a/BatteryMonitor.Manager/Interface/IBatteryMonitorInit.cs b/BatteryMonitor.Manager/Interface/IBatteryMonitorInit.cs deleted file mode 100644 index 14678e4..0000000 --- a/BatteryMonitor.Manager/Interface/IBatteryMonitorInit.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace BatteryMonitorManager.Interface; - -public interface IBatteryMonitorInit -{ - Task InitializeAsync(); -} diff --git a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs index 66ab3ca..3072422 100644 --- a/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs +++ b/BatteryMonitor.Manager/Models/BatteryMonitorOptions.cs @@ -6,7 +6,7 @@ public sealed class BatteryMonitorOptions { public const string SectionName = "BatteryMonitor"; - public bool Enabled { get; set; } + public bool Enabled { get; init; } - public int BatteryThresholdPercent { get; set; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent; + public int BatteryThresholdPercent { get; init; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent; } diff --git a/BoilerMonitor.Manager/BoilerConfigReader.cs b/BoilerMonitor.Manager/BoilerConfigReader.cs index d8b2aea..da40315 100644 --- a/BoilerMonitor.Manager/BoilerConfigReader.cs +++ b/BoilerMonitor.Manager/BoilerConfigReader.cs @@ -37,7 +37,10 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger logger) : var effectiveBudgetExhausted = budgetExhausted && !budgetOverride; var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted; - if (shouldBeOn && !isCurrentlyOn) + switch (shouldBeOn, isCurrentlyOn) { - logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState); + 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; + return BoilerAction.TurnOn; + + case (false, true): + { + 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; } - - if (!shouldBeOn && isCurrentlyOn) - { - var reason = GetTurnOffReason(waterReady, isNowCheap, effectiveBudgetExhausted); - - logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState); - - return BoilerAction.TurnOff; - } - - logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", - currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted); - - return BoilerAction.NoChange; } - private static string GetTurnOffReason(bool waterReady, bool isNowCheap, bool effectiveBudgetExhausted) + private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted) { if (waterReady) { return "water is already ready"; } - if (effectiveBudgetExhausted) - { - return "daily budget is exhausted"; - } - - return "not in a cheap interval"; + return effectiveBudgetExhausted + ? "daily budget is exhausted" + : "not in a cheap interval"; } } diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs index 163c0a1..19d3040 100644 --- a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -51,7 +51,10 @@ public sealed class BoilerMonitorEntityService( { try { - logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId); + } await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); } catch (Exception ex) @@ -148,8 +151,11 @@ public sealed class BoilerMonitorEntityService( if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount)) { - logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", - runtimeState, sessionCountState); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", + runtimeState, sessionCountState); + } return null; } @@ -161,8 +167,11 @@ public sealed class BoilerMonitorEntityService( BudgetOverrideState = budgetOverrideState }; - logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}", - persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState); + 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 +209,7 @@ public sealed class BoilerMonitorEntityService( return tryParseEntityInt; } - private ICollection GetAllEntities() + private static ICollection GetAllEntities() { var device = CreateDeviceBlock(); @@ -468,7 +477,10 @@ public sealed class BoilerMonitorEntityService( DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed)) { - logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed); + } return parsed; } } @@ -485,7 +497,10 @@ public sealed class BoilerMonitorEntityService( try { await entityManager.SetEntityState(entityId, state).ConfigureAwait(false); - logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state); + } } catch (Exception ex) { @@ -498,7 +513,10 @@ public sealed class BoilerMonitorEntityService( try { await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false); - logger.LogDebug("Successfully set attributes for {EntityId}", entityId); + 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 66edab9..efbbee6 100644 --- a/BoilerMonitor.Manager/BoilerMonitorInit.cs +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -16,7 +16,7 @@ using static BoilerMonitor.Models.BoilerMonitorConsts; namespace BoilerMonitorManager; [NetDaemonApp] -public sealed class BoilerMonitorInit : IBoilerMonitorInit +public sealed class BoilerMonitorInit { private readonly ILogger _logger; private readonly IHaContext _haContext; @@ -110,7 +110,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit } } - public async Task InitializeAsync() + private async Task InitializeAsync() { try { @@ -131,7 +131,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit if (persisted is not null) { - _tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount); + _tracker.RestoreFromSnapshot(); if (persistedCooldown.HasValue) { @@ -139,8 +139,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit } await _entityService.ResetTransientEntitiesAsync(); - _logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", - persisted.AccumulatedRunTime, persisted.SessionCount); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", + persisted.AccumulatedRunTime, persisted.SessionCount); + } } else { @@ -162,11 +165,6 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit } } - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) - { - await _entityService.CleanupEntitiesAsync(cancellationToken); - } - private void SchedulePeriodicPolling() { var now = DateTime.Now; @@ -175,7 +173,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext); var nextPollTime = now.Add(delayUntilNext); - _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime); + 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()); } @@ -206,15 +207,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit try { var switchState = _haContext.GetState(SkipPriceCapEntityId); - if (string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) { - _haContext.CallService("notify", "mobile_app_marius_phone", null, new - { - message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", - title = "Boiler reminder" - }); - _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); + return; } + + _haContext.CallService("notify", "mobile_app_marius_phone", null, new + { + message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", + title = "Boiler reminder" + }); + _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); } catch (Exception ex) { @@ -308,7 +311,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit { try { - _logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state); + 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) @@ -337,7 +343,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit { try { - _logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state); + 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) @@ -386,9 +395,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!); var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State; var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value; - var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value); - - _tracker.RecordPollResult(isHeating, pollInterval); + _tracker.RecordPollResult(); if (isHeating) { @@ -397,7 +404,6 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); - var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval"); var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State; var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase); @@ -431,7 +437,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit } var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 - ? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0 + ? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0 : 0.0; var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan; @@ -454,9 +460,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit } else if (boilerAction is not BoilerAction.NoChange) { - _logger.LogInformation( - "Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", - boilerAction); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation( + "Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", + boilerAction); + } } var context = new BoilerMonitorUpdateContext @@ -467,19 +476,19 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit BudgetExhausted = budgetExhausted, SessionCount = snapshot.SessionCount, BudgetHours = dailyHours, - IsCurrentlyHeating = isHeating, WaterReady = waterReady, BoilerSwitchState = boilerSwitchState, BoilerPowerWatts = boilerPowerWatts, CooldownSince = _waterReadyService.WaterReadySince, - IsNowCheap = effectiveIsNowCheap, - NextCheapIntervalStart = nextCheapInterval }; await _entityService.UpdateEntitiesAsync(context); - _logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", - boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage); + 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) { @@ -553,14 +562,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit private static bool ReadAttributeBool(EntityState? entityState, string attributeName) { - if (entityState?.Attributes is null) + if (entityState?.Attributes is not IDictionary attributes) { return false; } try { - if (entityState.Attributes is IDictionary attributes && attributes.TryGetValue(attributeName, out var value)) + if (attributes.TryGetValue(attributeName, out var value)) { return value switch { diff --git a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs index 1f70a79..f53311f 100644 --- a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs +++ b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs @@ -5,7 +5,7 @@ namespace BoilerMonitorManager; public class BoilerRunTimeTracker : IBoilerRunTimeTracker { - public void RecordPollResult(bool isHeating, TimeSpan pollInterval) + public void RecordPollResult() { } @@ -15,8 +15,7 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker return new RunTimeSnapshot { AccumulatedRunTime = TimeSpan.Zero, - SessionCount = 0, - IsInSession = false + SessionCount = 0 }; } @@ -25,7 +24,7 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker } - public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount) + public void RestoreFromSnapshot() { } diff --git a/BoilerMonitor.Manager/Interface/IBoilerMonitorInit.cs b/BoilerMonitor.Manager/Interface/IBoilerMonitorInit.cs deleted file mode 100644 index fc3f482..0000000 --- a/BoilerMonitor.Manager/Interface/IBoilerMonitorInit.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace BoilerMonitorManager.Interface; - -public interface IBoilerMonitorInit -{ - Task InitializeAsync(); - Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); -} diff --git a/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs index a8fdb81..4c4384a 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs @@ -4,8 +4,8 @@ namespace BoilerMonitorManager.Interface; public interface IBoilerRunTimeTracker { - void RecordPollResult(bool isHeating, TimeSpan pollInterval); + void RecordPollResult(); RunTimeSnapshot GetSnapshot(); void Reset(); - void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount); + void RestoreFromSnapshot(); } diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs index 66083ce..f055d15 100644 --- a/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs +++ b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs @@ -8,11 +8,8 @@ public record BoilerMonitorUpdateContext public required bool BudgetExhausted { get; init; } public required int SessionCount { get; init; } public required double BudgetHours { get; init; } - public required bool IsCurrentlyHeating { get; init; } public required bool WaterReady { get; init; } public required string? BoilerSwitchState { get; init; } public required double? BoilerPowerWatts { get; init; } public required DateTimeOffset? CooldownSince { get; init; } - public required bool IsNowCheap { get; init; } - public required DateTime? NextCheapIntervalStart { get; init; } } diff --git a/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs b/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs index 8ba7d84..3be74b3 100644 --- a/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs +++ b/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs @@ -4,5 +4,4 @@ public record RunTimeSnapshot { public required TimeSpan AccumulatedRunTime { get; init; } public required int SessionCount { get; init; } - public required bool IsInSession { get; init; } } diff --git a/BoilerMonitor.Manager/WaterReadyService.cs b/BoilerMonitor.Manager/WaterReadyService.cs index 138b764..c3ac4d9 100644 --- a/BoilerMonitor.Manager/WaterReadyService.cs +++ b/BoilerMonitor.Manager/WaterReadyService.cs @@ -40,7 +40,10 @@ public sealed class WaterReadyService(ILogger logger, TimePro { if (IsWithinCooldownPeriod()) { - logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince); + } return true; } } @@ -59,7 +62,10 @@ public sealed class WaterReadyService(ILogger logger, TimePro { if (!_hasObservedHeating) { - logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value); + } return false; } @@ -74,15 +80,21 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired) { - logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", - _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", + _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value); + } return false; } _waterReadySince ??= timeProvider.GetUtcNow(); - logger.LogInformation("Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", _consecutiveBelowThresholdCount); + 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; } @@ -132,13 +144,19 @@ public sealed class WaterReadyService(ILogger logger, TimePro var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero); if (waterReadySince < todayMidnightUtc) { - logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince); + } return; } _waterReadySince = waterReadySince; - logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince); + } } } diff --git a/BoilerMonitor.Models/BoilerMonitorEntity.cs b/BoilerMonitor.Models/BoilerMonitorEntity.cs index 8561efd..f36d91d 100644 --- a/BoilerMonitor.Models/BoilerMonitorEntity.cs +++ b/BoilerMonitor.Models/BoilerMonitorEntity.cs @@ -5,9 +5,9 @@ namespace BoilerMonitor.Models; public class BoilerMonitorEntity : EntityCreateModel { - public string Domain { get; set; } - public string Identifier { get; set; } - public string Name { get; set; } + private string Domain { get; } + private string Identifier { get; } + private string Name { get; } public BoilerMonitorEntity(string domain, string identifier, string name) { diff --git a/HomeAssistant.Entities/EntityManager.cs b/HomeAssistant.Entities/EntityManager.cs index e2bee8a..287d677 100644 --- a/HomeAssistant.Entities/EntityManager.cs +++ b/HomeAssistant.Entities/EntityManager.cs @@ -20,11 +20,6 @@ public class EntityManager( /// private static readonly string[] CleanupTopicSuffixes = ["state", "attributes", "availability", "set", "config"]; - public async Task CreateEntitiesAsync(ICollection entities) - { - await Task.WhenAll(entities.Select(CreateEntityAsync)); - } - public async Task CreateEntityAsync(EntityCreateModel createModel) { if (createModel.EntityId != null) diff --git a/HomeAssistant.Entities/Interfaces/IEntityManager.cs b/HomeAssistant.Entities/Interfaces/IEntityManager.cs index c958a37..d666f75 100644 --- a/HomeAssistant.Entities/Interfaces/IEntityManager.cs +++ b/HomeAssistant.Entities/Interfaces/IEntityManager.cs @@ -4,7 +4,6 @@ namespace HomeAssistant.Entities.Interfaces; public interface IEntityManager { - Task CreateEntitiesAsync(ICollection entities); Task CreateEntityAsync(EntityCreateModel createModel); Task SetEntityState(string entityId, string state); Task SetEntityAttributes(string entityId, object attributes); diff --git a/HomeAssistant.Models/EntityCreateModel.cs b/HomeAssistant.Models/EntityCreateModel.cs index e65b13c..b27a261 100644 --- a/HomeAssistant.Models/EntityCreateModel.cs +++ b/HomeAssistant.Models/EntityCreateModel.cs @@ -4,7 +4,7 @@ namespace HomeAssistant.Models; public class EntityCreateModel { - public string? EntityId { get; set; } - public EntityCreationOptions? Options { get; set; } = new(); - public object? AdditionalConfig { get; set; } = null; + public string? EntityId { get; init; } + public EntityCreationOptions? Options { get; init; } = new(); + public object? AdditionalConfig { get; init; } } \ No newline at end of file diff --git a/HomeAssistant.Server/MqttRecreateApp.cs b/HomeAssistant.Server/MqttRecreateApp.cs index 43e92f2..28eb57f 100644 --- a/HomeAssistant.Server/MqttRecreateApp.cs +++ b/HomeAssistant.Server/MqttRecreateApp.cs @@ -22,6 +22,8 @@ public sealed class MqttRecreateApp private const string NordPoolPriceEntityId = "sensor.nordpool_price"; private const string DefaultUnitOfMeasurement = "EUR/kWh"; + private static readonly string[] AppDaemonIdentifiers = ["appdaemon"]; + private readonly IHaContext _haContext; private readonly IMqttEntityManager _mqttEntityManager; private readonly IServiceProvider _serviceProvider; @@ -59,14 +61,17 @@ public sealed class MqttRecreateApp icon = "mdi:refresh", device = new { - identifiers = new[] { "appdaemon" }, + identifiers = AppDaemonIdentifiers, name = "AppDaemon", model = "AppDaemon", manufacturer = "HomeAssistant App Daemon" } }).ConfigureAwait(false); - _logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId); + } var button = new Entity(_haContext, RecreateButtonEntityId); button.StateChanges() @@ -210,7 +215,10 @@ public sealed class MqttRecreateApp } catch (Exception ex) { - _logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId); + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId); + } } return null; diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index bdd3cf0..0a39ace 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -53,9 +53,9 @@ try .AddSingleton(TimeProvider.System) .AddScoped() .Configure(context.Configuration.GetSection(NordPoolOptions.SectionName)) - .AddNordPool(context.Configuration) + .AddNordPool() .Configure(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) - .AddPowerMonitor(context.Configuration) + .AddPowerMonitor() .Configure(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) .AddBoilerMonitor(context.Configuration) .Configure(context.Configuration.GetSection(ShowerMonitorOptions.SectionName)) diff --git a/LeakMonitor.Manager/Interface/ILeakMonitorInit.cs b/LeakMonitor.Manager/Interface/ILeakMonitorInit.cs deleted file mode 100644 index 631d898..0000000 --- a/LeakMonitor.Manager/Interface/ILeakMonitorInit.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace LeakMonitorManager.Interface; - -public interface ILeakMonitorInit -{ - Task InitializeAsync(); -} diff --git a/LeakMonitor.Manager/LeakMonitorInit.cs b/LeakMonitor.Manager/LeakMonitorInit.cs index 21c959e..54b1153 100644 --- a/LeakMonitor.Manager/LeakMonitorInit.cs +++ b/LeakMonitor.Manager/LeakMonitorInit.cs @@ -10,7 +10,7 @@ using LeakMonitorManager.Models; namespace LeakMonitorManager; [NetDaemonApp] -public sealed class LeakMonitorInit : ILeakMonitorInit +public sealed class LeakMonitorInit { private readonly IHaContext _haContext; private readonly ILeakNotificationService _notificationService; @@ -31,7 +31,7 @@ public sealed class LeakMonitorInit : ILeakMonitorInit _ = InitializeAsync(); } - public Task InitializeAsync() + private Task InitializeAsync() { try { @@ -47,7 +47,10 @@ public sealed class LeakMonitorInit : ILeakMonitorInit SubscribeToLeakSensor(sensorEntityId); } - _logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)", _options.SensorEntityIds.Length); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)", _options.SensorEntityIds.Length); + } } catch (Exception ex) { @@ -74,7 +77,10 @@ public sealed class LeakMonitorInit : ILeakMonitorInit } }); - _logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId); + } } internal void HandleStateChange(string sensorEntityId, StateChange change) @@ -89,8 +95,11 @@ public sealed class LeakMonitorInit : ILeakMonitorInit } else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase)) { - _logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId); - + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId); + } + _notificationService.DismissLeakAlert(sensorEntityId); } } diff --git a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs index 0c1e693..ac59c28 100644 --- a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs +++ b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs @@ -8,7 +8,7 @@ namespace LeakMonitorManager; public static class LeakMonitorServiceRegistration { - public static IServiceCollection AddLeakMonitor(this IServiceCollection services, IConfiguration configuration) + public static void AddLeakMonitor(this IServiceCollection services, IConfiguration configuration) { var options = configuration .GetSection(LeakMonitorOptions.SectionName) @@ -16,11 +16,9 @@ public static class LeakMonitorServiceRegistration if (!options.Enabled) { - return services; + return; } services.AddNetDaemonApp().AddScoped(); - - return services; } } diff --git a/LeakMonitor.Manager/LeakNotificationService.cs b/LeakMonitor.Manager/LeakNotificationService.cs index 4ee84c0..4a14038 100644 --- a/LeakMonitor.Manager/LeakNotificationService.cs +++ b/LeakMonitor.Manager/LeakNotificationService.cs @@ -8,37 +8,30 @@ using LeakMonitorManager.Models; namespace LeakMonitorManager; -public sealed class LeakNotificationService : ILeakNotificationService +public sealed class LeakNotificationService( + IHaContext haContext, + ILogger logger, + IOptions options, + TimeProvider timeProvider) : ILeakNotificationService { - private readonly IHaContext _haContext; - private readonly ILogger _logger; - private readonly LeakMonitorOptions _options; - private readonly TimeProvider _timeProvider; + private readonly LeakMonitorOptions _options = options.Value; private readonly ConcurrentDictionary _lastNotificationTimes = new(); - public LeakNotificationService( - IHaContext haContext, - ILogger logger, - IOptions options, - TimeProvider timeProvider) - { - _haContext = haContext; - _logger = logger; - _options = options.Value; - _timeProvider = timeProvider; - } - public void SendLeakAlert(string sensorEntityId) { if (IsWithinCooldown(sensorEntityId)) { - _logger.LogDebug( - "Skipping leak notification for {SensorId} -- within cooldown period", - sensorEntityId); + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug( + "Skipping leak notification for {SensorId} -- within cooldown period", + sensorEntityId); + } + return; } - _lastNotificationTimes[sensorEntityId] = _timeProvider.GetUtcNow(); + _lastNotificationTimes[sensorEntityId] = timeProvider.GetUtcNow(); var notificationId = BuildNotificationId(sensorEntityId); var message = $"Water detected by {sensorEntityId}! Check immediately."; @@ -46,24 +39,27 @@ public sealed class LeakNotificationService : ILeakNotificationService SendMobilePushNotification(message); CreatePersistentNotification(notificationId, message); - _logger.LogWarning("Leak alert sent for sensor {SensorId}", sensorEntityId); + logger.LogWarning("Leak alert sent for sensor {SensorId}", sensorEntityId); } public void DismissLeakAlert(string sensorEntityId) { var notificationId = BuildNotificationId(sensorEntityId); - _haContext.CallService( + haContext.CallService( LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationDismissService, data: new { notification_id = notificationId }); - _logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId); + } } private void SendMobilePushNotification(string message) { - _haContext.CallService( + haContext.CallService( LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService, data: new @@ -86,7 +82,7 @@ public sealed class LeakNotificationService : ILeakNotificationService private void CreatePersistentNotification(string notificationId, string message) { - _haContext.CallService( + haContext.CallService( LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService, data: new @@ -105,7 +101,7 @@ public sealed class LeakNotificationService : ILeakNotificationService } var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes); - return _timeProvider.GetUtcNow() - lastTime < cooldown; + return timeProvider.GetUtcNow() - lastTime < cooldown; } internal static string BuildNotificationId(string sensorEntityId) diff --git a/LeakMonitor.Manager/Models/LeakMonitorOptions.cs b/LeakMonitor.Manager/Models/LeakMonitorOptions.cs index 00fb037..d73a0d2 100644 --- a/LeakMonitor.Manager/Models/LeakMonitorOptions.cs +++ b/LeakMonitor.Manager/Models/LeakMonitorOptions.cs @@ -6,9 +6,9 @@ public sealed class LeakMonitorOptions { public const string SectionName = "LeakMonitor"; - public bool Enabled { get; set; } + public bool Enabled { get; init; } - public string[] SensorEntityIds { get; set; } = []; + public string[] SensorEntityIds { get; init; } = []; - public int NotificationCooldownMinutes { get; set; } = LeakMonitorConsts.DefaultNotificationCooldownMinutes; + public int NotificationCooldownMinutes { get; init; } = LeakMonitorConsts.DefaultNotificationCooldownMinutes; } diff --git a/LeakMonitor.Models/LeakMonitorConsts.cs b/LeakMonitor.Models/LeakMonitorConsts.cs index 982a8c8..200c4ea 100644 --- a/LeakMonitor.Models/LeakMonitorConsts.cs +++ b/LeakMonitor.Models/LeakMonitorConsts.cs @@ -20,7 +20,5 @@ public static class LeakMonitorConsts public const string NotificationTitle = "Water Leak Detected!"; - public const string DismissTitle = "Water Leak Cleared"; - public const int DefaultNotificationCooldownMinutes = 5; } diff --git a/LightMonitor.Manager/Interface/ILightMonitorInit.cs b/LightMonitor.Manager/Interface/ILightMonitorInit.cs deleted file mode 100644 index badbe4d..0000000 --- a/LightMonitor.Manager/Interface/ILightMonitorInit.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace LightMonitorManager.Interface; - -public interface ILightMonitorInit -{ - Task InitializeAsync(); -} diff --git a/LightMonitor.Manager/LightControlService.cs b/LightMonitor.Manager/LightControlService.cs index f70eae0..0b95ae8 100644 --- a/LightMonitor.Manager/LightControlService.cs +++ b/LightMonitor.Manager/LightControlService.cs @@ -21,8 +21,11 @@ public sealed class LightControlService( if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) { - logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState); - + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState); + } + return; } @@ -30,13 +33,19 @@ public sealed class LightControlService( if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase)) { - logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId); - + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId); + } + return; } haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId)); - - logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId); + + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId); + } } } diff --git a/LightMonitor.Manager/LightMonitorInit.cs b/LightMonitor.Manager/LightMonitorInit.cs index 5b70ed1..b233588 100644 --- a/LightMonitor.Manager/LightMonitorInit.cs +++ b/LightMonitor.Manager/LightMonitorInit.cs @@ -9,7 +9,7 @@ using LightMonitorManager.Interface; namespace LightMonitorManager; [NetDaemonApp] -public sealed class LightMonitorInit : ILightMonitorInit +public sealed class LightMonitorInit { private readonly IHaContext _haContext; private readonly ILogger _logger; @@ -39,7 +39,11 @@ public sealed class LightMonitorInit : ILightMonitorInit { SubscribeToSunStateChanges(); SubscribeToPersonStateChanges(); - _logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", _options.PersonEntityIds.Length); + + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", _options.PersonEntityIds.Length); + } } catch (Exception ex) { @@ -64,8 +68,11 @@ public sealed class LightMonitorInit : ILightMonitorInit if (IsRecoveryTransition(e.Old?.State)) { - _logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State); - + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State); + } + return; } @@ -100,11 +107,19 @@ public sealed class LightMonitorInit : ILightMonitorInit if (IsRecoveryTransition(e.Old?.State)) { - _logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", personEntityId, e.Old?.State); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", personEntityId, e.Old?.State); + } + return; } - _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId); + } + _lightControlService.TurnOnLight(); } catch (Exception ex) diff --git a/LightMonitor.Manager/PresenceService.cs b/LightMonitor.Manager/PresenceService.cs index be8fd2a..70f45e3 100644 --- a/LightMonitor.Manager/PresenceService.cs +++ b/LightMonitor.Manager/PresenceService.cs @@ -24,15 +24,19 @@ public sealed class PresenceService( continue; } - if (string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Person {EntityId} is home", personEntityId); - - return true; } + + return true; } - - + return false; } } diff --git a/LightMonitor.Models/LightMonitorOptions.cs b/LightMonitor.Models/LightMonitorOptions.cs index c4381a4..5b1158b 100644 --- a/LightMonitor.Models/LightMonitorOptions.cs +++ b/LightMonitor.Models/LightMonitorOptions.cs @@ -6,8 +6,8 @@ public sealed class LightMonitorOptions { public const string SectionName = "LightMonitor"; - public bool Enabled { get; set; } - public string LightEntityId { get; set; } = DefaultLightEntityId; - public string SunEntityId { get; set; } = DefaultSunEntityId; - public string[] PersonEntityIds { get; set; } = DefaultPersonEntityIds; + public bool Enabled { get; init; } + public string LightEntityId { get; init; } = DefaultLightEntityId; + public string SunEntityId { get; init; } = DefaultSunEntityId; + public string[] PersonEntityIds { get; init; } = DefaultPersonEntityIds; } diff --git a/Mappings/NordPoolMappingProfile.cs b/Mappings/NordPoolMappingProfile.cs index 820909f..60f3cf6 100644 --- a/Mappings/NordPoolMappingProfile.cs +++ b/Mappings/NordPoolMappingProfile.cs @@ -8,7 +8,8 @@ public class NordPoolMappingProfile : Profile { public NordPoolMappingProfile() { - CreateMap(); + CreateMap() + .ForMember(destination => destination.Price, options => options.MapFrom(source => source.Price)); CreateMap(); } } \ No newline at end of file diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index 6b19ed1..da1abfc 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -167,8 +167,11 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< } var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; - - logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap); + + 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[] { @@ -273,9 +276,9 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< } } - internal ICollection GetInitEntitiesList(string? unitOfMeasurement) + internal static ICollection GetInitEntitiesList(string? unitOfMeasurement) { - var currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId; + const string currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId; var currentPriceDomainSeparator = currentPriceEntityId.IndexOf('.', StringComparison.Ordinal); var currentPriceDomain = currentPriceEntityId[..currentPriceDomainSeparator]; var currentPriceObjectId = currentPriceEntityId[(currentPriceDomainSeparator + 1)..]; diff --git a/NordPool.Manager/NordPoolPriceService.cs b/NordPool.Manager/NordPoolPriceService.cs index b1402c9..7c8fcc3 100644 --- a/NordPool.Manager/NordPoolPriceService.cs +++ b/NordPool.Manager/NordPoolPriceService.cs @@ -28,13 +28,21 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger index) - { - var price = TodayNordPoolPrice.Prices[index].Price; + logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0); + } - if (price.HasValue) - { - CurrentPrice = price.Value; - } - else - { - logger.LogWarning("Price at index {Index} is null", index); - } + if (DayQuartersIndex == index) + { + return; + } + + if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index) + { + var price = TodayNordPoolPrice.Prices[index].Price; + + if (price.HasValue) + { + CurrentPrice = price.Value; } else { - logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0); + logger.LogWarning("Price at index {Index} is null", index); } - - DayQuartersIndex = index; } + else + { + logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0); + } + + DayQuartersIndex = index; } public double GetCurrentPrice() @@ -94,17 +107,14 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger 0 }) { - var currentHour = DateTime.Now.Hour; - - if (currentHour >= 13) - { - return true; - } + return false; } - return false; + var currentHour = DateTime.Now.Hour; + + return currentHour >= 13; } public void RollOverPrices(DateOnly today) @@ -172,27 +182,31 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger(priceResult) : new NordPoolPrice(); } - internal NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice) + internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice) { var recalculatedPrice = new NordPoolPrice { Prices = new List() }; - if (todayNordPoolPrice.Prices != null) + if (todayNordPoolPrice.Prices is null) { - foreach (var price in todayNordPoolPrice.Prices) + return recalculatedPrice; + } + + foreach (var price in todayNordPoolPrice.Prices) + { + if (price.Price is null) { - if (price.Price != null) - { - recalculatedPrice.Prices.Add(new NordPoolDayPrice - { - Start = price.Start, - End = price.End, - Price = PriceCorrection(price.Price.Value) - }); - } + continue; } + + recalculatedPrice.Prices.Add(new NordPoolDayPrice + { + Start = price.Start, + End = price.End, + Price = PriceCorrection(price.Price.Value) + }); } return recalculatedPrice; diff --git a/NordPool.Manager/NordPoolServiceRegistration.cs b/NordPool.Manager/NordPoolServiceRegistration.cs index 65ab90a..da6d66b 100644 --- a/NordPool.Manager/NordPoolServiceRegistration.cs +++ b/NordPool.Manager/NordPoolServiceRegistration.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; using NordPoolManager.Interface; @@ -7,7 +6,7 @@ namespace NordPoolManager; public static class NordPoolServiceRegistration { - public static IServiceCollection AddNordPool(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddNordPool(this IServiceCollection services) { services .AddNetDaemonApp() diff --git a/NordPool.Models/CheapestIntervalResult.cs b/NordPool.Models/CheapestIntervalResult.cs index 7973024..f2758b1 100644 --- a/NordPool.Models/CheapestIntervalResult.cs +++ b/NordPool.Models/CheapestIntervalResult.cs @@ -5,14 +5,14 @@ namespace NordPool.Models; public class CheapestIntervalResult { [JsonPropertyName("start")] - public DateTime Start { get; set; } + public DateTime Start { get; init; } [JsonPropertyName("end")] - public DateTime End { get; set; } + public DateTime End { get; init; } [JsonPropertyName("price")] - public double Price { get; set; } + public double Price { get; init; } [JsonPropertyName("rank")] - public int Rank { get; set; } + public int Rank { get; init; } } diff --git a/NordPool.Models/CompactNordPoolDayPrice.cs b/NordPool.Models/CompactNordPoolDayPrice.cs index caf92ba..5e77340 100644 --- a/NordPool.Models/CompactNordPoolDayPrice.cs +++ b/NordPool.Models/CompactNordPoolDayPrice.cs @@ -69,12 +69,10 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter? Prices { get; set; } + public List? Prices { get; init; } } \ No newline at end of file diff --git a/NordPool.Models/NordPoolConsts.cs b/NordPool.Models/NordPoolConsts.cs index 7209365..f30158c 100644 --- a/NordPool.Models/NordPoolConsts.cs +++ b/NordPool.Models/NordPoolConsts.cs @@ -2,7 +2,7 @@ namespace NordPool.Models; public static class NordPoolConsts { - public static readonly string ConfigEntry = "01K9HYQE4Y0E7KC36JZV11MEXH"; + public const string ConfigEntry = "01K9HYQE4Y0E7KC36JZV11MEXH"; /// /// NordPool electricity market uses 15-minute trading intervals. diff --git a/NordPool.Models/NordPoolDayPriceExtensions.cs b/NordPool.Models/NordPoolDayPriceExtensions.cs index 147c520..4436e1e 100644 --- a/NordPool.Models/NordPoolDayPriceExtensions.cs +++ b/NordPool.Models/NordPoolDayPriceExtensions.cs @@ -4,11 +4,8 @@ public static class NordPoolDayPriceExtensions { public static List ToCompact(this IEnumerable? prices) { - if (prices is null) - { - return []; - } - - return prices.Select(CompactNordPoolDayPrice.FromDayPrice).ToList(); + return prices is null + ? [] + : [.. prices.Select(CompactNordPoolDayPrice.FromDayPrice)]; } } diff --git a/NordPool.Models/NordPoolEntities.cs b/NordPool.Models/NordPoolEntities.cs index f430629..43a09c1 100644 --- a/NordPool.Models/NordPoolEntities.cs +++ b/NordPool.Models/NordPoolEntities.cs @@ -13,9 +13,9 @@ public class NordPoolEntity : EntityCreateModel manufacturer = NordPoolConsts.DeviceManufacturer }; - public string Domain { get; set; } - public string Identifier { get; set; } - public string Name { get; set; } + public string Domain { get; } + public string Identifier { get; } + public string Name { get; } public NordPoolEntity(string domain, string identifier, string name) { diff --git a/NordPool.Models/NordPoolPrice.cs b/NordPool.Models/NordPoolPrice.cs index 06c9666..8396252 100644 --- a/NordPool.Models/NordPoolPrice.cs +++ b/NordPool.Models/NordPoolPrice.cs @@ -2,5 +2,5 @@ public class NordPoolPrice { - public IList? Prices { get; set; } + public IList? Prices { get; init; } } \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs b/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs index 519f2e4..e971889 100644 --- a/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs +++ b/PowerMonitor.Manager/Interface/IOtherPowerCalculationService.cs @@ -5,5 +5,4 @@ namespace PowerMonitorManager.Interface; public interface IOtherPowerCalculationService { PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary deviceReadings); - void Reset(); } diff --git a/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs b/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs index 71dc639..ae2ffaf 100644 --- a/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs +++ b/PowerMonitor.Manager/Interface/IPowerCostCalculationService.cs @@ -7,9 +7,7 @@ public interface IPowerCostCalculationService void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now); CostSnapshot GetTotalCostSnapshot(); CostSnapshot GetOtherCostSnapshot(); - CostSnapshot GetDeviceCostSnapshot(string entityId); IReadOnlyDictionary GetAllDeviceCostSnapshots(); double LastKnownPrice { get; } string PriceSource { get; } - void SetPrice(double price); } diff --git a/PowerMonitor.Manager/Interface/IPowerMonitorInit.cs b/PowerMonitor.Manager/Interface/IPowerMonitorInit.cs deleted file mode 100644 index 9d4ef4b..0000000 --- a/PowerMonitor.Manager/Interface/IPowerMonitorInit.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace PowerMonitorManager.Interface; - -public interface IPowerMonitorInit -{ - Task InitializeAsync(); - Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); -} diff --git a/PowerMonitor.Manager/Models/CostAccumulator.cs b/PowerMonitor.Manager/Models/CostAccumulator.cs index 271cbea..072feac 100644 --- a/PowerMonitor.Manager/Models/CostAccumulator.cs +++ b/PowerMonitor.Manager/Models/CostAccumulator.cs @@ -1,6 +1,6 @@ namespace PowerMonitorManager.Models; -public sealed class CostAccumulator +public sealed class CostAccumulator(DateTime now) { private readonly Lock _lock = new(); @@ -14,21 +14,13 @@ public sealed class CostAccumulator private double _previousDaily; private double _previousMonthly; - private DateTime _last15MinReset; - private DateTime _last1HourReset; - private DateTime _lastDailyReset; - private DateTime _lastMonthlyReset; + private DateTime _last15MinReset = now; + private DateTime _last1HourReset = now; + private DateTime _lastDailyReset = now; + private DateTime _lastMonthlyReset = now; private bool _partialWindow = true; - public CostAccumulator(DateTime now) - { - _last15MinReset = now; - _last1HourReset = now; - _lastDailyReset = now; - _lastMonthlyReset = now; - } - public void AddCost(double costIncrement, DateTime now) { lock (_lock) @@ -85,12 +77,14 @@ public sealed class CostAccumulator _lastDailyReset = now; } - if (IsNewMonthWindow(now, _lastMonthlyReset)) + if (!IsNewMonthWindow(now, _lastMonthlyReset)) { - _previousMonthly = _costMonthly; - _costMonthly = 0; - _lastMonthlyReset = now; + return; } + + _previousMonthly = _costMonthly; + _costMonthly = 0; + _lastMonthlyReset = now; } internal static bool IsNew15MinWindow(DateTime now, DateTime lastReset) diff --git a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs index b2e4d51..4ecd319 100644 --- a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs +++ b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs @@ -6,13 +6,13 @@ public sealed class PowerMonitorOptions { public const string SectionName = "PowerMonitor"; - public bool Enabled { get; set; } + public bool Enabled { get; init; } public string MainMeterEntityId { get; set; } = string.Empty; - public int PollIntervalSeconds { get; set; } = PowerMonitorConsts.DefaultPollIntervalSeconds; - public int SmoothingWindowSize { get; set; } = PowerMonitorConsts.DefaultSmoothingWindowSize; - public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts; + public int PollIntervalSeconds { get; init; } = PowerMonitorConsts.DefaultPollIntervalSeconds; + public int SmoothingWindowSize { get; init; } = PowerMonitorConsts.DefaultSmoothingWindowSize; + public double AnomalyThresholdWatts { get; init; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts; public string[] ExcludedSensorPatterns { get; set; } = []; - public double HighPowerThresholdWatts { get; set; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts; + public double HighPowerThresholdWatts { get; init; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts; public bool EnforceLimitEnabled { get; set; } = true; public double PowerLimitWatts { get; set; } = PowerMonitorConsts.DefaultPowerLimitWatts; diff --git a/PowerMonitor.Manager/OtherPowerCalculationService.cs b/PowerMonitor.Manager/OtherPowerCalculationService.cs index 3261336..5d6ec32 100644 --- a/PowerMonitor.Manager/OtherPowerCalculationService.cs +++ b/PowerMonitor.Manager/OtherPowerCalculationService.cs @@ -32,7 +32,7 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService lock (_lock) { smoothed = _previousSmoothed.HasValue - ? (_alpha * rawOther) + ((1 - _alpha) * _previousSmoothed.Value) + ? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value : rawOther; _previousSmoothed = smoothed; } diff --git a/PowerMonitor.Manager/PowerLimitEnforcementService.cs b/PowerMonitor.Manager/PowerLimitEnforcementService.cs index 44726ad..bcc1a45 100644 --- a/PowerMonitor.Manager/PowerLimitEnforcementService.cs +++ b/PowerMonitor.Manager/PowerLimitEnforcementService.cs @@ -18,11 +18,10 @@ public sealed class PowerLimitEnforcementService( { private readonly PowerMonitorOptions _options = options.Value; - private bool _isLimitActive; private DateTimeOffset _enforcedAt; private DateTimeOffset _lastActionTime; - public bool IsLimitActive => _isLimitActive; + public bool IsLimitActive { get; private set; } public void EnforceLimit(double currentPowerWatts) { @@ -33,7 +32,7 @@ public sealed class PowerLimitEnforcementService( var now = timeProvider.GetUtcNow(); - if (!_isLimitActive) + if (!IsLimitActive) { TryEnforce(currentPowerWatts, now); return; @@ -44,7 +43,7 @@ public sealed class PowerLimitEnforcementService( public void TriggerLimitBreach() { - if (_isLimitActive) + if (IsLimitActive) { logger.LogInformation("Debug: trigger requested but limit already active"); return; @@ -56,7 +55,7 @@ public sealed class PowerLimitEnforcementService( public void ResetLimitBreach() { - if (!_isLimitActive) + if (!IsLimitActive) { logger.LogInformation("Debug: reset requested but limit not active"); return; @@ -80,7 +79,7 @@ public sealed class PowerLimitEnforcementService( NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts); - _isLimitActive = true; + IsLimitActive = true; var now = timeProvider.GetUtcNow(); _enforcedAt = now; _lastActionTime = now; @@ -95,7 +94,7 @@ public sealed class PowerLimitEnforcementService( DismissLimitNotification(); - _isLimitActive = false; + IsLimitActive = false; _lastActionTime = timeProvider.GetUtcNow(); } @@ -108,8 +107,11 @@ public sealed class PowerLimitEnforcementService( if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds)) { - logger.LogDebug("Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", currentPowerWatts, _options.PowerLimitWatts); - + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", currentPowerWatts, _options.PowerLimitWatts); + } + return; } @@ -135,7 +137,10 @@ public sealed class PowerLimitEnforcementService( return; } - logger.LogInformation("Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors", currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds); + 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) { @@ -144,7 +149,7 @@ public sealed class PowerLimitEnforcementService( DismissLimitNotification(); - _isLimitActive = false; + IsLimitActive = false; _lastActionTime = now; } diff --git a/PowerMonitor.Manager/PowerMonitorEntityService.cs b/PowerMonitor.Manager/PowerMonitorEntityService.cs index df00b0b..8da663f 100644 --- a/PowerMonitor.Manager/PowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/PowerMonitorEntityService.cs @@ -48,7 +48,11 @@ public sealed class PowerMonitorEntityService( { try { - logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId); + } + await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); } catch (Exception ex) @@ -69,7 +73,11 @@ public sealed class PowerMonitorEntityService( { try { - logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId); + } + await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); } catch (Exception ex) @@ -169,8 +177,11 @@ public sealed class PowerMonitorEntityService( try { await entityManager.RemoveEntity(id).ConfigureAwait(false); - - logger.LogDebug("Entity removed: {EntityId}", id); + + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("Entity removed: {EntityId}", id); + } } catch (Exception ex) { @@ -182,7 +193,7 @@ public sealed class PowerMonitorEntityService( } - internal ICollection GetSystemEntitiesList() + internal static ICollection GetSystemEntitiesList() { return new List { diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index b7b073f..8ee8b67 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -13,7 +13,7 @@ using PowerMonitorManager.Models.Consts; namespace PowerMonitorManager; [NetDaemonApp] -public sealed class PowerMonitorInit : IPowerMonitorInit +public sealed class PowerMonitorInit { private readonly ILogger _logger; private readonly IHaContext _haContext; @@ -84,7 +84,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit } } - public async Task InitializeAsync() + private async Task InitializeAsync() { try { @@ -98,7 +98,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit var sensors = GetPowerSensorEntitiesNames(); await _entityService.CreateDeviceEntitiesAsync(sensors); - _logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count); + } await PollAndUpdateAsync(); } @@ -116,7 +119,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit return sensors; } - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) + private async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { await _entityService.RemoveSystemEntitiesAsync(cancellationToken); } @@ -141,7 +144,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit _ = PollAndUpdateAsync(); }); - _logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId); + } } private void SubscribeToRediscoverButton() @@ -190,7 +196,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit if (added.Count > 0) { await _entityService.CreateDeviceEntitiesAsync(added); - _logger.LogInformation("Created entities for {Count} new sensors", added.Count); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Created entities for {Count} new sensors", added.Count); + } } if (removed.Count > 0) @@ -198,7 +207,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit await RemoreDevicePriceEntities(removed); } - _logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", newSensors.Count, added.Count, removed.Count); + 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 +223,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit var removedNames = removed.Select(s => s.DeviceName).ToList(); await _entityService.RemoveDeviceEntitiesAsync(removedNames); - _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); + } } private async Task PollAndUpdateAsync() @@ -247,15 +262,13 @@ public sealed class PowerMonitorInit : IPowerMonitorInit _costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime); var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts; - - if (isAnomaly && _anomalyStartTime is null) + + _anomalyStartTime = isAnomaly switch { - _anomalyStartTime = now; - } - else if (!isAnomaly) - { - _anomalyStartTime = null; - } + true when _anomalyStartTime is null => now, + false => null, + _ => _anomalyStartTime + }; var anomalyDuration = _anomalyStartTime.HasValue ? now - _anomalyStartTime.Value @@ -288,8 +301,11 @@ public sealed class PowerMonitorInit : IPowerMonitorInit _enforcementService.EnforceLimit(calculation.TotalPowerWatts); - _logger.LogDebug("Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", - calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, effectivePrice); + 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 +328,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit return price; } - _logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State); + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State); + } return 0; } @@ -321,15 +340,17 @@ public sealed class PowerMonitorInit : IPowerMonitorInit { var isAboveThreshold = totalPowerWatts > _options.HighPowerThresholdWatts; - if (isAboveThreshold && !_highPowerNotificationActive) + switch (isAboveThreshold, _highPowerNotificationActive) { - _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); - _highPowerNotificationActive = true; - } - else if (!isAboveThreshold && _highPowerNotificationActive) - { - _notificationService.DismissHighPowerNotification(); - _highPowerNotificationActive = false; + case (true, false): + _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); + _highPowerNotificationActive = true; + break; + + case (false, true): + _notificationService.DismissHighPowerNotification(); + _highPowerNotificationActive = false; + break; } } diff --git a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs index 777aeb5..366906d 100644 --- a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs +++ b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs @@ -1,19 +1,13 @@ -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; using PowerMonitorManager.Interface; -using PowerMonitorManager.Models; namespace PowerMonitorManager; public static class PowerMonitorServiceRegistration { - public static IServiceCollection AddPowerMonitor(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddPowerMonitor(this IServiceCollection services) { - var options = configuration - .GetSection(PowerMonitorOptions.SectionName) - .Get() ?? new PowerMonitorOptions(); - services .AddNetDaemonApp() .AddScoped() diff --git a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs index 54e1168..982e651 100644 --- a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs +++ b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs @@ -30,9 +30,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService _haContext = haContext; _options = options.Value; _logger = logger; - _exclusionPatterns = _options.ExcludedSensorPatterns - .Select(GlobToRegex) - .ToArray(); + _exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)]; } public IReadOnlyList DiscoverDeviceSensors() @@ -54,13 +52,16 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService _currentDeviceSensors = powerSensors; - _logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", - powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); + 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; } - internal bool IsPowerSensor(Entity entity) + internal static bool IsPowerSensor(Entity entity) { if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) { diff --git a/PowerMonitor.Models/PowerMonitorEntity.cs b/PowerMonitor.Models/PowerMonitorEntity.cs index 18e86d8..f1a5bce 100644 --- a/PowerMonitor.Models/PowerMonitorEntity.cs +++ b/PowerMonitor.Models/PowerMonitorEntity.cs @@ -5,9 +5,9 @@ namespace PowerMonitor.Models; public class PowerMonitorEntity : EntityCreateModel { - public string Domain { get; set; } - public string Identifier { get; set; } - public string Name { get; set; } + public string Domain { get; } + public string Identifier { get; } + public string Name { get; } public PowerMonitorEntity(string domain, string identifier, string name) { diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs index 75740ec..82a283c 100644 --- a/ShowerMonitor.Manager/ExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -38,6 +38,10 @@ public sealed class ExhaustFanControlService( case ShowerState.Idle: EvaluatePostShowerFanOff(timestamp); break; + + default: + // Unknown state: leave the fan untouched. + break; } } } diff --git a/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs index 18918d6..cb55183 100644 --- a/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs +++ b/ShowerMonitor.Manager/Interface/IShowerDetectionService.cs @@ -5,7 +5,6 @@ namespace ShowerMonitorManager.Interface; public interface IShowerDetectionService { - ShowerState CurrentState { get; } ShowerSession? CurrentSession { get; } ShowerSession? LastCompletedSession { get; } int TodaySessionCount { get; } diff --git a/ShowerMonitor.Manager/Interface/IShowerMonitorInit.cs b/ShowerMonitor.Manager/Interface/IShowerMonitorInit.cs deleted file mode 100644 index fa730a7..0000000 --- a/ShowerMonitor.Manager/Interface/IShowerMonitorInit.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ShowerMonitorManager.Interface; - -public interface IShowerMonitorInit -{ - Task InitializeAsync(); - Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); -} diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs index fb28023..95bbed6 100644 --- a/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs +++ b/ShowerMonitor.Manager/Models/ShowerMonitorUpdateContext.cs @@ -6,11 +6,8 @@ namespace ShowerMonitorManager.Models; public sealed class ShowerMonitorUpdateContext { public required ShowerState State { get; init; } - public required double BathroomHumidity { get; init; } - public required double MainHomeHumidity { get; init; } public required double Differential { get; init; } public required double HumidityRate { get; init; } public required int TodaySessionCount { get; init; } public ShowerSession? LastCompletedSession { get; init; } - public ShowerSession? CurrentSession { get; init; } } diff --git a/ShowerMonitor.Manager/ShowerDetectionService.cs b/ShowerMonitor.Manager/ShowerDetectionService.cs index ce1b44b..549b957 100644 --- a/ShowerMonitor.Manager/ShowerDetectionService.cs +++ b/ShowerMonitor.Manager/ShowerDetectionService.cs @@ -80,21 +80,24 @@ public sealed class ShowerDetectionService( private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp) { - if (rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity) - { - _suspectedSince = timestamp; - _currentSession = new ShowerSession - { - StartTime = timestamp, - PreEventHumidity = rateCalculator.PreviousReading ?? humidity, - PeakHumidity = humidity, - PeakTime = timestamp - }; + var showerSuspected = rate >= _options.SpikeRateThreshold + && differential >= _options.MinDifferentialHumidity; - return ShowerState.Suspected; + if (!showerSuspected) + { + return ShowerState.Idle; } - return ShowerState.Idle; + _suspectedSince = timestamp; + _currentSession = new ShowerSession + { + StartTime = timestamp, + PreEventHumidity = rateCalculator.PreviousReading ?? humidity, + PeakHumidity = humidity, + PeakTime = timestamp + }; + + return ShowerState.Suspected; } private ShowerState EvaluateSuspected(double rate, double differential, double humidity, DateTimeOffset timestamp) @@ -106,21 +109,23 @@ public sealed class ShowerDetectionService( } var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes); - - if (_suspectedSince.HasValue && (timestamp - _suspectedSince.Value) >= confirmationWindow + + if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow && humidity >= _options.PeakHumidityThreshold && differential >= _options.MinDifferentialHumidity) { return ShowerState.Active; } - if (rate < 0 && differential < _options.MinDifferentialHumidity) + var showerAbandoned = rate < 0 && differential < _options.MinDifferentialHumidity; + if (!showerAbandoned) { - CompleteSessionCleanup(); - return ShowerState.Idle; + return ShowerState.Suspected; } - return ShowerState.Suspected; + CompleteSessionCleanup(); + + return ShowerState.Idle; } private ShowerState EvaluateActive(double rate, double differential, double humidity, DateTimeOffset timestamp) @@ -132,13 +137,11 @@ public sealed class ShowerDetectionService( } var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); + var maxDurationReached = _currentSession is not null + && _currentSession.GetDuration(timestamp) >= maxDuration; + var humidityRecovered = rate < 0 && differential < _options.MinDifferentialHumidity; - if (_currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration) - { - return TransitionToDeclining(); - } - - if (rate < 0 && differential < _options.MinDifferentialHumidity) + if (maxDurationReached || humidityRecovered) { return TransitionToDeclining(); } @@ -151,23 +154,25 @@ public sealed class ShowerDetectionService( if (differential <= _options.RecoveryDifferentialThreshold) { CompleteSession(timestamp); - + return ShowerState.Completed; } var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); + var maxDurationReached = _currentSession is not null + && _currentSession.GetDuration(timestamp) >= maxDuration; - if (_currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration) + if (!maxDurationReached) { - CompleteSession(timestamp); - - return ShowerState.Completed; + return ShowerState.Declining; } - return ShowerState.Declining; + CompleteSession(timestamp); + + return ShowerState.Completed; } - private ShowerState TransitionToDeclining() + private static ShowerState TransitionToDeclining() { return ShowerState.Declining; } diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs index 1649ded..aa61290 100644 --- a/ShowerMonitor.Manager/ShowerMonitorInit.cs +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -13,7 +13,7 @@ using static ShowerMonitor.Models.ShowerMonitorConsts; namespace ShowerMonitorManager; [NetDaemonApp] -public sealed class ShowerMonitorInit : IShowerMonitorInit +public sealed class ShowerMonitorInit { private readonly ILogger _logger; private readonly IHaContext _haContext; @@ -63,7 +63,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit } } - public async Task InitializeAsync() + private async Task InitializeAsync() { try { @@ -88,11 +88,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit } } - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) - { - await _entityService.CleanupEntitiesAsync(cancellationToken); - } - private void SchedulePeriodicPolling() { var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds); @@ -162,7 +157,11 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue) { - _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity); + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity); + } + return; } @@ -175,19 +174,19 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit var context = new ShowerMonitorUpdateContext { State = state, - BathroomHumidity = bathroomHumidity.Value, - MainHomeHumidity = mainHomeHumidity.Value, Differential = differential, HumidityRate = _detectionService.LastRate, TodaySessionCount = _detectionService.TodaySessionCount, - LastCompletedSession = _detectionService.LastCompletedSession, - CurrentSession = _detectionService.CurrentSession + LastCompletedSession = _detectionService.LastCompletedSession }; await _entityService.UpdateEntitiesAsync(context); - _logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}", - bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state); + 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) { diff --git a/ShowerMonitor.Models/ShowerMonitorEntity.cs b/ShowerMonitor.Models/ShowerMonitorEntity.cs index 4edbb3f..ee3903b 100644 --- a/ShowerMonitor.Models/ShowerMonitorEntity.cs +++ b/ShowerMonitor.Models/ShowerMonitorEntity.cs @@ -5,9 +5,9 @@ namespace ShowerMonitor.Models; public class ShowerMonitorEntity : EntityCreateModel { - public string Domain { get; set; } - public string Identifier { get; set; } - public string Name { get; set; } + private string Domain { get; } + private string Identifier { get; } + private string Name { get; } public ShowerMonitorEntity(string domain, string identifier, string name) { diff --git a/qodana.yaml b/qodana.yaml index f4ddb9e..2756460 100644 --- a/qodana.yaml +++ b/qodana.yaml @@ -70,7 +70,9 @@ exclude: # testCoverageThresholds - configures minimum code coverage on a whole project and newly added code # dependencyLicenses - fails the run on prohibited or unknown dependency licenses # Code Coverage is available in Ultimate and Ultimate Plus plans -#failureConditions: +failureConditions: + severityThresholds: + any: 0 # severityThresholds: # any: 15 # critical: 5