feat: migrate boiler control implementation to BoilerMonitor namespace and add budget handling logic

This commit is contained in:
Marius
2026-03-24 15:29:59 +02:00
parent c4015277a3
commit 11c2574235
61 changed files with 3250 additions and 728 deletions
@@ -0,0 +1,49 @@
using System.Globalization;
using BoilerMonitor.Models;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts;
using static NordPool.Models.NordPoolConsts;
namespace BoilerMonitorManager;
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
{
private const double DefaultDailyHours = 1.0;
public BoilerConfig ReadConfig()
{
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours;
var intervalCount = (int)(dailyHours * 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 : double.MaxValue;
var deadline = DateTime.Today.AddDays(1);
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime))
{
deadline = DateTime.Today.Add(readyByTime);
}
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);
return new BoilerConfig
{
IntervalCount = intervalCount,
PriceCap = priceCap,
Deadline = deadline,
SkipPriceCap = skipPriceCap
};
}
}
@@ -0,0 +1,53 @@
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface;
using Microsoft.Extensions.Logging;
namespace BoilerMonitorManager;
public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
{
private const string SwitchOnState = "on";
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;
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
if (shouldBeOn && !isCurrentlyOn)
{
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
return BoilerAction.TurnOn;
}
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)
{
if (waterReady)
{
return "water is already ready";
}
if (effectiveBudgetExhausted)
{
return "daily budget is exhausted";
}
return "not in a cheap interval";
}
}
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>BoilerMonitorManager</RootNamespace>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>BoilerMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.2" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,465 @@
using System.Globalization;
using BoilerMonitor.Models;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts;
namespace BoilerMonitorManager;
public sealed class BoilerMonitorEntityService(
IEntityManager entityManager,
IHaContext haContext,
ILogger<BoilerMonitorEntityService> logger) : IBoilerMonitorEntityService
{
private static readonly string[] CleanableEntityIds =
[
ConfigPowerEntityId,
ConfigSwitchEntityId,
ConfigPollIntervalEntityId,
ConfigHeatingThresholdEntityId,
StatusEntityId,
WaterReadyEntityId,
SkipPriceCapEntityId,
TodayRuntimeEntityId,
RemainingTimeEntityId,
BudgetPercentageEntityId,
BudgetExhaustedEntityId,
SessionCountEntityId,
BudgetOverrideEntityId
];
private static object CreateDeviceBlock() => new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var entities = GetAllEntities();
var createTasks = entities.Select(async entity =>
{
try
{
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 Task.WhenAll(createTasks).ConfigureAwait(false);
}
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults");
await Task.WhenAll(
ResetStatusAsync(),
ResetWaterReadyAsync(),
ResetSkipPriceCapAsync(),
ResetTodayRuntimeAsync(),
ResetRemainingTimeAsync(),
ResetBudgetPercentageAsync(),
ResetBudgetExhaustedAsync(),
ResetSessionCountAsync(),
ResetBudgetOverrideAsync()
).ConfigureAwait(false);
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
}
public async Task UpdateEntitiesAsync(BoilerMonitorUpdateContext ctx, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var timestamp = DateTime.UtcNow.ToString("O");
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
// logger.LogInformation("Updating BoilerMonitor entities: runtime={RunTime}, remaining={Remaining}, budget={Budget}%, sessions={Sessions}",
// formattedRunTime, formattedRemaining, ctx.BudgetPercentage, ctx.SessionCount);
var updateTasks = new[]
{
UpdateStatusAsync(StatusConfigured),
UpdateWaterReadyAsync(ctx, timestamp),
UpdateTodayRuntimeAsync(ctx.TodayRunTime, formattedRunTime, timestamp),
UpdateRemainingTimeAsync(ctx.RemainingTime, formattedRemaining, ctx.BudgetHours, timestamp),
UpdateBudgetPercentageAsync(ctx.BudgetPercentage, timestamp),
UpdateBudgetExhaustedAsync(ctx.BudgetExhausted),
UpdateSessionCountAsync(ctx.SessionCount, timestamp)
};
await Task.WhenAll(updateTasks).ConfigureAwait(false);
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
}
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
throw;
}
}
public async Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)");
await Task.WhenAll(
ResetStatusAsync(),
ResetWaterReadyAsync()
).ConfigureAwait(false);
}
public PersistedBoilerState? ReadPersistedState()
{
try
{
var runtimeState = haContext.GetState(TodayRuntimeEntityId)?.State;
var sessionCountState = haContext.GetState(SessionCountEntityId)?.State;
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
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);
return null;
}
var persisted = new PersistedBoilerState
{
AccumulatedRunTime = TimeSpan.FromSeconds(runtimeSeconds),
SessionCount = sessionCount,
SkipPriceCapState = skipPriceCapState,
BudgetOverrideState = budgetOverrideState
};
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
return persisted;
}
catch (Exception ex)
{
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
return null;
}
}
public async Task SetStatusAsync(string status)
{
await UpdateStatusAsync(status).ConfigureAwait(false);
}
private static bool TryParseEntitySeconds(string? state, out double seconds)
{
seconds = 0;
return !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown")
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
&& seconds >= 0;
}
private static bool TryParseEntityInt(string? state, out int value)
{
value = 0;
return !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown")
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
&& value >= 0;
}
private ICollection<BoilerMonitorEntity> GetAllEntities()
{
var device = CreateDeviceBlock();
return
[
new BoilerMonitorEntity("text", "boilermonitor_config_power_entity_id", "Boiler power entity ID")
{
AdditionalConfig = new { icon = "mdi:flash", device }
},
new BoilerMonitorEntity("text", "boilermonitor_config_switch_entity_id", "Boiler switch entity ID")
{
AdditionalConfig = new { icon = "mdi:toggle-switch", device }
},
new BoilerMonitorEntity("number", "boilermonitor_config_poll_interval", "Poll interval (seconds)")
{
AdditionalConfig = new
{
min = (double)MinPollIntervalSeconds,
max = (double)MaxPollIntervalSeconds,
step = (double)PollIntervalStepSeconds,
unit_of_measurement = "s",
icon = "mdi:timer-outline",
device
}
},
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)")
{
AdditionalConfig = new
{
min = MinHeatingThresholdWatts,
max = MaxHeatingThresholdWatts,
step = HeatingThresholdStepWatts,
unit_of_measurement = "W",
icon = "mdi:thermometer",
device
}
},
new BoilerMonitorEntity("button", "boilermonitor_cleanup", "Cleanup all entities")
{
AdditionalConfig = new { icon = "mdi:delete-sweep", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_status", "Boiler Monitor status")
{
AdditionalConfig = new { icon = "mdi:information-outline", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_water_ready", "Boiler water ready")
{
AdditionalConfig = new { icon = "mdi:water-thermometer", device }
},
new BoilerMonitorEntity("switch", "boilermonitor_skip_price_cap", "Skip price cap, heat until ready")
{
AdditionalConfig = new { optimistic = true, icon = "mdi:water-thermometer-outline", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
{
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:percent", device }
},
new BoilerMonitorEntity("binary_sensor", "boilermonitor_budget_exhausted", "Budget exhausted")
{
Options = new EntityCreationOptions
{
UniqueId = BudgetExhaustedEntityId,
Name = "Budget exhausted"
},
AdditionalConfig = new { icon = "mdi:battery-alert", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_session_count", "Heating sessions today")
{
AdditionalConfig = new { icon = "mdi:counter", device }
},
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
{
AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device }
}
];
}
private async Task UpdateStatusAsync(string status)
{
await SetEntityStateSafe(StatusEntityId, status).ConfigureAwait(false);
}
private async Task ResetStatusAsync()
{
await SetEntityStateSafe(StatusEntityId, StatusAwaitingConfiguration).ConfigureAwait(false);
}
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);
}
private async Task ResetSkipPriceCapAsync()
{
await SetEntityStateSafe(SkipPriceCapEntityId, "OFF").ConfigureAwait(false);
}
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);
}
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);
}
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);
}
private async Task ResetBudgetExhaustedAsync()
{
await SetEntityStateSafe(BudgetExhaustedEntityId, "off").ConfigureAwait(false);
}
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);
}
private async Task ResetBudgetOverrideAsync()
{
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
}
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,
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);
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
{
formatted,
friendly_name = "Today runtime",
last_updated = timestamp
}).ConfigureAwait(false);
}
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);
await SetEntityAttributesSafe(RemainingTimeEntityId, new
{
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);
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
{
unit_of_measurement = "%",
friendly_name = "Budget usage",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
{
await SetEntityStateSafe(BudgetExhaustedEntityId, exhausted ? "on" : "off").ConfigureAwait(false);
}
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
{
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(SessionCountEntityId, new
{
friendly_name = "Heating sessions today",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task SetEntityStateSafe(string entityId, string state)
{
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
}
}
private async Task SetEntityAttributesSafe(string entityId, object attributes)
{
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
}
}
private static string FormatTimeSpan(TimeSpan ts)
{
var totalHours = (int)ts.TotalHours;
var minutes = ts.Minutes;
return $"{totalHours}h {minutes}m";
}
}
+503
View File
@@ -0,0 +1,503 @@
using System.Globalization;
using System.Reactive.Concurrency;
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.AppModel;
using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.Extensions.Scheduler;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
namespace BoilerMonitorManager;
[NetDaemonApp]
public sealed class BoilerMonitorInit : IBoilerMonitorInit
{
private readonly ILogger<BoilerMonitorInit> _logger;
private readonly IHaContext _haContext;
private readonly IScheduler _scheduler;
private readonly IMqttEntityManager _mqttEntityManager;
private readonly IBoilerControlService _boilerControlService;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IBoilerMonitorEntityService _entityService;
private readonly IWaterReadyService _waterReadyService;
private readonly BoilerMonitorOptions _options;
private bool _lastWaterReady;
private bool _cleanedUp;
public BoilerMonitorInit(
IHaContext haContext,
ILogger<BoilerMonitorInit> logger,
IScheduler scheduler,
IMqttEntityManager mqttEntityManager,
IBoilerControlService boilerControlService,
IBoilerRunTimeTracker tracker,
IBoilerMonitorEntityService entityService,
IWaterReadyService waterReadyService,
IOptions<BoilerMonitorOptions> options)
{
_haContext = haContext;
_logger = logger;
_scheduler = scheduler;
_mqttEntityManager = mqttEntityManager;
_boilerControlService = boilerControlService;
_tracker = tracker;
_entityService = entityService;
_waterReadyService = waterReadyService;
_options = options.Value;
_ = InitializeAndScheduleAsync();
}
private async Task InitializeAndScheduleAsync()
{
try
{
await InitializeAsync();
await SubscribeToConfigCommandsAsync();
await SubscribeToSwitchCommandsAsync();
SchedulePeriodicPolling();
ScheduleMidnightReset();
ScheduleEndOfDayReminder();
SubscribeToSkipPriceCapChanges();
SubscribeToCleanupButton();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during BoilerMonitor initialization and scheduling");
}
}
public async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3));
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
await _entityService.CreateEntitiesAsync();
await _entityService.ResetEntitiesAsync();
}
else
{
var persisted = _entityService.ReadPersistedState();
await _entityService.CreateEntitiesAsync();
if (persisted is not null)
{
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount);
await _entityService.ResetTransientEntitiesAsync();
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
}
else
{
await _entityService.ResetEntitiesAsync();
_logger.LogInformation("No persisted state found, performing full entity reset");
}
}
await Task.Delay(TimeSpan.FromSeconds(5));
await PollAndUpdateAsync();
_logger.LogInformation("BoilerMonitor initialized");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing BoilerMonitor");
throw;
}
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void SchedulePeriodicPolling()
{
var now = DateTime.Now;
var currentSecondInInterval = (now.Minute * 60 + now.Second) % DefaultPollIntervalSeconds;
var secondsUntilNext = DefaultPollIntervalSeconds - currentSecondInInterval;
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
var nextPollTime = now.Add(delayUntilNext);
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, async void () =>
{
try
{
await PollAndUpdateAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during BoilerMonitor poll cycle");
}
});
}
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();
_ = _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))
{
_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();
});
}
private void SubscribeToCleanupButton()
{
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
cleanupButton.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
Task.Run(HandleCleanupAsync);
});
}
private async Task SubscribeToConfigCommandsAsync()
{
var configEntityIds = new[]
{
ConfigPowerEntityId,
ConfigSwitchEntityId,
ConfigPollIntervalEntityId,
ConfigHeatingThresholdEntityId
};
foreach (var entityId in configEntityIds)
{
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
subscription.Subscribe(async void (state) =>
{
try
{
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogError(e, "Error handling command for entity {EntityId}", entityId);
}
});
}
}
private async Task SubscribeToSwitchCommandsAsync()
{
var switchEntityIds = new[]
{
SkipPriceCapEntityId,
BudgetOverrideEntityId
};
foreach (var entityId in switchEntityIds)
{
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
subscription.Subscribe(async void (state) =>
{
try
{
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId);
}
});
}
}
private async Task HandleCleanupAsync()
{
try
{
await _entityService.CleanupEntitiesAsync();
_cleanedUp = true;
_tracker.Reset();
_logger.LogInformation("BoilerMonitor cleanup complete. Entities removed, monitoring stopped");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during BoilerMonitor cleanup");
}
}
private async Task PollAndUpdateAsync()
{
if (_cleanedUp)
{
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
return;
}
try
{
var config = ReadConfigFromHaEntities();
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);
return;
}
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);
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);
var skipPriceCapState = _haContext.GetState(SkipPriceCapEntityId)?.State;
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
if (!_lastWaterReady && waterReady)
{
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
{
message = "Hot water is ready.",
title = "Boiler"
});
_logger.LogInformation("Water ready notification sent");
}
_lastWaterReady = waterReady;
var snapshot = _tracker.GetSnapshot();
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
if (remainingTime < TimeSpan.Zero)
{
remainingTime = TimeSpan.Zero;
}
var budgetPercentage = budgetTimeSpan.TotalSeconds > 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);
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
var context = new BoilerMonitorUpdateContext
{
TodayRunTime = snapshot.AccumulatedRunTime,
RemainingTime = remainingTime,
BudgetPercentage = budgetPercentage,
BudgetExhausted = budgetExhausted,
SessionCount = snapshot.SessionCount,
BudgetHours = dailyHours,
IsCurrentlyHeating = isHeating,
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts,
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);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
}
}
private void ExecuteBoilerAction(BoilerAction action, string switchEntityId)
{
switch (action)
{
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);
}
}
private BoilerMonitorConfig ReadConfigFromHaEntities()
{
var powerEntityId = _haContext.GetState(ConfigPowerEntityId)?.State;
var switchEntityId = _haContext.GetState(ConfigSwitchEntityId)?.State;
int? pollInterval = null;
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
if (!string.IsNullOrWhiteSpace(pollIntervalState)
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
&& pollIntervalValue > 0)
{
pollInterval = (int)pollIntervalValue;
}
double? heatingThreshold = null;
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
if (!string.IsNullOrWhiteSpace(thresholdState)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
&& thresholdValue > 0)
{
heatingThreshold = thresholdValue;
}
return new BoilerMonitorConfig
{
BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId,
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId,
PollIntervalSeconds = pollInterval,
HeatingPowerThresholdWatts = heatingThreshold
};
}
private double? ReadSensorDouble(string entityId)
{
var state = _haContext.GetState(entityId);
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 null)
{
return false;
}
try
{
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
{
return value switch
{
bool b => b,
string s => bool.TryParse(s, out var parsed) && parsed,
_ => false
};
}
}
catch
{
// Attribute not found or not parseable
}
return false;
}
private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName)
{
if (entityState?.Attributes is null)
{
return null;
}
try
{
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))
{
return parsed;
}
}
}
catch
{
// Attribute not found or not parseable
}
return null;
}
}
@@ -0,0 +1,34 @@
using BoilerMonitor.Models;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
namespace BoilerMonitorManager;
public static class BoilerMonitorServiceRegistration
{
public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration
.GetSection(BoilerMonitorOptions.SectionName)
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
if (!options.Enabled)
{
return services;
}
services
.AddNetDaemonApp<BoilerMonitorInit>()
.AddSingleton<IBoilerControlService, BoilerControlService>()
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
.AddSingleton<IWaterReadyService, WaterReadyService>()
.AddSingleton(TimeProvider.System)
.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
return services;
}
}
@@ -0,0 +1,66 @@
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
namespace BoilerMonitorManager;
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
{
private readonly Lock _lock = new();
private TimeSpan _accumulatedRunTime = TimeSpan.Zero;
private int _sessionCount;
private bool _isInSession;
public void RecordPollResult(bool isHeating, TimeSpan pollInterval)
{
lock (_lock)
{
if (isHeating)
{
_accumulatedRunTime += pollInterval;
if (!_isInSession)
{
_sessionCount++;
_isInSession = true;
}
}
else
{
_isInSession = false;
}
}
}
public RunTimeSnapshot GetSnapshot()
{
lock (_lock)
{
return new RunTimeSnapshot
{
AccumulatedRunTime = _accumulatedRunTime,
SessionCount = _sessionCount,
IsInSession = _isInSession
};
}
}
public void Reset()
{
lock (_lock)
{
_accumulatedRunTime = TimeSpan.Zero;
_sessionCount = 0;
_isInSession = false;
}
}
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount)
{
lock (_lock)
{
_accumulatedRunTime = accumulatedRunTime;
_sessionCount = sessionCount;
_isInSession = false;
}
}
}
@@ -0,0 +1,8 @@
using BoilerMonitor.Models.Enums;
namespace BoilerMonitorManager.Interface;
public interface IBoilerControlService
{
BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride);
}
@@ -0,0 +1,14 @@
using BoilerMonitorManager.Models;
namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorEntityService
{
Task CreateEntitiesAsync(CancellationToken cancellationToken = default);
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default);
Task UpdateEntitiesAsync(BoilerMonitorUpdateContext context, CancellationToken cancellationToken = default);
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
Task SetStatusAsync(string status);
PersistedBoilerState? ReadPersistedState();
}
@@ -0,0 +1,7 @@
namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -0,0 +1,11 @@
using BoilerMonitorManager.Models;
namespace BoilerMonitorManager.Interface;
public interface IBoilerRunTimeTracker
{
void RecordPollResult(bool isHeating, TimeSpan pollInterval);
RunTimeSnapshot GetSnapshot();
void Reset();
void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount);
}
@@ -0,0 +1,9 @@
namespace BoilerMonitorManager.Interface;
public interface IWaterReadyService
{
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
bool IsInCooldown { get; }
void NotifyTurnedOn();
void ResetCooldown();
}
@@ -0,0 +1,15 @@
namespace BoilerMonitorManager.Models;
public record BoilerMonitorConfig
{
public string? BoilerPowerEntityId { get; init; }
public string? BoilerSwitchEntityId { get; init; }
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;
}
@@ -0,0 +1,14 @@
namespace BoilerMonitorManager.Models;
public sealed class BoilerMonitorOptions
{
public const string SectionName = "BoilerMonitor";
public bool Enabled { get; init; } = true;
/// <summary>
/// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup.
/// Manual cleanup (e.g. HA button) is not affected.
/// </summary>
public bool CleanupEntitiesOnStartup { get; init; } = true;
}
@@ -0,0 +1,17 @@
namespace BoilerMonitorManager.Models;
public record BoilerMonitorUpdateContext
{
public required TimeSpan TodayRunTime { get; init; }
public required TimeSpan RemainingTime { get; init; }
public required double BudgetPercentage { get; init; }
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 bool IsNowCheap { get; init; }
public required DateTime? NextCheapIntervalStart { get; init; }
}
@@ -0,0 +1,9 @@
namespace BoilerMonitorManager.Models;
public record PersistedBoilerState
{
public required TimeSpan AccumulatedRunTime { get; init; }
public required int SessionCount { get; init; }
public required string? SkipPriceCapState { get; init; }
public required string? BudgetOverrideState { get; init; }
}
@@ -0,0 +1,8 @@
namespace BoilerMonitorManager.Models;
public record RunTimeSnapshot
{
public required TimeSpan AccumulatedRunTime { get; init; }
public required int SessionCount { get; init; }
public required bool IsInSession { get; init; }
}
+115
View File
@@ -0,0 +1,115 @@
using BoilerMonitor.Models;
using BoilerMonitorManager.Interface;
using Microsoft.Extensions.Logging;
namespace BoilerMonitorManager;
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
{
private const string SwitchOnState = "on";
private readonly Lock _lock = new();
private DateTimeOffset? _lastTurnedOnAt;
private DateTimeOffset? _waterReadySince;
public bool IsInCooldown
{
get
{
lock (_lock)
{
return IsWithinCooldownPeriod();
}
}
}
public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts)
{
lock (_lock)
{
if (IsWithinCooldownPeriod())
{
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
return true;
}
}
if (switchState is null || powerWatts is null)
{
return false;
}
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (IsWithinWarmUpGracePeriod())
{
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)
{
_waterReadySince ??= timeProvider.GetUtcNow();
}
logger.LogInformation(
"Water detected as ready, cooldown period ({CooldownPeriod}) started",
BoilerMonitorConsts.WaterReadyCooldownPeriod);
}
return isReady;
}
public void NotifyTurnedOn()
{
lock (_lock)
{
_lastTurnedOnAt = timeProvider.GetUtcNow();
}
logger.LogDebug("Boiler turn-on recorded, warm-up grace period started ({GracePeriod})", BoilerMonitorConsts.WarmUpGracePeriod);
}
public void ResetCooldown()
{
lock (_lock)
{
_waterReadySince = null;
}
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()
{
lock (_lock)
{
if (_lastTurnedOnAt is null)
{
return false;
}
var elapsed = timeProvider.GetUtcNow() - _lastTurnedOnAt.Value;
return elapsed < BoilerMonitorConsts.WarmUpGracePeriod;
}
}
}