Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests - Expand single-statement guards and loops into braced blocks - Realign wrapped method arguments, chained calls and continuations - Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty` - Flatten the boiler config expression and reindent the remaining touched files
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using BoilerMonitor.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -5,6 +7,8 @@ using NetDaemon.HassModel;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
using static NordPool.Models.NordPoolConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
||||
@@ -14,15 +18,20 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
||||
public BoilerConfig ReadConfig()
|
||||
{
|
||||
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
||||
|
||||
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
|
||||
? dh
|
||||
: DefaultDailyHours;
|
||||
? dh
|
||||
: DefaultDailyHours;
|
||||
|
||||
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
||||
|
||||
if (intervalCount <= 0) intervalCount = IntervalsPerHour;
|
||||
if (intervalCount <= 0)
|
||||
{
|
||||
intervalCount = IntervalsPerHour;
|
||||
}
|
||||
|
||||
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
||||
|
||||
var priceCap =
|
||||
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
|
||||
? pc
|
||||
@@ -43,8 +52,8 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||
intervalCount, priceCap, skipPriceCap, deadline);
|
||||
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||
intervalCount, priceCap, skipPriceCap, deadline);
|
||||
}
|
||||
|
||||
var config = new BoilerConfig
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models.Enums;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
||||
@@ -25,8 +29,8 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||
currentSwitchState);
|
||||
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||
currentSwitchState);
|
||||
}
|
||||
|
||||
return BoilerAction.TurnOn;
|
||||
@@ -38,7 +42,7 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason,
|
||||
currentSwitchState);
|
||||
currentSwitchState);
|
||||
}
|
||||
|
||||
return BoilerAction.TurnOff;
|
||||
@@ -48,8 +52,8 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||
}
|
||||
|
||||
return BoilerAction.NoChange;
|
||||
@@ -58,10 +62,13 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
||||
|
||||
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
|
||||
{
|
||||
if (waterReady) return "water is already ready";
|
||||
if (waterReady)
|
||||
{
|
||||
return "water is already ready";
|
||||
}
|
||||
|
||||
return effectiveBudgetExhausted
|
||||
? "daily budget is exhausted"
|
||||
: "not in a cheap interval";
|
||||
? "daily budget is exhausted"
|
||||
: "not in a cheap interval";
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using BoilerMonitor.Models;
|
||||
@@ -9,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager;
|
||||
using NetDaemon.HassModel;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class BoilerMonitorEntityService(
|
||||
@@ -41,21 +45,21 @@ public sealed class BoilerMonitorEntityService(
|
||||
var entities = GetAllEntities();
|
||||
|
||||
var createTasks = entities.Select(async entity =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
{
|
||||
try
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(createTasks).ConfigureAwait(false);
|
||||
}
|
||||
@@ -67,17 +71,18 @@ public sealed class BoilerMonitorEntityService(
|
||||
logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults");
|
||||
|
||||
await Task.WhenAll(
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync(),
|
||||
ResetSkipPriceCapAsync(),
|
||||
ResetTodayRuntimeAsync(),
|
||||
ResetRemainingTimeAsync(),
|
||||
ResetBudgetPercentageAsync(),
|
||||
ResetBudgetExhaustedAsync(),
|
||||
ResetSessionCountAsync(),
|
||||
ResetBudgetOverrideAsync(),
|
||||
ResetAutoManagementAsync()
|
||||
).ConfigureAwait(false);
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync(),
|
||||
ResetSkipPriceCapAsync(),
|
||||
ResetTodayRuntimeAsync(),
|
||||
ResetRemainingTimeAsync(),
|
||||
ResetBudgetPercentageAsync(),
|
||||
ResetBudgetExhaustedAsync(),
|
||||
ResetSessionCountAsync(),
|
||||
ResetBudgetOverrideAsync(),
|
||||
ResetAutoManagementAsync()
|
||||
)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
||||
}
|
||||
@@ -118,6 +123,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -129,9 +135,10 @@ public sealed class BoilerMonitorEntityService(
|
||||
logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)");
|
||||
|
||||
await Task.WhenAll(
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync()
|
||||
).ConfigureAwait(false);
|
||||
ResetStatusAsync(),
|
||||
ResetWaterReadyAsync()
|
||||
)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public PersistedBoilerState? ReadPersistedState()
|
||||
@@ -149,8 +156,8 @@ public sealed class BoilerMonitorEntityService(
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||
runtimeState, sessionCountState);
|
||||
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||
runtimeState, sessionCountState);
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -167,9 +174,9 @@ public sealed class BoilerMonitorEntityService(
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||
persisted.BudgetOverrideState);
|
||||
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||
persisted.BudgetOverrideState);
|
||||
}
|
||||
|
||||
return persisted;
|
||||
@@ -177,6 +184,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -191,9 +199,16 @@ public sealed class BoilerMonitorEntityService(
|
||||
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;
|
||||
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
|
||||
{
|
||||
@@ -205,7 +220,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
|
||||
if (stringValue is not null &&
|
||||
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out var parsed))
|
||||
DateTimeStyles.RoundtripKind, out var parsed))
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
@@ -237,10 +252,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
||||
{
|
||||
seconds = 0;
|
||||
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state)
|
||||
&& state is not ("unavailable" or "unknown")
|
||||
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
|
||||
&& seconds >= 0;
|
||||
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
|
||||
|
||||
return tryParseEntitySeconds;
|
||||
}
|
||||
@@ -248,10 +260,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
private static bool TryParseEntityInt(string? state, out int value)
|
||||
{
|
||||
value = 0;
|
||||
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state)
|
||||
&& state is not ("unavailable" or "unknown")
|
||||
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
|
||||
&& value >= 0;
|
||||
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
|
||||
|
||||
return tryParseEntityInt;
|
||||
}
|
||||
@@ -283,7 +292,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
}
|
||||
},
|
||||
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
|
||||
"Heating power threshold (watts)")
|
||||
"Heating power threshold (watts)")
|
||||
{
|
||||
AdditionalConfig = new
|
||||
{
|
||||
@@ -362,14 +371,16 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task ResetWaterReadyAsync()
|
||||
{
|
||||
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||
{
|
||||
boiler_switch_state = "unknown",
|
||||
boiler_power_watts = 0.0,
|
||||
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
boiler_switch_state = "unknown",
|
||||
boiler_power_watts = 0.0,
|
||||
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetSkipPriceCapAsync()
|
||||
@@ -380,35 +391,41 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task ResetTodayRuntimeAsync()
|
||||
{
|
||||
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetRemainingTimeAsync()
|
||||
{
|
||||
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
budget_hours = 0.0,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted = "0h 0m",
|
||||
budget_hours = 0.0,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetBudgetPercentageAsync()
|
||||
{
|
||||
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetBudgetExhaustedAsync()
|
||||
@@ -419,11 +436,13 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task ResetSessionCountAsync()
|
||||
{
|
||||
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = (string?)null
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = (string?)null
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ResetBudgetOverrideAsync()
|
||||
@@ -439,54 +458,68 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||
{
|
||||
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
||||
friendly_name = "Boiler water ready",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(TodayRuntimeEntityId,
|
||||
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||
{
|
||||
formatted,
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted,
|
||||
friendly_name = "Today runtime",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours,
|
||||
string timestamp)
|
||||
private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
|
||||
string formatted,
|
||||
double budgetHours,
|
||||
string timestamp)
|
||||
{
|
||||
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
||||
|
||||
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||
{
|
||||
formatted,
|
||||
budget_hours = budgetHours,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
formatted,
|
||||
budget_hours = budgetHours,
|
||||
friendly_name = "Remaining budget time",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
||||
{
|
||||
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
||||
|
||||
await SetEntityStateSafe(BudgetPercentageEntityId,
|
||||
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
unit_of_measurement = "%",
|
||||
friendly_name = "Budget usage",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
||||
@@ -497,12 +530,14 @@ public sealed class BoilerMonitorEntityService(
|
||||
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
|
||||
.ConfigureAwait(false);
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = timestamp
|
||||
}).ConfigureAwait(false);
|
||||
{
|
||||
friendly_name = "Heating sessions today",
|
||||
last_updated = timestamp
|
||||
})
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task SetEntityStateSafe(string entityId, string state)
|
||||
@@ -510,6 +545,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
||||
@@ -526,6 +562,7 @@ public sealed class BoilerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using System.Reactive.Concurrency;
|
||||
using System.Text.Json;
|
||||
@@ -13,6 +15,8 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
@@ -45,17 +49,17 @@ public sealed class BoilerMonitorInit
|
||||
IOptions<BoilerMonitorOptions> options,
|
||||
TimeProvider timeProvider)
|
||||
: this(
|
||||
haContext,
|
||||
logger,
|
||||
scheduler,
|
||||
mqttEntityManager,
|
||||
boilerControlService,
|
||||
tracker,
|
||||
entityService,
|
||||
waterReadyService,
|
||||
options,
|
||||
timeProvider,
|
||||
true)
|
||||
haContext,
|
||||
logger,
|
||||
scheduler,
|
||||
mqttEntityManager,
|
||||
boilerControlService,
|
||||
tracker,
|
||||
entityService,
|
||||
waterReadyService,
|
||||
options,
|
||||
timeProvider,
|
||||
true)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -83,7 +87,10 @@ public sealed class BoilerMonitorInit
|
||||
_options = options.Value;
|
||||
_timeProvider = timeProvider;
|
||||
|
||||
if (startBackgroundScheduling) _ = InitializeAndScheduleAsync();
|
||||
if (startBackgroundScheduling)
|
||||
{
|
||||
_ = InitializeAndScheduleAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task InitializeAndScheduleAsync()
|
||||
@@ -130,14 +137,18 @@ public sealed class BoilerMonitorInit
|
||||
{
|
||||
_tracker.RestoreFromSnapshot();
|
||||
|
||||
if (persistedCooldown.HasValue) _waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||
if (persistedCooldown.HasValue)
|
||||
{
|
||||
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||
}
|
||||
|
||||
await _entityService.ResetTransientEntitiesAsync();
|
||||
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -156,6 +167,7 @@ public sealed class BoilerMonitorInit
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -171,105 +183,126 @@ public sealed class BoilerMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
|
||||
DefaultPollIntervalSeconds, nextPollTime);
|
||||
DefaultPollIntervalSeconds, nextPollTime);
|
||||
}
|
||||
|
||||
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
|
||||
() => _ = PollAndUpdateAsync());
|
||||
() => _ = PollAndUpdateAsync());
|
||||
}
|
||||
|
||||
private void ScheduleMidnightReset()
|
||||
{
|
||||
_scheduler.ScheduleCron("0 0 * * *", () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||
_tracker.Reset();
|
||||
_waterReadyService.ResetCooldown();
|
||||
_lastWaterReadyNotificationSentAt = null;
|
||||
_ = _entityService.ResetEntitiesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during midnight reset");
|
||||
}
|
||||
});
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||
_tracker.Reset();
|
||||
_waterReadyService.ResetCooldown();
|
||||
_lastWaterReadyNotificationSentAt = null;
|
||||
_ = _entityService.ResetEntitiesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during midnight reset");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ScheduleEndOfDayReminder()
|
||||
{
|
||||
_scheduler.ScheduleCron("0 22 * * *", () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return;
|
||||
{
|
||||
try
|
||||
{
|
||||
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||
|
||||
_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)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||
}
|
||||
});
|
||||
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
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)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToSkipPriceCapChanges()
|
||||
{
|
||||
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
||||
skipPriceCapSwitch.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State) return;
|
||||
|
||||
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
skipPriceCapSwitch.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
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;
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_waterReadyService.IsInCooldown) return;
|
||||
if (!_waterReadyService.IsInCooldown)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
|
||||
_waterReadyService.ResetCooldown();
|
||||
});
|
||||
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
|
||||
_waterReadyService.ResetCooldown();
|
||||
});
|
||||
}
|
||||
|
||||
private void SubscribeToCleanupButton()
|
||||
{
|
||||
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
||||
|
||||
cleanupButton.StateChanges()
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
|
||||
Task.Run(HandleCleanupAsync);
|
||||
});
|
||||
.Subscribe(_ =>
|
||||
{
|
||||
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
|
||||
Task.Run(HandleCleanupAsync);
|
||||
});
|
||||
}
|
||||
|
||||
private async Task SubscribeToConfigCommandsAsync()
|
||||
@@ -359,6 +392,7 @@ public sealed class BoilerMonitorInit
|
||||
if (_cleanedUp)
|
||||
{
|
||||
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -369,21 +403,27 @@ public sealed class BoilerMonitorInit
|
||||
if (!config.IsFullyConfigured)
|
||||
{
|
||||
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
||||
|
||||
_logger.LogWarning(
|
||||
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
||||
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
||||
|
||||
var isHeating = boilerPowerWatts.HasValue &&
|
||||
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
||||
|
||||
_tracker.RecordPollResult();
|
||||
|
||||
if (isHeating) _waterReadyService.RecordHeatingObserved();
|
||||
if (isHeating)
|
||||
{
|
||||
_waterReadyService.RecordHeatingObserved();
|
||||
}
|
||||
|
||||
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
||||
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
||||
@@ -397,7 +437,7 @@ public sealed class BoilerMonitorInit
|
||||
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
||||
|
||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
|
||||
config.HeatingPowerThresholdWatts!.Value);
|
||||
config.HeatingPowerThresholdWatts!.Value);
|
||||
|
||||
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
||||
{
|
||||
@@ -406,6 +446,7 @@ public sealed class BoilerMonitorInit
|
||||
message = "Hot water is ready.",
|
||||
title = "Boiler"
|
||||
});
|
||||
|
||||
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
||||
_logger.LogInformation("Water ready notification sent");
|
||||
}
|
||||
@@ -416,24 +457,28 @@ public sealed class BoilerMonitorInit
|
||||
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
||||
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
|
||||
|
||||
if (remainingTime < TimeSpan.Zero) remainingTime = TimeSpan.Zero;
|
||||
if (remainingTime < TimeSpan.Zero)
|
||||
{
|
||||
remainingTime = TimeSpan.Zero;
|
||||
}
|
||||
|
||||
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
||||
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
|
||||
: 0.0;
|
||||
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
|
||||
: 0.0;
|
||||
|
||||
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
||||
|
||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||
|
||||
var boilerAction = _boilerControlService.DetermineAction(
|
||||
effectiveIsNowCheap,
|
||||
waterReady,
|
||||
boilerSwitchState,
|
||||
budgetExhausted,
|
||||
budgetOverride);
|
||||
effectiveIsNowCheap,
|
||||
waterReady,
|
||||
boilerSwitchState,
|
||||
budgetExhausted,
|
||||
budgetOverride);
|
||||
|
||||
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
||||
|
||||
var autoManagementEnabled =
|
||||
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
@@ -468,8 +513,8 @@ public sealed class BoilerMonitorInit
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -485,12 +530,17 @@ public sealed class BoilerMonitorInit
|
||||
case BoilerAction.TurnOn:
|
||||
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
||||
_waterReadyService.NotifyTurnedOn();
|
||||
|
||||
break;
|
||||
|
||||
case BoilerAction.TurnOff:
|
||||
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
||||
|
||||
break;
|
||||
|
||||
case BoilerAction.NoChange:
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
||||
}
|
||||
@@ -504,9 +554,7 @@ public sealed class BoilerMonitorInit
|
||||
int? pollInterval = null;
|
||||
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(pollIntervalState)
|
||||
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
|
||||
&& pollIntervalValue > 0)
|
||||
if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
|
||||
{
|
||||
pollInterval = (int)pollIntervalValue;
|
||||
}
|
||||
@@ -514,9 +562,7 @@ public sealed class BoilerMonitorInit
|
||||
double? heatingThreshold = null;
|
||||
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(thresholdState)
|
||||
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
|
||||
&& thresholdValue > 0)
|
||||
if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
|
||||
{
|
||||
heatingThreshold = thresholdValue;
|
||||
}
|
||||
@@ -534,14 +580,20 @@ public sealed class BoilerMonitorInit
|
||||
{
|
||||
var state = _haContext.GetState(entityId);
|
||||
|
||||
if (state?.State is null or "unavailable" or "unknown") return null;
|
||||
if (state?.State is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
|
||||
}
|
||||
|
||||
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
||||
{
|
||||
if (entityState?.Attributes is not IDictionary<string, object> attributes) return false;
|
||||
if (entityState?.Attributes is not IDictionary<string, object> attributes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
@@ -569,9 +621,13 @@ public sealed class BoilerMonitorInit
|
||||
|
||||
private bool IsWithinNotificationCooldown()
|
||||
{
|
||||
if (_lastWaterReadyNotificationSentAt is null) return false;
|
||||
if (_lastWaterReadyNotificationSentAt is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
||||
|
||||
return elapsed < WaterReadyNotificationCooldown;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Interface;
|
||||
using BoilerMonitorManager.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public static class BoilerMonitorServiceRegistration
|
||||
@@ -11,17 +15,21 @@ public static class BoilerMonitorServiceRegistration
|
||||
public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var options = configuration
|
||||
.GetSection(BoilerMonitorOptions.SectionName)
|
||||
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
||||
.GetSection(BoilerMonitorOptions.SectionName)
|
||||
.Get<BoilerMonitorOptions>() ??
|
||||
new BoilerMonitorOptions();
|
||||
|
||||
if (!options.Enabled) return services;
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
}
|
||||
|
||||
services
|
||||
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Interface;
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models.Enums;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager.Interface;
|
||||
|
||||
public interface IBoilerControlService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager.Interface;
|
||||
|
||||
public interface IBoilerMonitorEntityService
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager.Interface;
|
||||
|
||||
public interface IBoilerRunTimeTracker
|
||||
|
||||
@@ -7,9 +7,8 @@ public record BoilerMonitorConfig
|
||||
public int? PollIntervalSeconds { get; init; }
|
||||
public double? HeatingPowerThresholdWatts { get; init; }
|
||||
|
||||
public bool IsFullyConfigured =>
|
||||
!string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||
PollIntervalSeconds is > 0 &&
|
||||
HeatingPowerThresholdWatts is > 0;
|
||||
public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||
PollIntervalSeconds is > 0 &&
|
||||
HeatingPowerThresholdWatts is > 0;
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitorManager;
|
||||
|
||||
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
||||
{
|
||||
private const string SwitchOnState = "on";
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Lock _lock = new Lock();
|
||||
private int _consecutiveBelowThresholdCount;
|
||||
private bool _hasObservedHeating;
|
||||
private DateTimeOffset? _waterReadySince;
|
||||
@@ -43,16 +47,22 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
|
||||
_waterReadySince);
|
||||
_waterReadySince);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (switchState is null || powerWatts is null) return false;
|
||||
if (switchState is null || powerWatts is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
@@ -61,7 +71,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
||||
powerWatts.Value);
|
||||
powerWatts.Value);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -70,6 +80,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (powerWatts.Value >= heatingThresholdWatts)
|
||||
{
|
||||
_consecutiveBelowThresholdCount = 0;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -80,9 +91,9 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
||||
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
||||
powerWatts.Value);
|
||||
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
||||
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
||||
powerWatts.Value);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -93,8 +104,8 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||
_consecutiveBelowThresholdCount);
|
||||
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||
_consecutiveBelowThresholdCount);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -110,14 +121,17 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
}
|
||||
|
||||
logger.LogDebug(
|
||||
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
||||
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
||||
}
|
||||
|
||||
public void RecordHeatingObserved()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_hasObservedHeating) return;
|
||||
if (_hasObservedHeating)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_hasObservedHeating = true;
|
||||
}
|
||||
@@ -141,18 +155,20 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
||||
lock (_lock)
|
||||
{
|
||||
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
||||
|
||||
if (waterReadySince < todayMidnightUtc)
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
|
||||
waterReadySince);
|
||||
waterReadySince);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_waterReadySince = waterReadySince;
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
||||
|
||||
Reference in New Issue
Block a user