Update
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user