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