Update
This commit is contained in:
@@ -8,7 +8,12 @@ public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoile
|
||||
{
|
||||
private const string SwitchOnState = "on";
|
||||
|
||||
public BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride)
|
||||
public BoilerAction DetermineAction(
|
||||
bool isNowCheap,
|
||||
bool waterReady,
|
||||
string? currentSwitchState,
|
||||
bool budgetExhausted,
|
||||
bool budgetOverride)
|
||||
{
|
||||
var isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
|
||||
@@ -16,7 +21,9 @@ public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoile
|
||||
|
||||
if (shouldBeOn && !isCurrentlyOn)
|
||||
{
|
||||
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
|
||||
logger.LogInformation(
|
||||
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||
currentSwitchState);
|
||||
|
||||
return BoilerAction.TurnOn;
|
||||
}
|
||||
@@ -30,8 +37,12 @@ public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoile
|
||||
return BoilerAction.TurnOff;
|
||||
}
|
||||
|
||||
logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||
logger.LogDebug(
|
||||
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||
currentSwitchState,
|
||||
isNowCheap,
|
||||
waterReady,
|
||||
effectiveBudgetExhausted);
|
||||
|
||||
return BoilerAction.NoChange;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -29,7 +29,8 @@ public sealed class BoilerMonitorEntityService(
|
||||
BudgetPercentageEntityId,
|
||||
BudgetExhaustedEntityId,
|
||||
SessionCountEntityId,
|
||||
BudgetOverrideEntityId
|
||||
BudgetOverrideEntityId,
|
||||
AutoManagementEntityId
|
||||
];
|
||||
|
||||
private static object CreateDeviceBlock() => new
|
||||
@@ -77,7 +78,8 @@ public sealed class BoilerMonitorEntityService(
|
||||
ResetBudgetPercentageAsync(),
|
||||
ResetBudgetExhaustedAsync(),
|
||||
ResetSessionCountAsync(),
|
||||
ResetBudgetOverrideAsync()
|
||||
ResetBudgetOverrideAsync(),
|
||||
ResetAutoManagementAsync()
|
||||
).ConfigureAwait(false);
|
||||
|
||||
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
||||
@@ -280,6 +282,10 @@ public sealed class BoilerMonitorEntityService(
|
||||
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
|
||||
{
|
||||
AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device }
|
||||
},
|
||||
new BoilerMonitorEntity("switch", "boilermonitor_auto_management", "Automatic boiler control")
|
||||
{
|
||||
AdditionalConfig = new { optimistic = true, icon = "mdi:robot-outline", device }
|
||||
}
|
||||
];
|
||||
}
|
||||
@@ -366,6 +372,11 @@ public sealed class BoilerMonitorEntityService(
|
||||
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetAutoManagementAsync()
|
||||
{
|
||||
await SetEntityStateSafe(AutoManagementEntityId, "ON").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
||||
@@ -373,6 +384,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
{
|
||||
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||
cooldown_since = ctx.CooldownSince?.ToString("O"),
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
@@ -429,6 +441,45 @@ public sealed class BoilerMonitorEntityService(
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public DateTimeOffset? ReadPersistedCooldownTimestamp()
|
||||
{
|
||||
try
|
||||
{
|
||||
var entity = haContext.GetState(WaterReadyEntityId);
|
||||
if (entity?.Attributes is not IDictionary<string, object> attributes)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!attributes.TryGetValue("cooldown_since", out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var stringValue = value switch
|
||||
{
|
||||
string s => s,
|
||||
System.Text.Json.JsonElement { ValueKind: System.Text.Json.JsonValueKind.String } jsonElement =>
|
||||
jsonElement.GetString(),
|
||||
_ => null
|
||||
};
|
||||
|
||||
if (stringValue is not null &&
|
||||
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out var parsed))
|
||||
{
|
||||
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error reading persisted cooldown timestamp");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task SetEntityStateSafe(string entityId, string state)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Reactive.Concurrency;
|
||||
using System.Text.Json;
|
||||
using BoilerMonitor.Models;
|
||||
using BoilerMonitor.Models.Enums;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using BoilerMonitorManager.Models;
|
||||
@@ -27,8 +29,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
private readonly IWaterReadyService _waterReadyService;
|
||||
private readonly BoilerMonitorOptions _options;
|
||||
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private bool _lastWaterReady;
|
||||
private bool _cleanedUp;
|
||||
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
|
||||
|
||||
public BoilerMonitorInit(
|
||||
IHaContext haContext,
|
||||
@@ -39,7 +43,35 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
IBoilerRunTimeTracker tracker,
|
||||
IBoilerMonitorEntityService entityService,
|
||||
IWaterReadyService waterReadyService,
|
||||
IOptions<BoilerMonitorOptions> options)
|
||||
IOptions<BoilerMonitorOptions> options,
|
||||
TimeProvider timeProvider)
|
||||
: this(
|
||||
haContext,
|
||||
logger,
|
||||
scheduler,
|
||||
mqttEntityManager,
|
||||
boilerControlService,
|
||||
tracker,
|
||||
entityService,
|
||||
waterReadyService,
|
||||
options,
|
||||
timeProvider,
|
||||
startBackgroundScheduling: true)
|
||||
{
|
||||
}
|
||||
|
||||
internal BoilerMonitorInit(
|
||||
IHaContext haContext,
|
||||
ILogger<BoilerMonitorInit> logger,
|
||||
IScheduler scheduler,
|
||||
IMqttEntityManager mqttEntityManager,
|
||||
IBoilerControlService boilerControlService,
|
||||
IBoilerRunTimeTracker tracker,
|
||||
IBoilerMonitorEntityService entityService,
|
||||
IWaterReadyService waterReadyService,
|
||||
IOptions<BoilerMonitorOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
bool startBackgroundScheduling)
|
||||
{
|
||||
_haContext = haContext;
|
||||
_logger = logger;
|
||||
@@ -50,8 +82,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
_entityService = entityService;
|
||||
_waterReadyService = waterReadyService;
|
||||
_options = options.Value;
|
||||
_timeProvider = timeProvider;
|
||||
|
||||
_ = InitializeAndScheduleAsync();
|
||||
if (startBackgroundScheduling)
|
||||
{
|
||||
_ = InitializeAndScheduleAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task InitializeAndScheduleAsync()
|
||||
@@ -65,6 +101,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
ScheduleMidnightReset();
|
||||
ScheduleEndOfDayReminder();
|
||||
SubscribeToSkipPriceCapChanges();
|
||||
SubscribeToAutoManagementChanges();
|
||||
SubscribeToShowerState();
|
||||
SubscribeToCleanupButton();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -88,11 +126,19 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
else
|
||||
{
|
||||
var persisted = _entityService.ReadPersistedState();
|
||||
var persistedCooldown = _entityService.ReadPersistedCooldownTimestamp();
|
||||
|
||||
await _entityService.CreateEntitiesAsync();
|
||||
|
||||
if (persisted is not null)
|
||||
{
|
||||
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||
|
||||
if (persistedCooldown.HasValue)
|
||||
{
|
||||
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||
}
|
||||
|
||||
await _entityService.ResetTransientEntitiesAsync();
|
||||
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||
@@ -100,7 +146,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
else
|
||||
{
|
||||
await _entityService.ResetEntitiesAsync();
|
||||
_logger.LogInformation("No persisted state found, performing full entity reset");
|
||||
_logger.LogInformation("No persisted state found in HA entities, performing full entity reset");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +200,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||
_tracker.Reset();
|
||||
_waterReadyService.ResetCooldown();
|
||||
_lastWaterReadyNotificationSentAt = null;
|
||||
_ = _entityService.ResetEntitiesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -203,6 +250,43 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToAutoManagementChanges()
|
||||
{
|
||||
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
|
||||
autoManagementSwitch.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToShowerState()
|
||||
{
|
||||
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
|
||||
showerStateSensor.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_waterReadyService.IsInCooldown)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
|
||||
_waterReadyService.ResetCooldown();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToCleanupButton()
|
||||
{
|
||||
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
||||
@@ -247,7 +331,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
var switchEntityIds = new[]
|
||||
{
|
||||
SkipPriceCapEntityId,
|
||||
BudgetOverrideEntityId
|
||||
BudgetOverrideEntityId,
|
||||
AutoManagementEntityId
|
||||
};
|
||||
|
||||
foreach (var entityId in switchEntityIds)
|
||||
@@ -312,6 +397,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
|
||||
_tracker.RecordPollResult(isHeating, pollInterval);
|
||||
|
||||
if (isHeating)
|
||||
{
|
||||
_waterReadyService.RecordHeatingObserved();
|
||||
}
|
||||
|
||||
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
||||
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
||||
var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval");
|
||||
@@ -326,13 +416,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
|
||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
|
||||
|
||||
if (!_lastWaterReady && waterReady)
|
||||
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
||||
{
|
||||
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||
{
|
||||
message = "Hot water is ready.",
|
||||
title = "Boiler"
|
||||
});
|
||||
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
||||
_logger.LogInformation("Water ready notification sent");
|
||||
}
|
||||
_lastWaterReady = waterReady;
|
||||
@@ -354,9 +445,26 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
|
||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||
|
||||
var boilerAction = _boilerControlService.DetermineAction(effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
|
||||
var boilerAction = _boilerControlService.DetermineAction(
|
||||
effectiveIsNowCheap,
|
||||
waterReady,
|
||||
boilerSwitchState,
|
||||
budgetExhausted,
|
||||
budgetOverride);
|
||||
|
||||
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
|
||||
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
||||
var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (autoManagementEnabled)
|
||||
{
|
||||
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
|
||||
}
|
||||
else if (boilerAction is not BoilerAction.NoChange)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
|
||||
boilerAction);
|
||||
}
|
||||
|
||||
var context = new BoilerMonitorUpdateContext
|
||||
{
|
||||
@@ -370,6 +478,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
WaterReady = waterReady,
|
||||
BoilerSwitchState = boilerSwitchState,
|
||||
BoilerPowerWatts = boilerPowerWatts,
|
||||
CooldownSince = _waterReadyService.WaterReadySince,
|
||||
IsNowCheap = effectiveIsNowCheap,
|
||||
NextCheapIntervalStart = nextCheapInterval
|
||||
};
|
||||
@@ -464,6 +573,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
{
|
||||
bool b => b,
|
||||
string s => bool.TryParse(s, out var parsed) && parsed,
|
||||
JsonElement { ValueKind: JsonValueKind.True } => true,
|
||||
JsonElement { ValueKind: JsonValueKind.False } => false,
|
||||
JsonElement jsonElement when jsonElement.ValueKind == JsonValueKind.String =>
|
||||
bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
@@ -476,6 +589,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool IsWithinNotificationCooldown()
|
||||
{
|
||||
if (_lastWaterReadyNotificationSentAt is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
||||
return elapsed < WaterReadyNotificationCooldown;
|
||||
}
|
||||
|
||||
private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName)
|
||||
{
|
||||
if (entityState?.Attributes is null)
|
||||
@@ -487,7 +611,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
||||
{
|
||||
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
|
||||
{
|
||||
if (value is string s && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed))
|
||||
var stringValue = value switch
|
||||
{
|
||||
string s => s,
|
||||
JsonElement { ValueKind: JsonValueKind.String } jsonElement => jsonElement.GetString(),
|
||||
_ => null
|
||||
};
|
||||
|
||||
if (stringValue is not null && DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed))
|
||||
{
|
||||
return parsed;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ public static class BoilerMonitorServiceRegistration
|
||||
.GetSection(BoilerMonitorOptions.SectionName)
|
||||
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
||||
|
||||
// Always register: NordPool and other features resolve boiler tuning from HA entity state
|
||||
// even when the BoilerMonitor app itself is disabled.
|
||||
services.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
|
||||
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
@@ -26,8 +30,7 @@ public static class BoilerMonitorServiceRegistration
|
||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
|
||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||
.AddSingleton(TimeProvider.System)
|
||||
.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
|
||||
.AddSingleton(TimeProvider.System);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -4,5 +4,10 @@ namespace BoilerMonitorManager.Interface;
|
||||
|
||||
public interface IBoilerControlService
|
||||
{
|
||||
BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride);
|
||||
BoilerAction DetermineAction(
|
||||
bool isNowCheap,
|
||||
bool waterReady,
|
||||
string? currentSwitchState,
|
||||
bool budgetExhausted,
|
||||
bool budgetOverride);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using BoilerMonitor.Models;
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
namespace BoilerMonitorManager.Interface;
|
||||
@@ -11,4 +12,5 @@ public interface IBoilerMonitorEntityService
|
||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
Task SetStatusAsync(string status);
|
||||
PersistedBoilerState? ReadPersistedState();
|
||||
DateTimeOffset? ReadPersistedCooldownTimestamp();
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ public interface IWaterReadyService
|
||||
{
|
||||
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
||||
bool IsInCooldown { get; }
|
||||
DateTimeOffset? WaterReadySince { get; }
|
||||
void NotifyTurnedOn();
|
||||
void RecordHeatingObserved();
|
||||
void ResetCooldown();
|
||||
void RestoreCooldownState(DateTimeOffset waterReadySince);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ public record BoilerMonitorUpdateContext
|
||||
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; }
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
{
|
||||
private const string SwitchOnState = "on";
|
||||
private readonly Lock _lock = new();
|
||||
private DateTimeOffset? _lastTurnedOnAt;
|
||||
private DateTimeOffset? _waterReadySince;
|
||||
private bool _hasObservedHeating;
|
||||
private int _consecutiveBelowThresholdCount;
|
||||
|
||||
public bool IsInCooldown
|
||||
{
|
||||
@@ -22,6 +23,17 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
}
|
||||
}
|
||||
|
||||
public DateTimeOffset? WaterReadySince
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _waterReadySince;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts)
|
||||
{
|
||||
lock (_lock)
|
||||
@@ -43,39 +55,68 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
return false;
|
||||
}
|
||||
|
||||
if (IsWithinWarmUpGracePeriod())
|
||||
lock (_lock)
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Ignoring low power reading ({PowerWatts}W) during warm-up grace period",
|
||||
powerWatts.Value);
|
||||
return false;
|
||||
}
|
||||
|
||||
var isReady = powerWatts.Value < heatingThresholdWatts;
|
||||
|
||||
if (isReady)
|
||||
{
|
||||
lock (_lock)
|
||||
if (!_hasObservedHeating)
|
||||
{
|
||||
_waterReadySince ??= timeProvider.GetUtcNow();
|
||||
logger.LogDebug(
|
||||
"Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
||||
powerWatts.Value);
|
||||
return false;
|
||||
}
|
||||
|
||||
logger.LogInformation(
|
||||
"Water detected as ready, cooldown period ({CooldownPeriod}) started",
|
||||
BoilerMonitorConsts.WaterReadyCooldownPeriod);
|
||||
}
|
||||
if (powerWatts.Value >= heatingThresholdWatts)
|
||||
{
|
||||
_consecutiveBelowThresholdCount = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
return isReady;
|
||||
_consecutiveBelowThresholdCount++;
|
||||
|
||||
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
|
||||
{
|
||||
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);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifyTurnedOn()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_lastTurnedOnAt = timeProvider.GetUtcNow();
|
||||
_hasObservedHeating = false;
|
||||
_consecutiveBelowThresholdCount = 0;
|
||||
}
|
||||
|
||||
logger.LogDebug("Boiler turn-on recorded, warm-up grace period started ({GracePeriod})", BoilerMonitorConsts.WarmUpGracePeriod);
|
||||
logger.LogDebug("Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
||||
}
|
||||
|
||||
public void RecordHeatingObserved()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_hasObservedHeating)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_hasObservedHeating = true;
|
||||
}
|
||||
|
||||
logger.LogDebug("Heating observed, water ready detection is now enabled");
|
||||
}
|
||||
|
||||
public void ResetCooldown()
|
||||
@@ -83,33 +124,28 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
lock (_lock)
|
||||
{
|
||||
_waterReadySince = null;
|
||||
_consecutiveBelowThresholdCount = 0;
|
||||
}
|
||||
|
||||
logger.LogInformation("Water ready cooldown has been reset");
|
||||
}
|
||||
|
||||
private bool IsWithinCooldownPeriod()
|
||||
{
|
||||
if (_waterReadySince is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var elapsed = timeProvider.GetUtcNow() - _waterReadySince.Value;
|
||||
return elapsed < BoilerMonitorConsts.WaterReadyCooldownPeriod;
|
||||
}
|
||||
|
||||
private bool IsWithinWarmUpGracePeriod()
|
||||
public void RestoreCooldownState(DateTimeOffset waterReadySince)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_lastTurnedOnAt is null)
|
||||
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
||||
if (waterReadySince < todayMidnightUtc)
|
||||
{
|
||||
return false;
|
||||
logger.LogInformation(
|
||||
"Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince);
|
||||
return;
|
||||
}
|
||||
|
||||
var elapsed = timeProvider.GetUtcNow() - _lastTurnedOnAt.Value;
|
||||
return elapsed < BoilerMonitorConsts.WarmUpGracePeriod;
|
||||
_waterReadySince = waterReadySince;
|
||||
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsWithinCooldownPeriod() => _waterReadySince is not null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user