Clear Qodana findings in monitor runtime code

- Guard logger calls with IsEnabled so value-type arguments are not boxed
  when the level is disabled
- Make helper members static, narrow write-only properties to init or
  private get, and delete members no call site reaches
- Flatten nested conditionals and convert if/else chains into switch and
  ternary form
- Drop the unused *MonitorInit interfaces; NetDaemon instantiates the
  concrete app classes
- Drop the unused IConfiguration parameter from AddNordPool and
  AddPowerMonitor, and the unused IEntityManager.CreateEntitiesAsync
- Remove the ignored parameters of the boiler run-time tracker stub
- Pin the NordPool DTO price mapping explicitly so the getter use is
  visible to static analysis
- Fail Qodana on any finding and record the registration changes in
  AGENTS.md
This commit is contained in:
2026-11-29 21:42:43 +02:00
parent 17774b40b8
commit 41ac93733e
65 changed files with 545 additions and 459 deletions
+7 -4
View File
@@ -43,12 +43,15 @@ before editing; it only records things that are easy to get wrong.
`*ServiceRegistration.cs`, reference the projects from `*ServiceRegistration.cs`, reference the projects from
`HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in `HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in
`program.cs`. **NordPool breaks the naming convention**: its extension is `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 - `*ServiceRegistration.cs` honors an `Enabled` flag in the options and
no-ops (skips `AddNetDaemonApp`) when disabled — for every monitor no-ops (skips `AddNetDaemonApp`) when disabled — for every monitor
**except NordPool**, which has no `Enabled` option and always registers. **except NordPool** (no `Enabled` option, always registers) and
`PowerMonitor` ships disabled by default in `appsettings.json`; all **PowerMonitor** (registers unconditionally; `PowerMonitorInit` reads
others ship enabled. `Enabled` itself). `PowerMonitor` ships disabled by default in
`appsettings.json`; all others ship enabled.
- `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated` - `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated`
code (entity metadata sourced from code (entity metadata sourced from
`HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`). `HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`).
+7 -4
View File
@@ -9,7 +9,7 @@ using BatteryMonitorManager.Models;
namespace BatteryMonitorManager; namespace BatteryMonitorManager;
[NetDaemonApp] [NetDaemonApp]
public sealed class BatteryMonitorInit : IBatteryMonitorInit public sealed class BatteryMonitorInit
{ {
private readonly ILogger<BatteryMonitorInit> _logger; private readonly ILogger<BatteryMonitorInit> _logger;
private readonly IScheduler _scheduler; private readonly IScheduler _scheduler;
@@ -46,7 +46,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
} }
} }
public async Task InitializeAsync() private async Task InitializeAsync()
{ {
try try
{ {
@@ -54,7 +54,10 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
CheckAndNotify(); 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) catch (Exception ex)
{ {
@@ -81,7 +84,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
_logger.LogInformation("Scheduled daily battery check at 08:00"); _logger.LogInformation("Scheduled daily battery check at 08:00");
} }
internal void CheckAndNotify() private void CheckAndNotify()
{ {
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent); var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
@@ -6,19 +6,10 @@ using BatteryMonitorManager.Interface;
namespace BatteryMonitorManager; namespace BatteryMonitorManager;
public sealed class BatteryNotificationService : IBatteryNotificationService public sealed class BatteryNotificationService(
IHaContext haContext,
ILogger<BatteryNotificationService> logger) : IBatteryNotificationService
{ {
private readonly IHaContext _haContext;
private readonly ILogger<BatteryNotificationService> _logger;
public BatteryNotificationService(
IHaContext haContext,
ILogger<BatteryNotificationService> logger)
{
_haContext = haContext;
_logger = logger;
}
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices) public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
{ {
if (lowBatteryDevices.Count == 0) if (lowBatteryDevices.Count == 0)
@@ -28,7 +19,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
var message = BuildNotificationMessage(lowBatteryDevices); var message = BuildNotificationMessage(lowBatteryDevices);
_haContext.CallService( haContext.CallService(
BatteryMonitorConsts.PersistentNotificationDomain, BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationCreateService, BatteryMonitorConsts.PersistentNotificationCreateService,
data: new data: new
@@ -38,14 +29,17 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
notification_id = BatteryMonitorConsts.NotificationId notification_id = BatteryMonitorConsts.NotificationId
}); });
_logger.LogInformation( if (logger.IsEnabled(LogLevel.Information))
"Sent low battery notification for {Count} device(s)", {
lowBatteryDevices.Count); logger.LogInformation(
"Sent low battery notification for {Count} device(s)",
lowBatteryDevices.Count);
}
} }
public void DismissNotification() public void DismissNotification()
{ {
_haContext.CallService( haContext.CallService(
BatteryMonitorConsts.PersistentNotificationDomain, BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationDismissService, BatteryMonitorConsts.PersistentNotificationDismissService,
data: new data: new
@@ -53,7 +47,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
notification_id = BatteryMonitorConsts.NotificationId notification_id = BatteryMonitorConsts.NotificationId
}); });
_logger.LogDebug("Dismissed low battery notification"); logger.LogDebug("Dismissed low battery notification");
} }
internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices) internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices)
@@ -8,22 +8,13 @@ using BatteryMonitorManager.Interface;
namespace BatteryMonitorManager; namespace BatteryMonitorManager;
public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryService public sealed class BatterySensorDiscoveryService(
IHaContext haContext,
ILogger<BatterySensorDiscoveryService> logger) : IBatterySensorDiscoveryService
{ {
private readonly IHaContext _haContext;
private readonly ILogger<BatterySensorDiscoveryService> _logger;
public BatterySensorDiscoveryService(
IHaContext haContext,
ILogger<BatterySensorDiscoveryService> logger)
{
_haContext = haContext;
_logger = logger;
}
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent) public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
{ {
var allEntities = _haContext.GetAllEntities(); var allEntities = haContext.GetAllEntities();
var lowBatterySensors = allEntities var lowBatterySensors = allEntities
.Where(IsBatterySensor) .Where(IsBatterySensor)
@@ -32,9 +23,12 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
.Where(info => info is not null) .Where(info => info is not null)
.ToList(); .ToList();
_logger.LogInformation( if (logger.IsEnabled(LogLevel.Information))
"Battery check: found {Count} sensors below {Threshold}%", {
lowBatterySensors.Count, thresholdPercent); logger.LogInformation(
"Battery check: found {Count} sensors below {Threshold}%",
lowBatterySensors.Count, thresholdPercent);
}
return lowBatterySensors!; return lowBatterySensors!;
} }
@@ -65,13 +59,21 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
if (state is null or "unavailable" or "unknown") 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; return null;
} }
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel)) 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; 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) if (element is null)
{ {
@@ -1,6 +0,0 @@
namespace BatteryMonitorManager.Interface;
public interface IBatteryMonitorInit
{
Task InitializeAsync();
}
@@ -6,7 +6,7 @@ public sealed class BatteryMonitorOptions
{ {
public const string SectionName = "BatteryMonitor"; 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;
} }
+4 -1
View File
@@ -37,7 +37,10 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State; var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase); var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", intervalCount, priceCap, skipPriceCap, deadline); if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", intervalCount, priceCap, skipPriceCap, deadline);
}
var config = new BoilerConfig var config = new BoilerConfig
{ {
+32 -24
View File
@@ -19,40 +19,48 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride; var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted; 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) if (waterReady)
{ {
return "water is already ready"; return "water is already ready";
} }
if (effectiveBudgetExhausted) return effectiveBudgetExhausted
{ ? "daily budget is exhausted"
return "daily budget is exhausted"; : "not in a cheap interval";
}
return "not in a cheap interval";
} }
} }
@@ -51,7 +51,10 @@ public sealed class BoilerMonitorEntityService(
{ {
try 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); await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
@@ -148,8 +151,11 @@ public sealed class BoilerMonitorEntityService(
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount)) 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})", if (logger.IsEnabled(LogLevel.Information))
runtimeState, sessionCountState); {
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
}
return null; return null;
} }
@@ -161,8 +167,11 @@ public sealed class BoilerMonitorEntityService(
BudgetOverrideState = budgetOverrideState BudgetOverrideState = budgetOverrideState
}; };
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}", if (logger.IsEnabled(LogLevel.Information))
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState); {
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
}
return persisted; return persisted;
} }
@@ -200,7 +209,7 @@ public sealed class BoilerMonitorEntityService(
return tryParseEntityInt; return tryParseEntityInt;
} }
private ICollection<BoilerMonitorEntity> GetAllEntities() private static ICollection<BoilerMonitorEntity> GetAllEntities()
{ {
var device = CreateDeviceBlock(); var device = CreateDeviceBlock();
@@ -468,7 +477,10 @@ public sealed class BoilerMonitorEntityService(
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var parsed)) 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; return parsed;
} }
} }
@@ -485,7 +497,10 @@ public sealed class BoilerMonitorEntityService(
try try
{ {
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false); 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) catch (Exception ex)
{ {
@@ -498,7 +513,10 @@ public sealed class BoilerMonitorEntityService(
try try
{ {
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false); 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) catch (Exception ex)
{ {
+44 -35
View File
@@ -16,7 +16,7 @@ using static BoilerMonitor.Models.BoilerMonitorConsts;
namespace BoilerMonitorManager; namespace BoilerMonitorManager;
[NetDaemonApp] [NetDaemonApp]
public sealed class BoilerMonitorInit : IBoilerMonitorInit public sealed class BoilerMonitorInit
{ {
private readonly ILogger<BoilerMonitorInit> _logger; private readonly ILogger<BoilerMonitorInit> _logger;
private readonly IHaContext _haContext; private readonly IHaContext _haContext;
@@ -110,7 +110,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
} }
} }
public async Task InitializeAsync() private async Task InitializeAsync()
{ {
try try
{ {
@@ -131,7 +131,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
if (persisted is not null) if (persisted is not null)
{ {
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount); _tracker.RestoreFromSnapshot();
if (persistedCooldown.HasValue) if (persistedCooldown.HasValue)
{ {
@@ -139,8 +139,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
} }
await _entityService.ResetTransientEntitiesAsync(); await _entityService.ResetTransientEntitiesAsync();
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", if (_logger.IsEnabled(LogLevel.Information))
persisted.AccumulatedRunTime, persisted.SessionCount); {
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
}
} }
else else
{ {
@@ -162,11 +165,6 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
} }
} }
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void SchedulePeriodicPolling() private void SchedulePeriodicPolling()
{ {
var now = DateTime.Now; var now = DateTime.Now;
@@ -175,7 +173,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext); var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
var nextPollTime = now.Add(delayUntilNext); 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()); _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync());
} }
@@ -206,15 +207,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
try try
{ {
var switchState = _haContext.GetState(SkipPriceCapEntityId); 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 return;
{
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");
} }
_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) catch (Exception ex)
{ {
@@ -308,7 +311,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
{ {
try 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); await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
} }
catch (Exception e) catch (Exception e)
@@ -337,7 +343,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
{ {
try 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); await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
} }
catch (Exception e) catch (Exception e)
@@ -386,9 +395,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!); var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State; var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value; var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value); _tracker.RecordPollResult();
_tracker.RecordPollResult(isHeating, pollInterval);
if (isHeating) if (isHeating)
{ {
@@ -397,7 +404,6 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval");
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State; var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase); var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
@@ -431,7 +437,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
} }
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0 ? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
: 0.0; : 0.0;
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan; var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
@@ -454,9 +460,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
} }
else if (boilerAction is not BoilerAction.NoChange) else if (boilerAction is not BoilerAction.NoChange)
{ {
_logger.LogInformation( if (_logger.IsEnabled(LogLevel.Information))
"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 var context = new BoilerMonitorUpdateContext
@@ -467,19 +476,19 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
BudgetExhausted = budgetExhausted, BudgetExhausted = budgetExhausted,
SessionCount = snapshot.SessionCount, SessionCount = snapshot.SessionCount,
BudgetHours = dailyHours, BudgetHours = dailyHours,
IsCurrentlyHeating = isHeating,
WaterReady = waterReady, WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState, BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts, BoilerPowerWatts = boilerPowerWatts,
CooldownSince = _waterReadyService.WaterReadySince, CooldownSince = _waterReadyService.WaterReadySince,
IsNowCheap = effectiveIsNowCheap,
NextCheapIntervalStart = nextCheapInterval
}; };
await _entityService.UpdateEntitiesAsync(context); await _entityService.UpdateEntitiesAsync(context);
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", if (_logger.IsEnabled(LogLevel.Debug))
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage); {
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -553,14 +562,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
private static bool ReadAttributeBool(EntityState? entityState, string attributeName) private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
{ {
if (entityState?.Attributes is null) if (entityState?.Attributes is not IDictionary<string, object> attributes)
{ {
return false; return false;
} }
try try
{ {
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value)) if (attributes.TryGetValue(attributeName, out var value))
{ {
return value switch return value switch
{ {
@@ -5,7 +5,7 @@ namespace BoilerMonitorManager;
public class BoilerRunTimeTracker : IBoilerRunTimeTracker 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 return new RunTimeSnapshot
{ {
AccumulatedRunTime = TimeSpan.Zero, AccumulatedRunTime = TimeSpan.Zero,
SessionCount = 0, SessionCount = 0
IsInSession = false
}; };
} }
@@ -25,7 +24,7 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker
} }
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount) public void RestoreFromSnapshot()
{ {
} }
@@ -1,7 +0,0 @@
namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -4,8 +4,8 @@ namespace BoilerMonitorManager.Interface;
public interface IBoilerRunTimeTracker public interface IBoilerRunTimeTracker
{ {
void RecordPollResult(bool isHeating, TimeSpan pollInterval); void RecordPollResult();
RunTimeSnapshot GetSnapshot(); RunTimeSnapshot GetSnapshot();
void Reset(); void Reset();
void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount); void RestoreFromSnapshot();
} }
@@ -8,11 +8,8 @@ public record BoilerMonitorUpdateContext
public required bool BudgetExhausted { get; init; } public required bool BudgetExhausted { get; init; }
public required int SessionCount { get; init; } public required int SessionCount { get; init; }
public required double BudgetHours { get; init; } public required double BudgetHours { get; init; }
public required bool IsCurrentlyHeating { get; init; }
public required bool WaterReady { get; init; } public required bool WaterReady { get; init; }
public required string? BoilerSwitchState { get; init; } public required string? BoilerSwitchState { get; init; }
public required double? BoilerPowerWatts { get; init; } public required double? BoilerPowerWatts { get; init; }
public required DateTimeOffset? CooldownSince { get; init; } public required DateTimeOffset? CooldownSince { get; init; }
public required bool IsNowCheap { get; init; }
public required DateTime? NextCheapIntervalStart { get; init; }
} }
@@ -4,5 +4,4 @@ public record RunTimeSnapshot
{ {
public required TimeSpan AccumulatedRunTime { get; init; } public required TimeSpan AccumulatedRunTime { get; init; }
public required int SessionCount { get; init; } public required int SessionCount { get; init; }
public required bool IsInSession { get; init; }
} }
+25 -7
View File
@@ -40,7 +40,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{ {
if (IsWithinCooldownPeriod()) 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; return true;
} }
} }
@@ -59,7 +62,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{ {
if (!_hasObservedHeating) 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; return false;
} }
@@ -74,15 +80,21 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired) if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
{ {
logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", if (logger.IsEnabled(LogLevel.Debug))
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value); {
logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value);
}
return false; return false;
} }
_waterReadySince ??= timeProvider.GetUtcNow(); _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; return true;
} }
@@ -132,13 +144,19 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero); var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
if (waterReadySince < todayMidnightUtc) 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; return;
} }
_waterReadySince = waterReadySince; _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);
}
} }
} }
+3 -3
View File
@@ -5,9 +5,9 @@ namespace BoilerMonitor.Models;
public class BoilerMonitorEntity : EntityCreateModel public class BoilerMonitorEntity : EntityCreateModel
{ {
public string Domain { get; set; } private string Domain { get; }
public string Identifier { get; set; } private string Identifier { get; }
public string Name { get; set; } private string Name { get; }
public BoilerMonitorEntity(string domain, string identifier, string name) public BoilerMonitorEntity(string domain, string identifier, string name)
{ {
-5
View File
@@ -20,11 +20,6 @@ public class EntityManager(
/// </summary> /// </summary>
private static readonly string[] CleanupTopicSuffixes = ["state", "attributes", "availability", "set", "config"]; private static readonly string[] CleanupTopicSuffixes = ["state", "attributes", "availability", "set", "config"];
public async Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
{
await Task.WhenAll(entities.Select(CreateEntityAsync));
}
public async Task CreateEntityAsync(EntityCreateModel createModel) public async Task CreateEntityAsync(EntityCreateModel createModel)
{ {
if (createModel.EntityId != null) if (createModel.EntityId != null)
@@ -4,7 +4,6 @@ namespace HomeAssistant.Entities.Interfaces;
public interface IEntityManager public interface IEntityManager
{ {
Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities);
Task CreateEntityAsync(EntityCreateModel createModel); Task CreateEntityAsync(EntityCreateModel createModel);
Task SetEntityState(string entityId, string state); Task SetEntityState(string entityId, string state);
Task SetEntityAttributes(string entityId, object attributes); Task SetEntityAttributes(string entityId, object attributes);
+3 -3
View File
@@ -4,7 +4,7 @@ namespace HomeAssistant.Models;
public class EntityCreateModel public class EntityCreateModel
{ {
public string? EntityId { get; set; } public string? EntityId { get; init; }
public EntityCreationOptions? Options { get; set; } = new(); public EntityCreationOptions? Options { get; init; } = new();
public object? AdditionalConfig { get; set; } = null; public object? AdditionalConfig { get; init; }
} }
+11 -3
View File
@@ -22,6 +22,8 @@ public sealed class MqttRecreateApp
private const string NordPoolPriceEntityId = "sensor.nordpool_price"; private const string NordPoolPriceEntityId = "sensor.nordpool_price";
private const string DefaultUnitOfMeasurement = "EUR/kWh"; private const string DefaultUnitOfMeasurement = "EUR/kWh";
private static readonly string[] AppDaemonIdentifiers = ["appdaemon"];
private readonly IHaContext _haContext; private readonly IHaContext _haContext;
private readonly IMqttEntityManager _mqttEntityManager; private readonly IMqttEntityManager _mqttEntityManager;
private readonly IServiceProvider _serviceProvider; private readonly IServiceProvider _serviceProvider;
@@ -59,14 +61,17 @@ public sealed class MqttRecreateApp
icon = "mdi:refresh", icon = "mdi:refresh",
device = new device = new
{ {
identifiers = new[] { "appdaemon" }, identifiers = AppDaemonIdentifiers,
name = "AppDaemon", name = "AppDaemon",
model = "AppDaemon", model = "AppDaemon",
manufacturer = "HomeAssistant App Daemon" manufacturer = "HomeAssistant App Daemon"
} }
}).ConfigureAwait(false); }).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); var button = new Entity(_haContext, RecreateButtonEntityId);
button.StateChanges() button.StateChanges()
@@ -210,7 +215,10 @@ public sealed class MqttRecreateApp
} }
catch (Exception ex) 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; return null;
+2 -2
View File
@@ -53,9 +53,9 @@ try
.AddSingleton(TimeProvider.System) .AddSingleton(TimeProvider.System)
.AddScoped<BoilerMonitor.Models.IBoilerConfigReader, BoilerConfigReader>() .AddScoped<BoilerMonitor.Models.IBoilerConfigReader, BoilerConfigReader>()
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName)) .Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
.AddNordPool(context.Configuration) .AddNordPool()
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) .Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
.AddPowerMonitor(context.Configuration) .AddPowerMonitor()
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) .Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
.AddBoilerMonitor(context.Configuration) .AddBoilerMonitor(context.Configuration)
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName)) .Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
@@ -1,6 +0,0 @@
namespace LeakMonitorManager.Interface;
public interface ILeakMonitorInit
{
Task InitializeAsync();
}
+15 -6
View File
@@ -10,7 +10,7 @@ using LeakMonitorManager.Models;
namespace LeakMonitorManager; namespace LeakMonitorManager;
[NetDaemonApp] [NetDaemonApp]
public sealed class LeakMonitorInit : ILeakMonitorInit public sealed class LeakMonitorInit
{ {
private readonly IHaContext _haContext; private readonly IHaContext _haContext;
private readonly ILeakNotificationService _notificationService; private readonly ILeakNotificationService _notificationService;
@@ -31,7 +31,7 @@ public sealed class LeakMonitorInit : ILeakMonitorInit
_ = InitializeAsync(); _ = InitializeAsync();
} }
public Task InitializeAsync() private Task InitializeAsync()
{ {
try try
{ {
@@ -47,7 +47,10 @@ public sealed class LeakMonitorInit : ILeakMonitorInit
SubscribeToLeakSensor(sensorEntityId); 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) 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) 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)) 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); _notificationService.DismissLeakAlert(sensorEntityId);
} }
} }
@@ -8,7 +8,7 @@ namespace LeakMonitorManager;
public static class LeakMonitorServiceRegistration 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 var options = configuration
.GetSection(LeakMonitorOptions.SectionName) .GetSection(LeakMonitorOptions.SectionName)
@@ -16,11 +16,9 @@ public static class LeakMonitorServiceRegistration
if (!options.Enabled) if (!options.Enabled)
{ {
return services; return;
} }
services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>(); services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
return services;
} }
} }
+23 -27
View File
@@ -8,37 +8,30 @@ using LeakMonitorManager.Models;
namespace LeakMonitorManager; namespace LeakMonitorManager;
public sealed class LeakNotificationService : ILeakNotificationService public sealed class LeakNotificationService(
IHaContext haContext,
ILogger<LeakNotificationService> logger,
IOptions<LeakMonitorOptions> options,
TimeProvider timeProvider) : ILeakNotificationService
{ {
private readonly IHaContext _haContext; private readonly LeakMonitorOptions _options = options.Value;
private readonly ILogger<LeakNotificationService> _logger;
private readonly LeakMonitorOptions _options;
private readonly TimeProvider _timeProvider;
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new(); private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new();
public LeakNotificationService(
IHaContext haContext,
ILogger<LeakNotificationService> logger,
IOptions<LeakMonitorOptions> options,
TimeProvider timeProvider)
{
_haContext = haContext;
_logger = logger;
_options = options.Value;
_timeProvider = timeProvider;
}
public void SendLeakAlert(string sensorEntityId) public void SendLeakAlert(string sensorEntityId)
{ {
if (IsWithinCooldown(sensorEntityId)) if (IsWithinCooldown(sensorEntityId))
{ {
_logger.LogDebug( if (logger.IsEnabled(LogLevel.Debug))
"Skipping leak notification for {SensorId} -- within cooldown period", {
sensorEntityId); logger.LogDebug(
"Skipping leak notification for {SensorId} -- within cooldown period",
sensorEntityId);
}
return; return;
} }
_lastNotificationTimes[sensorEntityId] = _timeProvider.GetUtcNow(); _lastNotificationTimes[sensorEntityId] = timeProvider.GetUtcNow();
var notificationId = BuildNotificationId(sensorEntityId); var notificationId = BuildNotificationId(sensorEntityId);
var message = $"Water detected by {sensorEntityId}! Check immediately."; var message = $"Water detected by {sensorEntityId}! Check immediately.";
@@ -46,24 +39,27 @@ public sealed class LeakNotificationService : ILeakNotificationService
SendMobilePushNotification(message); SendMobilePushNotification(message);
CreatePersistentNotification(notificationId, 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) public void DismissLeakAlert(string sensorEntityId)
{ {
var notificationId = BuildNotificationId(sensorEntityId); var notificationId = BuildNotificationId(sensorEntityId);
_haContext.CallService( haContext.CallService(
LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationDomain,
LeakMonitorConsts.PersistentNotificationDismissService, LeakMonitorConsts.PersistentNotificationDismissService,
data: new { notification_id = notificationId }); 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) private void SendMobilePushNotification(string message)
{ {
_haContext.CallService( haContext.CallService(
LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.NotifyDomain,
LeakMonitorConsts.MobileAppService, LeakMonitorConsts.MobileAppService,
data: new data: new
@@ -86,7 +82,7 @@ public sealed class LeakNotificationService : ILeakNotificationService
private void CreatePersistentNotification(string notificationId, string message) private void CreatePersistentNotification(string notificationId, string message)
{ {
_haContext.CallService( haContext.CallService(
LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationDomain,
LeakMonitorConsts.PersistentNotificationCreateService, LeakMonitorConsts.PersistentNotificationCreateService,
data: new data: new
@@ -105,7 +101,7 @@ public sealed class LeakNotificationService : ILeakNotificationService
} }
var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes); var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes);
return _timeProvider.GetUtcNow() - lastTime < cooldown; return timeProvider.GetUtcNow() - lastTime < cooldown;
} }
internal static string BuildNotificationId(string sensorEntityId) internal static string BuildNotificationId(string sensorEntityId)
@@ -6,9 +6,9 @@ public sealed class LeakMonitorOptions
{ {
public const string SectionName = "LeakMonitor"; 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;
} }
-2
View File
@@ -20,7 +20,5 @@ public static class LeakMonitorConsts
public const string NotificationTitle = "Water Leak Detected!"; public const string NotificationTitle = "Water Leak Detected!";
public const string DismissTitle = "Water Leak Cleared";
public const int DefaultNotificationCooldownMinutes = 5; public const int DefaultNotificationCooldownMinutes = 5;
} }
@@ -1,6 +0,0 @@
namespace LightMonitorManager.Interface;
public interface ILightMonitorInit
{
Task InitializeAsync();
}
+15 -6
View File
@@ -21,8 +21,11 @@ public sealed class LightControlService(
if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) 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; return;
} }
@@ -30,13 +33,19 @@ public sealed class LightControlService(
if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase)) 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; return;
} }
haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId)); 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);
}
} }
} }
+21 -6
View File
@@ -9,7 +9,7 @@ using LightMonitorManager.Interface;
namespace LightMonitorManager; namespace LightMonitorManager;
[NetDaemonApp] [NetDaemonApp]
public sealed class LightMonitorInit : ILightMonitorInit public sealed class LightMonitorInit
{ {
private readonly IHaContext _haContext; private readonly IHaContext _haContext;
private readonly ILogger<LightMonitorInit> _logger; private readonly ILogger<LightMonitorInit> _logger;
@@ -39,7 +39,11 @@ public sealed class LightMonitorInit : ILightMonitorInit
{ {
SubscribeToSunStateChanges(); SubscribeToSunStateChanges();
SubscribeToPersonStateChanges(); 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) catch (Exception ex)
{ {
@@ -64,8 +68,11 @@ public sealed class LightMonitorInit : ILightMonitorInit
if (IsRecoveryTransition(e.Old?.State)) 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; return;
} }
@@ -100,11 +107,19 @@ public sealed class LightMonitorInit : ILightMonitorInit
if (IsRecoveryTransition(e.Old?.State)) 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; 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(); _lightControlService.TurnOnLight();
} }
catch (Exception ex) catch (Exception ex)
+9 -5
View File
@@ -24,15 +24,19 @@ public sealed class PresenceService(
continue; 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); logger.LogDebug("Person {EntityId} is home", personEntityId);
return true;
} }
return true;
} }
return false; return false;
} }
} }
+4 -4
View File
@@ -6,8 +6,8 @@ public sealed class LightMonitorOptions
{ {
public const string SectionName = "LightMonitor"; public const string SectionName = "LightMonitor";
public bool Enabled { get; set; } public bool Enabled { get; init; }
public string LightEntityId { get; set; } = DefaultLightEntityId; public string LightEntityId { get; init; } = DefaultLightEntityId;
public string SunEntityId { get; set; } = DefaultSunEntityId; public string SunEntityId { get; init; } = DefaultSunEntityId;
public string[] PersonEntityIds { get; set; } = DefaultPersonEntityIds; public string[] PersonEntityIds { get; init; } = DefaultPersonEntityIds;
} }
+2 -1
View File
@@ -8,7 +8,8 @@ public class NordPoolMappingProfile : Profile
{ {
public NordPoolMappingProfile() public NordPoolMappingProfile()
{ {
CreateMap<NordPoolDayPriceDto, NordPoolDayPrice>(); CreateMap<NordPoolDayPriceDto, NordPoolDayPrice>()
.ForMember(destination => destination.Price, options => options.MapFrom(source => source.Price));
CreateMap<NordPoolPriceResultDto, NordPoolPrice>(); CreateMap<NordPoolPriceResultDto, NordPoolPrice>();
} }
} }
+7 -4
View File
@@ -167,8 +167,11 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
} }
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; 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[] var updateTasks = new[]
{ {
@@ -273,9 +276,9 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
} }
} }
internal ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement) internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
{ {
var currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId; const string currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId;
var currentPriceDomainSeparator = currentPriceEntityId.IndexOf('.', StringComparison.Ordinal); var currentPriceDomainSeparator = currentPriceEntityId.IndexOf('.', StringComparison.Ordinal);
var currentPriceDomain = currentPriceEntityId[..currentPriceDomainSeparator]; var currentPriceDomain = currentPriceEntityId[..currentPriceDomainSeparator];
var currentPriceObjectId = currentPriceEntityId[(currentPriceDomainSeparator + 1)..]; var currentPriceObjectId = currentPriceEntityId[(currentPriceDomainSeparator + 1)..];
+53 -39
View File
@@ -28,13 +28,21 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today)) if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today))
{ {
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today); if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
}
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today"); TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
} }
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today.AddDays(1))) if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today.AddDays(1)))
{ {
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1)); if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
}
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow"); TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
} }
@@ -46,30 +54,35 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
{ {
var index = GetTimeQuarterIndex(DateTime.UtcNow); var index = GetTimeQuarterIndex(DateTime.UtcNow);
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0); if (logger.IsEnabled(LogLevel.Debug))
if (DayQuartersIndex != index)
{ {
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index) logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
{ }
var price = TodayNordPoolPrice.Prices[index].Price;
if (price.HasValue) if (DayQuartersIndex == index)
{ {
CurrentPrice = price.Value; return;
} }
else
{ if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
logger.LogWarning("Price at index {Index} is null", index); {
} var price = TodayNordPoolPrice.Prices[index].Price;
if (price.HasValue)
{
CurrentPrice = price.Value;
} }
else 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() public double GetCurrentPrice()
@@ -94,17 +107,14 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
return true; return true;
} }
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
{ {
var currentHour = DateTime.Now.Hour; return false;
if (currentHour >= 13)
{
return true;
}
} }
return false; var currentHour = DateTime.Now.Hour;
return currentHour >= 13;
} }
public void RollOverPrices(DateOnly today) public void RollOverPrices(DateOnly today)
@@ -172,27 +182,31 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
return priceResult != null ? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult) : new NordPoolPrice(); return priceResult != null ? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult) : new NordPoolPrice();
} }
internal NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice) internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
{ {
var recalculatedPrice = new NordPoolPrice var recalculatedPrice = new NordPoolPrice
{ {
Prices = new List<NordPoolDayPrice>() Prices = new List<NordPoolDayPrice>()
}; };
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) continue;
{
recalculatedPrice.Prices.Add(new NordPoolDayPrice
{
Start = price.Start,
End = price.End,
Price = PriceCorrection(price.Price.Value)
});
}
} }
recalculatedPrice.Prices.Add(new NordPoolDayPrice
{
Start = price.Start,
End = price.End,
Price = PriceCorrection(price.Price.Value)
});
} }
return recalculatedPrice; return recalculatedPrice;
@@ -1,4 +1,3 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using NordPoolManager.Interface; using NordPoolManager.Interface;
@@ -7,7 +6,7 @@ namespace NordPoolManager;
public static class NordPoolServiceRegistration public static class NordPoolServiceRegistration
{ {
public static IServiceCollection AddNordPool(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddNordPool(this IServiceCollection services)
{ {
services services
.AddNetDaemonApp<NordPoolInit>() .AddNetDaemonApp<NordPoolInit>()
+4 -4
View File
@@ -5,14 +5,14 @@ namespace NordPool.Models;
public class CheapestIntervalResult public class CheapestIntervalResult
{ {
[JsonPropertyName("start")] [JsonPropertyName("start")]
public DateTime Start { get; set; } public DateTime Start { get; init; }
[JsonPropertyName("end")] [JsonPropertyName("end")]
public DateTime End { get; set; } public DateTime End { get; init; }
[JsonPropertyName("price")] [JsonPropertyName("price")]
public double Price { get; set; } public double Price { get; init; }
[JsonPropertyName("rank")] [JsonPropertyName("rank")]
public int Rank { get; set; } public int Rank { get; init; }
} }
+3 -5
View File
@@ -69,12 +69,10 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNo
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble(); double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
reader.Read(); reader.Read();
if (reader.TokenType != JsonTokenType.EndArray)
{
throw new JsonException("Expected end of array.");
}
return new CompactNordPoolDayPrice { Start = start, End = end, Price = price }; return reader.TokenType == JsonTokenType.EndArray
? new CompactNordPoolDayPrice { Start = start, End = end, Price = price }
: throw new JsonException("Expected end of array.");
} }
public override void Write(Utf8JsonWriter writer, CompactNordPoolDayPrice value, JsonSerializerOptions options) public override void Write(Utf8JsonWriter writer, CompactNordPoolDayPrice value, JsonSerializerOptions options)
+2 -2
View File
@@ -5,9 +5,9 @@ namespace NordPool.Models.Dtos;
public class NordPoolDayPriceDto public class NordPoolDayPriceDto
{ {
[JsonPropertyName("start")] [JsonPropertyName("start")]
public string? Start { get; set; } public string? Start { get; init; }
[JsonPropertyName("end")] [JsonPropertyName("end")]
public string? End { get; set; } public string? End { get; init; }
[JsonPropertyName("price")] [JsonPropertyName("price")]
public double? Price { get; set; } public double? Price { get; set; }
} }
@@ -5,5 +5,5 @@ namespace NordPool.Models.Dtos;
public class NordPoolPriceResultDto public class NordPoolPriceResultDto
{ {
[JsonPropertyName("LT")] [JsonPropertyName("LT")]
public List<NordPoolDayPriceDto>? Prices { get; set; } public List<NordPoolDayPriceDto>? Prices { get; init; }
} }
+1 -1
View File
@@ -2,7 +2,7 @@ namespace NordPool.Models;
public static class NordPoolConsts public static class NordPoolConsts
{ {
public static readonly string ConfigEntry = "01K9HYQE4Y0E7KC36JZV11MEXH"; public const string ConfigEntry = "01K9HYQE4Y0E7KC36JZV11MEXH";
/// <summary> /// <summary>
/// NordPool electricity market uses 15-minute trading intervals. /// NordPool electricity market uses 15-minute trading intervals.
@@ -4,11 +4,8 @@ public static class NordPoolDayPriceExtensions
{ {
public static List<CompactNordPoolDayPrice> ToCompact(this IEnumerable<NordPoolDayPrice>? prices) public static List<CompactNordPoolDayPrice> ToCompact(this IEnumerable<NordPoolDayPrice>? prices)
{ {
if (prices is null) return prices is null
{ ? []
return []; : [.. prices.Select(CompactNordPoolDayPrice.FromDayPrice)];
}
return prices.Select(CompactNordPoolDayPrice.FromDayPrice).ToList();
} }
} }
+3 -3
View File
@@ -13,9 +13,9 @@ public class NordPoolEntity : EntityCreateModel
manufacturer = NordPoolConsts.DeviceManufacturer manufacturer = NordPoolConsts.DeviceManufacturer
}; };
public string Domain { get; set; } public string Domain { get; }
public string Identifier { get; set; } public string Identifier { get; }
public string Name { get; set; } public string Name { get; }
public NordPoolEntity(string domain, string identifier, string name) public NordPoolEntity(string domain, string identifier, string name)
{ {
+1 -1
View File
@@ -2,5 +2,5 @@
public class NordPoolPrice public class NordPoolPrice
{ {
public IList<NordPoolDayPrice>? Prices { get; set; } public IList<NordPoolDayPrice>? Prices { get; init; }
} }
@@ -5,5 +5,4 @@ namespace PowerMonitorManager.Interface;
public interface IOtherPowerCalculationService public interface IOtherPowerCalculationService
{ {
PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary<string, double> deviceReadings); PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary<string, double> deviceReadings);
void Reset();
} }
@@ -7,9 +7,7 @@ public interface IPowerCostCalculationService
void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now); void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now);
CostSnapshot GetTotalCostSnapshot(); CostSnapshot GetTotalCostSnapshot();
CostSnapshot GetOtherCostSnapshot(); CostSnapshot GetOtherCostSnapshot();
CostSnapshot GetDeviceCostSnapshot(string entityId);
IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots(); IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots();
double LastKnownPrice { get; } double LastKnownPrice { get; }
string PriceSource { get; } string PriceSource { get; }
void SetPrice(double price);
} }
@@ -1,7 +0,0 @@
namespace PowerMonitorManager.Interface;
public interface IPowerMonitorInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
+11 -17
View File
@@ -1,6 +1,6 @@
namespace PowerMonitorManager.Models; namespace PowerMonitorManager.Models;
public sealed class CostAccumulator public sealed class CostAccumulator(DateTime now)
{ {
private readonly Lock _lock = new(); private readonly Lock _lock = new();
@@ -14,21 +14,13 @@ public sealed class CostAccumulator
private double _previousDaily; private double _previousDaily;
private double _previousMonthly; private double _previousMonthly;
private DateTime _last15MinReset; private DateTime _last15MinReset = now;
private DateTime _last1HourReset; private DateTime _last1HourReset = now;
private DateTime _lastDailyReset; private DateTime _lastDailyReset = now;
private DateTime _lastMonthlyReset; private DateTime _lastMonthlyReset = now;
private bool _partialWindow = true; private bool _partialWindow = true;
public CostAccumulator(DateTime now)
{
_last15MinReset = now;
_last1HourReset = now;
_lastDailyReset = now;
_lastMonthlyReset = now;
}
public void AddCost(double costIncrement, DateTime now) public void AddCost(double costIncrement, DateTime now)
{ {
lock (_lock) lock (_lock)
@@ -85,12 +77,14 @@ public sealed class CostAccumulator
_lastDailyReset = now; _lastDailyReset = now;
} }
if (IsNewMonthWindow(now, _lastMonthlyReset)) if (!IsNewMonthWindow(now, _lastMonthlyReset))
{ {
_previousMonthly = _costMonthly; return;
_costMonthly = 0;
_lastMonthlyReset = now;
} }
_previousMonthly = _costMonthly;
_costMonthly = 0;
_lastMonthlyReset = now;
} }
internal static bool IsNew15MinWindow(DateTime now, DateTime lastReset) internal static bool IsNew15MinWindow(DateTime now, DateTime lastReset)
@@ -6,13 +6,13 @@ public sealed class PowerMonitorOptions
{ {
public const string SectionName = "PowerMonitor"; public const string SectionName = "PowerMonitor";
public bool Enabled { get; set; } public bool Enabled { get; init; }
public string MainMeterEntityId { get; set; } = string.Empty; public string MainMeterEntityId { get; set; } = string.Empty;
public int PollIntervalSeconds { get; set; } = PowerMonitorConsts.DefaultPollIntervalSeconds; public int PollIntervalSeconds { get; init; } = PowerMonitorConsts.DefaultPollIntervalSeconds;
public int SmoothingWindowSize { get; set; } = PowerMonitorConsts.DefaultSmoothingWindowSize; public int SmoothingWindowSize { get; init; } = PowerMonitorConsts.DefaultSmoothingWindowSize;
public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts; public double AnomalyThresholdWatts { get; init; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts;
public string[] ExcludedSensorPatterns { get; set; } = []; 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 bool EnforceLimitEnabled { get; set; } = true;
public double PowerLimitWatts { get; set; } = PowerMonitorConsts.DefaultPowerLimitWatts; public double PowerLimitWatts { get; set; } = PowerMonitorConsts.DefaultPowerLimitWatts;
@@ -32,7 +32,7 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
lock (_lock) lock (_lock)
{ {
smoothed = _previousSmoothed.HasValue smoothed = _previousSmoothed.HasValue
? (_alpha * rawOther) + ((1 - _alpha) * _previousSmoothed.Value) ? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
: rawOther; : rawOther;
_previousSmoothed = smoothed; _previousSmoothed = smoothed;
} }
@@ -18,11 +18,10 @@ public sealed class PowerLimitEnforcementService(
{ {
private readonly PowerMonitorOptions _options = options.Value; private readonly PowerMonitorOptions _options = options.Value;
private bool _isLimitActive;
private DateTimeOffset _enforcedAt; private DateTimeOffset _enforcedAt;
private DateTimeOffset _lastActionTime; private DateTimeOffset _lastActionTime;
public bool IsLimitActive => _isLimitActive; public bool IsLimitActive { get; private set; }
public void EnforceLimit(double currentPowerWatts) public void EnforceLimit(double currentPowerWatts)
{ {
@@ -33,7 +32,7 @@ public sealed class PowerLimitEnforcementService(
var now = timeProvider.GetUtcNow(); var now = timeProvider.GetUtcNow();
if (!_isLimitActive) if (!IsLimitActive)
{ {
TryEnforce(currentPowerWatts, now); TryEnforce(currentPowerWatts, now);
return; return;
@@ -44,7 +43,7 @@ public sealed class PowerLimitEnforcementService(
public void TriggerLimitBreach() public void TriggerLimitBreach()
{ {
if (_isLimitActive) if (IsLimitActive)
{ {
logger.LogInformation("Debug: trigger requested but limit already active"); logger.LogInformation("Debug: trigger requested but limit already active");
return; return;
@@ -56,7 +55,7 @@ public sealed class PowerLimitEnforcementService(
public void ResetLimitBreach() public void ResetLimitBreach()
{ {
if (!_isLimitActive) if (!IsLimitActive)
{ {
logger.LogInformation("Debug: reset requested but limit not active"); logger.LogInformation("Debug: reset requested but limit not active");
return; return;
@@ -80,7 +79,7 @@ public sealed class PowerLimitEnforcementService(
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts); NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
_isLimitActive = true; IsLimitActive = true;
var now = timeProvider.GetUtcNow(); var now = timeProvider.GetUtcNow();
_enforcedAt = now; _enforcedAt = now;
_lastActionTime = now; _lastActionTime = now;
@@ -95,7 +94,7 @@ public sealed class PowerLimitEnforcementService(
DismissLimitNotification(); DismissLimitNotification();
_isLimitActive = false; IsLimitActive = false;
_lastActionTime = timeProvider.GetUtcNow(); _lastActionTime = timeProvider.GetUtcNow();
} }
@@ -108,8 +107,11 @@ public sealed class PowerLimitEnforcementService(
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds)) 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; return;
} }
@@ -135,7 +137,10 @@ public sealed class PowerLimitEnforcementService(
return; 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) foreach (var entityId in _options.PauseAndRestoreEntityIds)
{ {
@@ -144,7 +149,7 @@ public sealed class PowerLimitEnforcementService(
DismissLimitNotification(); DismissLimitNotification();
_isLimitActive = false; IsLimitActive = false;
_lastActionTime = now; _lastActionTime = now;
} }
@@ -48,7 +48,11 @@ public sealed class PowerMonitorEntityService(
{ {
try 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); await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
@@ -69,7 +73,11 @@ public sealed class PowerMonitorEntityService(
{ {
try 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); await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
@@ -169,8 +177,11 @@ public sealed class PowerMonitorEntityService(
try try
{ {
await entityManager.RemoveEntity(id).ConfigureAwait(false); 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) catch (Exception ex)
{ {
@@ -182,7 +193,7 @@ public sealed class PowerMonitorEntityService(
} }
internal ICollection<PowerMonitorEntity> GetSystemEntitiesList() internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList()
{ {
return new List<PowerMonitorEntity> return new List<PowerMonitorEntity>
{ {
+48 -27
View File
@@ -13,7 +13,7 @@ using PowerMonitorManager.Models.Consts;
namespace PowerMonitorManager; namespace PowerMonitorManager;
[NetDaemonApp] [NetDaemonApp]
public sealed class PowerMonitorInit : IPowerMonitorInit public sealed class PowerMonitorInit
{ {
private readonly ILogger<PowerMonitorInit> _logger; private readonly ILogger<PowerMonitorInit> _logger;
private readonly IHaContext _haContext; private readonly IHaContext _haContext;
@@ -84,7 +84,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
} }
} }
public async Task InitializeAsync() private async Task InitializeAsync()
{ {
try try
{ {
@@ -98,7 +98,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
var sensors = GetPowerSensorEntitiesNames(); var sensors = GetPowerSensorEntitiesNames();
await _entityService.CreateDeviceEntitiesAsync(sensors); 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(); await PollAndUpdateAsync();
} }
@@ -116,7 +119,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
return sensors; return sensors;
} }
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) private async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{ {
await _entityService.RemoveSystemEntitiesAsync(cancellationToken); await _entityService.RemoveSystemEntitiesAsync(cancellationToken);
} }
@@ -141,7 +144,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
_ = PollAndUpdateAsync(); _ = 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() private void SubscribeToRediscoverButton()
@@ -190,7 +196,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
if (added.Count > 0) if (added.Count > 0)
{ {
await _entityService.CreateDeviceEntitiesAsync(added); 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) if (removed.Count > 0)
@@ -198,7 +207,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
await RemoreDevicePriceEntities(removed); 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) catch (Exception ex)
{ {
@@ -211,7 +223,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
var removedNames = removed.Select(s => s.DeviceName).ToList(); var removedNames = removed.Select(s => s.DeviceName).ToList();
await _entityService.RemoveDeviceEntitiesAsync(removedNames); 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() private async Task PollAndUpdateAsync()
@@ -247,15 +262,13 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime); _costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts; var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts;
if (isAnomaly && _anomalyStartTime is null) _anomalyStartTime = isAnomaly switch
{ {
_anomalyStartTime = now; true when _anomalyStartTime is null => now,
} false => null,
else if (!isAnomaly) _ => _anomalyStartTime
{ };
_anomalyStartTime = null;
}
var anomalyDuration = _anomalyStartTime.HasValue var anomalyDuration = _anomalyStartTime.HasValue
? now - _anomalyStartTime.Value ? now - _anomalyStartTime.Value
@@ -288,8 +301,11 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
_enforcementService.EnforceLimit(calculation.TotalPowerWatts); _enforcementService.EnforceLimit(calculation.TotalPowerWatts);
_logger.LogDebug("Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", if (_logger.IsEnabled(LogLevel.Debug))
calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, effectivePrice); {
_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) catch (Exception ex)
{ {
@@ -312,7 +328,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
return price; 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; return 0;
} }
@@ -321,15 +340,17 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
{ {
var isAboveThreshold = totalPowerWatts > _options.HighPowerThresholdWatts; var isAboveThreshold = totalPowerWatts > _options.HighPowerThresholdWatts;
if (isAboveThreshold && !_highPowerNotificationActive) switch (isAboveThreshold, _highPowerNotificationActive)
{ {
_notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); case (true, false):
_highPowerNotificationActive = true; _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts);
} _highPowerNotificationActive = true;
else if (!isAboveThreshold && _highPowerNotificationActive) break;
{
_notificationService.DismissHighPowerNotification(); case (false, true):
_highPowerNotificationActive = false; _notificationService.DismissHighPowerNotification();
_highPowerNotificationActive = false;
break;
} }
} }
@@ -1,19 +1,13 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using PowerMonitorManager.Interface; using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
namespace PowerMonitorManager; namespace PowerMonitorManager;
public static class PowerMonitorServiceRegistration 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<PowerMonitorOptions>() ?? new PowerMonitorOptions();
services services
.AddNetDaemonApp<PowerMonitorInit>() .AddNetDaemonApp<PowerMonitorInit>()
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>() .AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
@@ -30,9 +30,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
_haContext = haContext; _haContext = haContext;
_options = options.Value; _options = options.Value;
_logger = logger; _logger = logger;
_exclusionPatterns = _options.ExcludedSensorPatterns _exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)];
.Select(GlobToRegex)
.ToArray();
} }
public IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors() public IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors()
@@ -54,13 +52,16 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
_currentDeviceSensors = powerSensors; _currentDeviceSensors = powerSensors;
_logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", if (_logger.IsEnabled(LogLevel.Information))
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); {
_logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
}
return powerSensors; return powerSensors;
} }
internal bool IsPowerSensor(Entity entity) internal static bool IsPowerSensor(Entity entity)
{ {
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase)) if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase))
{ {
+3 -3
View File
@@ -5,9 +5,9 @@ namespace PowerMonitor.Models;
public class PowerMonitorEntity : EntityCreateModel public class PowerMonitorEntity : EntityCreateModel
{ {
public string Domain { get; set; } public string Domain { get; }
public string Identifier { get; set; } public string Identifier { get; }
public string Name { get; set; } public string Name { get; }
public PowerMonitorEntity(string domain, string identifier, string name) public PowerMonitorEntity(string domain, string identifier, string name)
{ {
@@ -38,6 +38,10 @@ public sealed class ExhaustFanControlService(
case ShowerState.Idle: case ShowerState.Idle:
EvaluatePostShowerFanOff(timestamp); EvaluatePostShowerFanOff(timestamp);
break; break;
default:
// Unknown state: leave the fan untouched.
break;
} }
} }
} }
@@ -5,7 +5,6 @@ namespace ShowerMonitorManager.Interface;
public interface IShowerDetectionService public interface IShowerDetectionService
{ {
ShowerState CurrentState { get; }
ShowerSession? CurrentSession { get; } ShowerSession? CurrentSession { get; }
ShowerSession? LastCompletedSession { get; } ShowerSession? LastCompletedSession { get; }
int TodaySessionCount { get; } int TodaySessionCount { get; }
@@ -1,7 +0,0 @@
namespace ShowerMonitorManager.Interface;
public interface IShowerMonitorInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -6,11 +6,8 @@ namespace ShowerMonitorManager.Models;
public sealed class ShowerMonitorUpdateContext public sealed class ShowerMonitorUpdateContext
{ {
public required ShowerState State { get; init; } 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 Differential { get; init; }
public required double HumidityRate { get; init; } public required double HumidityRate { get; init; }
public required int TodaySessionCount { get; init; } public required int TodaySessionCount { get; init; }
public ShowerSession? LastCompletedSession { get; init; } public ShowerSession? LastCompletedSession { get; init; }
public ShowerSession? CurrentSession { get; init; }
} }
+36 -31
View File
@@ -80,21 +80,24 @@ public sealed class ShowerDetectionService(
private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp) private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp)
{ {
if (rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity) var showerSuspected = rate >= _options.SpikeRateThreshold
{ && differential >= _options.MinDifferentialHumidity;
_suspectedSince = timestamp;
_currentSession = new ShowerSession
{
StartTime = timestamp,
PreEventHumidity = rateCalculator.PreviousReading ?? humidity,
PeakHumidity = humidity,
PeakTime = timestamp
};
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) 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); var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes);
if (_suspectedSince.HasValue && (timestamp - _suspectedSince.Value) >= confirmationWindow if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow
&& humidity >= _options.PeakHumidityThreshold && humidity >= _options.PeakHumidityThreshold
&& differential >= _options.MinDifferentialHumidity) && differential >= _options.MinDifferentialHumidity)
{ {
return ShowerState.Active; return ShowerState.Active;
} }
if (rate < 0 && differential < _options.MinDifferentialHumidity) var showerAbandoned = rate < 0 && differential < _options.MinDifferentialHumidity;
if (!showerAbandoned)
{ {
CompleteSessionCleanup(); return ShowerState.Suspected;
return ShowerState.Idle;
} }
return ShowerState.Suspected; CompleteSessionCleanup();
return ShowerState.Idle;
} }
private ShowerState EvaluateActive(double rate, double differential, double humidity, DateTimeOffset timestamp) 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 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) if (maxDurationReached || humidityRecovered)
{
return TransitionToDeclining();
}
if (rate < 0 && differential < _options.MinDifferentialHumidity)
{ {
return TransitionToDeclining(); return TransitionToDeclining();
} }
@@ -151,23 +154,25 @@ public sealed class ShowerDetectionService(
if (differential <= _options.RecoveryDifferentialThreshold) if (differential <= _options.RecoveryDifferentialThreshold)
{ {
CompleteSession(timestamp); CompleteSession(timestamp);
return ShowerState.Completed; return ShowerState.Completed;
} }
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); 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.Declining;
return ShowerState.Completed;
} }
return ShowerState.Declining; CompleteSession(timestamp);
return ShowerState.Completed;
} }
private ShowerState TransitionToDeclining() private static ShowerState TransitionToDeclining()
{ {
return ShowerState.Declining; return ShowerState.Declining;
} }
+13 -14
View File
@@ -13,7 +13,7 @@ using static ShowerMonitor.Models.ShowerMonitorConsts;
namespace ShowerMonitorManager; namespace ShowerMonitorManager;
[NetDaemonApp] [NetDaemonApp]
public sealed class ShowerMonitorInit : IShowerMonitorInit public sealed class ShowerMonitorInit
{ {
private readonly ILogger<ShowerMonitorInit> _logger; private readonly ILogger<ShowerMonitorInit> _logger;
private readonly IHaContext _haContext; private readonly IHaContext _haContext;
@@ -63,7 +63,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
} }
} }
public async Task InitializeAsync() private async Task InitializeAsync()
{ {
try try
{ {
@@ -88,11 +88,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
} }
} }
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void SchedulePeriodicPolling() private void SchedulePeriodicPolling()
{ {
var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds); var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds);
@@ -162,7 +157,11 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue) 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; return;
} }
@@ -175,19 +174,19 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
var context = new ShowerMonitorUpdateContext var context = new ShowerMonitorUpdateContext
{ {
State = state, State = state,
BathroomHumidity = bathroomHumidity.Value,
MainHomeHumidity = mainHomeHumidity.Value,
Differential = differential, Differential = differential,
HumidityRate = _detectionService.LastRate, HumidityRate = _detectionService.LastRate,
TodaySessionCount = _detectionService.TodaySessionCount, TodaySessionCount = _detectionService.TodaySessionCount,
LastCompletedSession = _detectionService.LastCompletedSession, LastCompletedSession = _detectionService.LastCompletedSession
CurrentSession = _detectionService.CurrentSession
}; };
await _entityService.UpdateEntitiesAsync(context); await _entityService.UpdateEntitiesAsync(context);
_logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}", if (_logger.IsEnabled(LogLevel.Debug))
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state); {
_logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}",
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
+3 -3
View File
@@ -5,9 +5,9 @@ namespace ShowerMonitor.Models;
public class ShowerMonitorEntity : EntityCreateModel public class ShowerMonitorEntity : EntityCreateModel
{ {
public string Domain { get; set; } private string Domain { get; }
public string Identifier { get; set; } private string Identifier { get; }
public string Name { get; set; } private string Name { get; }
public ShowerMonitorEntity(string domain, string identifier, string name) public ShowerMonitorEntity(string domain, string identifier, string name)
{ {
+3 -1
View File
@@ -70,7 +70,9 @@ exclude:
# testCoverageThresholds - configures minimum code coverage on a whole project and newly added code # testCoverageThresholds - configures minimum code coverage on a whole project and newly added code
# dependencyLicenses - fails the run on prohibited or unknown dependency licenses # dependencyLicenses - fails the run on prohibited or unknown dependency licenses
# Code Coverage is available in Ultimate and Ultimate Plus plans # Code Coverage is available in Ultimate and Ultimate Plus plans
#failureConditions: failureConditions:
severityThresholds:
any: 0
# severityThresholds: # severityThresholds:
# any: 15 # any: 15
# critical: 5 # critical: 5