feat: add BatteryMonitor implementation with discovery, notification, and scheduling services
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
using BoilerMonitor.Models;
|
||||
using LightMonitor.Models;
|
||||
using NordPool.Models;
|
||||
using ShowerMonitor.Models;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Configuration;
|
||||
|
||||
public static class ReplayEntityMap
|
||||
{
|
||||
public static IReadOnlyList<string> GetNordPoolEntities() =>
|
||||
[
|
||||
"sensor.nordpool_kwh_lt_eur_3_10_0",
|
||||
NordPoolConsts.CurrentPriceEntityId,
|
||||
BoilerMonitorConsts.BoilerDailyHoursEntityId,
|
||||
BoilerMonitorConsts.BoilerPriceCapEntityId,
|
||||
BoilerMonitorConsts.BoilerReadyByEntityId,
|
||||
BoilerMonitorConsts.SkipPriceCapEntityId
|
||||
];
|
||||
|
||||
public static IReadOnlyList<string> GetBoilerEntities(string boilerPowerEntityId, string boilerSwitchEntityId) =>
|
||||
[
|
||||
boilerPowerEntityId,
|
||||
boilerSwitchEntityId,
|
||||
"sensor.nordpool_cheapest_intervals",
|
||||
BoilerMonitorConsts.SkipPriceCapEntityId,
|
||||
BoilerMonitorConsts.BudgetOverrideEntityId,
|
||||
BoilerMonitorConsts.BoilerDailyHoursEntityId
|
||||
];
|
||||
|
||||
public static IReadOnlyList<string> GetShowerEntities(string bathroomHumidityEntityId, string mainHomeHumidityEntityId) =>
|
||||
[
|
||||
bathroomHumidityEntityId,
|
||||
mainHomeHumidityEntityId
|
||||
];
|
||||
|
||||
public static IReadOnlyList<string> GetPowerEntities(string mainMeterEntityId) =>
|
||||
[
|
||||
mainMeterEntityId,
|
||||
NordPoolConsts.CurrentPriceEntityId
|
||||
];
|
||||
|
||||
public static IReadOnlyList<string> GetLightEntities(string sunEntityId, string lightEntityId, string[] personEntityIds)
|
||||
{
|
||||
var entities = new List<string> { sunEntityId, lightEntityId };
|
||||
entities.AddRange(personEntityIds);
|
||||
return entities;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<string> GetAllEntities(
|
||||
string boilerPowerEntityId,
|
||||
string boilerSwitchEntityId,
|
||||
string bathroomHumidityEntityId,
|
||||
string mainHomeHumidityEntityId,
|
||||
string mainMeterEntityId,
|
||||
string sunEntityId,
|
||||
string lightEntityId,
|
||||
string[] personEntityIds)
|
||||
{
|
||||
var all = new HashSet<string>();
|
||||
|
||||
foreach (var e in GetNordPoolEntities()) all.Add(e);
|
||||
foreach (var e in GetBoilerEntities(boilerPowerEntityId, boilerSwitchEntityId)) all.Add(e);
|
||||
foreach (var e in GetShowerEntities(bathroomHumidityEntityId, mainHomeHumidityEntityId)) all.Add(e);
|
||||
foreach (var e in GetPowerEntities(mainMeterEntityId)) all.Add(e);
|
||||
foreach (var e in GetLightEntities(sunEntityId, lightEntityId, personEntityIds)) all.Add(e);
|
||||
|
||||
return [.. all];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace HomeAssistant.HistoryReplay.Configuration;
|
||||
|
||||
public sealed class ReplayOptions
|
||||
{
|
||||
public const string SectionName = "Replay";
|
||||
|
||||
public DateTimeOffset StartTime { get; set; } = DateTimeOffset.UtcNow.AddDays(-1);
|
||||
public DateTimeOffset EndTime { get; set; } = DateTimeOffset.UtcNow;
|
||||
public ReplayMonitorFlags Monitors { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class ReplayMonitorFlags
|
||||
{
|
||||
public bool NordPool { get; set; } = true;
|
||||
public bool Boiler { get; set; } = true;
|
||||
public bool Shower { get; set; } = true;
|
||||
public bool Power { get; set; } = true;
|
||||
public bool Light { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
||||
|
||||
public sealed class HistoryStateEntry
|
||||
{
|
||||
public required string EntityId { get; init; }
|
||||
public required string? State { get; init; }
|
||||
public required DateTimeOffset LastChanged { get; init; }
|
||||
public IReadOnlyDictionary<string, object>? Attributes { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
||||
|
||||
public sealed class HistoryTimeline
|
||||
{
|
||||
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
|
||||
{
|
||||
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
||||
{
|
||||
list = [];
|
||||
_entityTimelines[entityId] = list;
|
||||
}
|
||||
|
||||
list.AddRange(entries);
|
||||
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
||||
}
|
||||
|
||||
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
|
||||
{
|
||||
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
HistoryStateEntry? best = null;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (entry.LastChanged <= timestamp)
|
||||
{
|
||||
best = entry;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
|
||||
{
|
||||
var timestamps = new SortedSet<DateTimeOffset>();
|
||||
|
||||
foreach (var entries in _entityTimelines.Values)
|
||||
{
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
timestamps.Add(entry.LastChanged);
|
||||
}
|
||||
}
|
||||
|
||||
return [.. timestamps];
|
||||
}
|
||||
|
||||
public IReadOnlyList<string> GetEntityIds() => [.. _entityTimelines.Keys];
|
||||
|
||||
public IReadOnlyList<HistoryStateEntry> GetEntityHistory(string entityId)
|
||||
{
|
||||
return _entityTimelines.TryGetValue(entityId, out var entries) ? entries : [];
|
||||
}
|
||||
|
||||
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using HomeAssistant.HistoryReplay.HomeAssistantClient;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
||||
|
||||
public sealed class HomeAssistantHistoryProvider(
|
||||
IHomeAssistantApiClient client,
|
||||
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
|
||||
{
|
||||
private const int MaxEntitiesPerRequest = 10;
|
||||
|
||||
public async Task<HistoryTimeline> FetchHistoryAsync(
|
||||
IReadOnlyList<string> entityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var timeline = new HistoryTimeline();
|
||||
var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest);
|
||||
|
||||
var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken));
|
||||
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
|
||||
foreach (var batchTimeline in results)
|
||||
{
|
||||
foreach (var entityId in batchTimeline.GetEntityIds())
|
||||
{
|
||||
timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId));
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation(
|
||||
"Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})",
|
||||
entityIds.Count, timeline.TotalEntryCount, startTime, endTime);
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
private async Task<HistoryTimeline> FetchBatchAsync(
|
||||
IReadOnlyList<string> entityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var timeline = new HistoryTimeline();
|
||||
var entityIdsString = string.Join(",", entityIds);
|
||||
|
||||
logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString);
|
||||
|
||||
try
|
||||
{
|
||||
var result = await client.GetHistoryAsync(
|
||||
entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
ParseHistoryResponse(result, timeline);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString);
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline)
|
||||
{
|
||||
if (response.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var entityArray in response.EnumerateArray())
|
||||
{
|
||||
if (entityArray.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var stateObj in entityArray.EnumerateArray())
|
||||
{
|
||||
var entry = ParseStateEntry(stateObj);
|
||||
if (entry is not null)
|
||||
{
|
||||
timeline.AddEntries(entry.EntityId, [entry]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private HistoryStateEntry? ParseStateEntry(JsonElement stateObj)
|
||||
{
|
||||
if (!stateObj.TryGetProperty("entity_id", out var entityIdProp))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var entityId = entityIdProp.GetString();
|
||||
if (string.IsNullOrEmpty(entityId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
|
||||
|
||||
DateTimeOffset lastChanged;
|
||||
if (stateObj.TryGetProperty("last_changed", out var lastChangedProp))
|
||||
{
|
||||
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out lastChanged))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Dictionary<string, object>? attributes = null;
|
||||
if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
attributes = ParseAttributes(attrProp);
|
||||
}
|
||||
|
||||
return new HistoryStateEntry
|
||||
{
|
||||
EntityId = entityId,
|
||||
State = state,
|
||||
LastChanged = lastChanged,
|
||||
Attributes = attributes
|
||||
};
|
||||
}
|
||||
|
||||
private static Dictionary<string, object> ParseAttributes(JsonElement attrElement)
|
||||
{
|
||||
var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var prop in attrElement.EnumerateObject())
|
||||
{
|
||||
attributes[prop.Name] = prop.Value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => prop.Value.GetString() ?? string.Empty,
|
||||
JsonValueKind.Number => prop.Value.GetDouble(),
|
||||
JsonValueKind.True => true,
|
||||
JsonValueKind.False => false,
|
||||
_ => prop.Value.GetRawText()
|
||||
};
|
||||
}
|
||||
|
||||
return attributes;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<IReadOnlyList<string>> ChunkEntities(IReadOnlyList<string> entities, int chunkSize)
|
||||
{
|
||||
var chunks = new List<IReadOnlyList<string>>();
|
||||
|
||||
for (var i = 0; i < entities.Count; i += chunkSize)
|
||||
{
|
||||
var chunk = entities.Skip(i).Take(chunkSize).ToList();
|
||||
chunks.Add(chunk);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
||||
|
||||
public interface IHistoryDataProvider
|
||||
{
|
||||
Task<HistoryTimeline> FetchHistoryAsync(
|
||||
IReadOnlyList<string> entityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>HomeAssistant.HistoryReplay</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="appsettings.development.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
||||
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
|
||||
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
|
||||
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
|
||||
|
||||
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_httpClient.BaseAddress = settings.Value.BaseUrl;
|
||||
_httpClient.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
|
||||
_httpClient.DefaultRequestHeaders.Accept.Add(
|
||||
new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
|
||||
}
|
||||
|
||||
public async Task<JsonElement> GetHistoryAsync(
|
||||
string entityIds,
|
||||
DateTimeOffset? startTime = null,
|
||||
DateTimeOffset? endTime = null,
|
||||
bool minimalResponse = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
|
||||
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
|
||||
|
||||
if (endTime.HasValue)
|
||||
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
|
||||
|
||||
if (minimalResponse)
|
||||
path += "&minimal_response";
|
||||
|
||||
return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
return doc.RootElement.Clone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
|
||||
|
||||
public sealed class HomeAssistantSettings
|
||||
{
|
||||
public const string SectionName = "HomeAssistant";
|
||||
public const int DefaultPort = 8123;
|
||||
public const int DefaultTimeoutSeconds = 30;
|
||||
|
||||
public string Host { get; set; } = string.Empty;
|
||||
public int Port { get; set; } = DefaultPort;
|
||||
public string Token { get; set; } = string.Empty;
|
||||
public bool Ssl { get; set; }
|
||||
|
||||
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
|
||||
|
||||
public interface IHomeAssistantApiClient
|
||||
{
|
||||
Task<JsonElement> GetHistoryAsync(
|
||||
string entityIds,
|
||||
DateTimeOffset? startTime = null,
|
||||
DateTimeOffset? endTime = null,
|
||||
bool minimalResponse = true,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using BoilerMonitorManager;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using BoilerMonitorManager.Models;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using HomeAssistant.HistoryReplay.Runners;
|
||||
using HomeAssistant.HistoryReplay.HomeAssistantClient;
|
||||
using LightMonitorManager.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NordPoolManager;
|
||||
using NordPoolManager.Interface;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using Serilog;
|
||||
using ShowerMonitorManager;
|
||||
using ShowerMonitorManager.Interface;
|
||||
using ShowerMonitorManager.Models;
|
||||
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
.MinimumLevel.Information()
|
||||
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.CreateLogger();
|
||||
|
||||
try
|
||||
{
|
||||
Log.Information("Starting Home Assistant History Replay");
|
||||
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json", optional: false)
|
||||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
|
||||
var services = new ServiceCollection();
|
||||
|
||||
services.AddLogging(builder =>
|
||||
{
|
||||
builder.ClearProviders();
|
||||
builder.AddSerilog(dispose: true);
|
||||
});
|
||||
|
||||
services.Configure<HomeAssistantSettings>(configuration.GetSection(HomeAssistantSettings.SectionName));
|
||||
services.Configure<ReplayOptions>(configuration.GetSection(ReplayOptions.SectionName));
|
||||
services.Configure<BoilerMonitorOptions>(configuration.GetSection(BoilerMonitorOptions.SectionName));
|
||||
services.Configure<ShowerMonitorOptions>(configuration.GetSection(ShowerMonitorOptions.SectionName));
|
||||
services.Configure<PowerMonitorOptions>(configuration.GetSection(PowerMonitorOptions.SectionName));
|
||||
services.Configure<LightMonitorOptions>(configuration.GetSection(LightMonitorOptions.SectionName));
|
||||
|
||||
services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
|
||||
services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
|
||||
|
||||
var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get<ReplayOptions>() ?? new ReplayOptions();
|
||||
|
||||
var replayTimeline = new ReplayTimeline();
|
||||
var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime);
|
||||
|
||||
services.AddSingleton(replayTimeline);
|
||||
services.AddSingleton(replayTimeProvider);
|
||||
services.AddSingleton<TimeProvider>(replayTimeProvider);
|
||||
|
||||
services.AddSingleton<IEntityManager, NoOpEntityManager>();
|
||||
|
||||
services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
|
||||
services.AddSingleton<IBoilerControlService, BoilerControlService>();
|
||||
services.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||
services.AddSingleton<IWaterReadyService, WaterReadyService>();
|
||||
services.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>();
|
||||
services.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>();
|
||||
|
||||
var showerOptions = configuration.GetSection(ShowerMonitorOptions.SectionName).Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
|
||||
services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOptions.RateWindowSize));
|
||||
services.AddSingleton<IShowerDetectionService, ShowerDetectionService>();
|
||||
|
||||
services.AddSingleton<ConsoleReportRenderer>();
|
||||
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
var historyProvider = provider.GetRequiredService<IHistoryDataProvider>();
|
||||
var logger = provider.GetRequiredService<ILogger<Program>>();
|
||||
|
||||
var boilerOpts = provider.GetRequiredService<IOptions<BoilerMonitorOptions>>().Value;
|
||||
var showerOpts = provider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
|
||||
var powerOpts = provider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
|
||||
var lightOpts = provider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
|
||||
|
||||
logger.LogInformation("Replay period: {Start} to {End}", replayOptions.StartTime, replayOptions.EndTime);
|
||||
|
||||
var allEntityIds = ReplayEntityMap.GetAllEntities(
|
||||
boilerPowerEntityId: "sensor.boiler_power",
|
||||
boilerSwitchEntityId: "switch.boiler",
|
||||
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
|
||||
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
|
||||
mainMeterEntityId: powerOpts.MainMeterEntityId,
|
||||
sunEntityId: lightOpts.SunEntityId,
|
||||
lightEntityId: lightOpts.LightEntityId,
|
||||
personEntityIds: lightOpts.PersonEntityIds);
|
||||
|
||||
logger.LogInformation("Fetching history for {Count} entities...", allEntityIds.Count);
|
||||
|
||||
var timeline = await historyProvider.FetchHistoryAsync(
|
||||
allEntityIds, replayOptions.StartTime, replayOptions.EndTime);
|
||||
|
||||
var replayHaContext = new ReplayHaContext(
|
||||
timeline,
|
||||
replayTimeProvider,
|
||||
replayTimeline,
|
||||
provider.GetRequiredService<ILogger<ReplayHaContext>>());
|
||||
|
||||
var fanControlService = new ExhaustFanControlService(
|
||||
replayHaContext,
|
||||
provider.GetRequiredService<ILogger<ExhaustFanControlService>>(),
|
||||
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>());
|
||||
|
||||
var runners = new List<IMonitorReplayRunner>();
|
||||
|
||||
if (replayOptions.Monitors.NordPool)
|
||||
{
|
||||
runners.Add(new NordPoolReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<ICheapestIntervalsFinder>(),
|
||||
provider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Boiler)
|
||||
{
|
||||
runners.Add(new BoilerReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<IBoilerControlService>(),
|
||||
provider.GetRequiredService<IBoilerRunTimeTracker>(),
|
||||
provider.GetRequiredService<IWaterReadyService>(),
|
||||
provider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<BoilerMonitorOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Shower)
|
||||
{
|
||||
runners.Add(new ShowerReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<IShowerDetectionService>(),
|
||||
fanControlService,
|
||||
provider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Power)
|
||||
{
|
||||
runners.Add(new PowerReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<IOtherPowerCalculationService>(),
|
||||
provider.GetRequiredService<IPowerCostCalculationService>(),
|
||||
provider.GetRequiredService<ILogger<PowerReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Light)
|
||||
{
|
||||
runners.Add(new LightReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<ILogger<LightReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<LightMonitorOptions>>()));
|
||||
}
|
||||
|
||||
logger.LogInformation("Running {Count} monitor replay(s) in parallel...", runners.Count);
|
||||
|
||||
var replayTasks = runners.Select(r => Task.Run(() => r.RunAsync()));
|
||||
await Task.WhenAll(replayTasks);
|
||||
|
||||
var renderer = provider.GetRequiredService<ConsoleReportRenderer>();
|
||||
renderer.Render(replayTimeline, replayOptions);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "History replay failed");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Log.CloseAndFlushAsync();
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using HomeAssistant.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Replay;
|
||||
|
||||
public sealed class NoOpEntityManager(ILogger<NoOpEntityManager> logger) : IEntityManager
|
||||
{
|
||||
public Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
|
||||
{
|
||||
logger.LogDebug("[REPLAY] Would create {Count} entities", entities.Count);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task CreateEntityAsync(EntityCreateModel createModel)
|
||||
{
|
||||
logger.LogDebug("[REPLAY] Would create entity: {EntityId}", createModel.EntityId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SetEntityState(string entityId, string state)
|
||||
{
|
||||
logger.LogDebug("[REPLAY] Would set state for {EntityId}: {State}", entityId, state);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SetEntityAttributes(string entityId, object attributes)
|
||||
{
|
||||
logger.LogDebug("[REPLAY] Would set attributes for {EntityId}", entityId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task RemoveEntity(string entityId)
|
||||
{
|
||||
logger.LogDebug("[REPLAY] Would remove entity: {EntityId}", entityId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Reactive.Linq;
|
||||
using System.Text.Json;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Replay;
|
||||
|
||||
public sealed class ReplayHaContext : IHaContext
|
||||
{
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ILogger<ReplayHaContext> _logger;
|
||||
|
||||
public ReplayHaContext(
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ILogger<ReplayHaContext> logger)
|
||||
{
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public EntityState? GetState(string entityId)
|
||||
{
|
||||
var currentTime = _timeProvider.GetUtcNow();
|
||||
var entry = _timeline.GetStateAt(entityId, currentTime);
|
||||
|
||||
if (entry is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
JsonElement? attributesJson = null;
|
||||
if (entry.Attributes is { Count: > 0 })
|
||||
{
|
||||
attributesJson = JsonSerializer.SerializeToElement(entry.Attributes);
|
||||
}
|
||||
|
||||
return new EntityState
|
||||
{
|
||||
State = entry.State,
|
||||
AttributesJson = attributesJson
|
||||
};
|
||||
}
|
||||
|
||||
public IReadOnlyList<Entity> GetAllEntities()
|
||||
{
|
||||
return _timeline.GetEntityIds()
|
||||
.Select(id => new Entity(this, id))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public void CallService(string domain, string service, ServiceTarget? target = null, object? data = null)
|
||||
{
|
||||
var currentTime = _timeProvider.GetUtcNow();
|
||||
var targetDescription = target?.EntityIds is not null
|
||||
? string.Join(", ", target.EntityIds)
|
||||
: "no target";
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = "ServiceCall",
|
||||
EventType = ReplayEventType.ServiceCall,
|
||||
Message = $"Would call {domain}.{service} on {targetDescription}",
|
||||
Details = data is not null ? JsonSerializer.Serialize(data) : null
|
||||
});
|
||||
|
||||
_logger.LogDebug("[REPLAY] {Domain}.{Service} → {Target}", domain, service, targetDescription);
|
||||
}
|
||||
|
||||
public void SendEvent(string eventType, object? data = null)
|
||||
{
|
||||
_logger.LogDebug("[REPLAY] Would send event: {EventType}", eventType);
|
||||
}
|
||||
|
||||
public IObservable<StateChange> StateAllChanges() => Observable.Empty<StateChange>();
|
||||
|
||||
public IObservable<Event> Events => Observable.Empty<Event>();
|
||||
|
||||
public Task<JsonElement?> CallServiceWithResponseAsync(
|
||||
string domain, string service, ServiceTarget? target = null, object? data = null)
|
||||
{
|
||||
CallService(domain, service, target, data);
|
||||
return Task.FromResult<JsonElement?>(null);
|
||||
}
|
||||
|
||||
public Area? GetAreaFromEntityId(string entityId) => null;
|
||||
|
||||
public EntityRegistration? GetEntityRegistration(string entityId) => null;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace HomeAssistant.HistoryReplay.Replay;
|
||||
|
||||
public sealed class ReplayTimeProvider : TimeProvider
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private DateTimeOffset _currentUtcTime;
|
||||
private readonly TimeZoneInfo _localTimeZone;
|
||||
|
||||
public ReplayTimeProvider(DateTimeOffset initialTime)
|
||||
{
|
||||
_currentUtcTime = initialTime.ToUniversalTime();
|
||||
_localTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
||||
}
|
||||
|
||||
public override DateTimeOffset GetUtcNow()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _currentUtcTime;
|
||||
}
|
||||
}
|
||||
|
||||
public override TimeZoneInfo LocalTimeZone => _localTimeZone;
|
||||
|
||||
public void AdvanceTo(DateTimeOffset utcTime)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_currentUtcTime = utcTime.ToUniversalTime();
|
||||
}
|
||||
}
|
||||
|
||||
public void AdvanceBy(TimeSpan duration)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_currentUtcTime += duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
||||
|
||||
public sealed class ConsoleReportRenderer
|
||||
{
|
||||
private const string Separator = "═══════════════════════════════════════════════════════════";
|
||||
private const string SectionSeparator = "── {0} ──────────────────────────────────────────────";
|
||||
private const string TimeFormat = "HH:mm:ss";
|
||||
|
||||
public void Render(ReplayTimeline timeline, ReplayOptions options)
|
||||
{
|
||||
Console.WriteLine();
|
||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
||||
WriteColored($" REPLAY: {options.StartTime:yyyy-MM-dd HH:mm} → {options.EndTime:yyyy-MM-dd HH:mm}", ConsoleColor.White);
|
||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
||||
Console.WriteLine();
|
||||
|
||||
var monitors = timeline.GetMonitors()
|
||||
.Where(m => !string.Equals(m, "ServiceCall", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList();
|
||||
|
||||
foreach (var monitor in monitors)
|
||||
{
|
||||
RenderMonitorSection(monitor, timeline.GetEventsByMonitor(monitor));
|
||||
}
|
||||
|
||||
RenderServiceCallSection(timeline.GetEventsByMonitor("ServiceCall"));
|
||||
RenderSummary(timeline);
|
||||
}
|
||||
|
||||
private static void RenderMonitorSection(string monitor, IReadOnlyList<ReplayEvent> events)
|
||||
{
|
||||
Console.WriteLine();
|
||||
WriteColored(string.Format(SectionSeparator, monitor), ConsoleColor.Yellow);
|
||||
|
||||
if (events.Count == 0)
|
||||
{
|
||||
WriteColored(" No events recorded", ConsoleColor.DarkGray);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var evt in events)
|
||||
{
|
||||
var color = GetEventColor(evt.EventType);
|
||||
var prefix = GetEventPrefix(evt.EventType);
|
||||
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
|
||||
|
||||
WriteColored($" {timestamp} {prefix}{evt.Message}", color);
|
||||
|
||||
if (!string.IsNullOrEmpty(evt.Details))
|
||||
{
|
||||
WriteColored($" {evt.Details}", ConsoleColor.DarkGray);
|
||||
}
|
||||
}
|
||||
|
||||
WriteSectionSummary(events);
|
||||
}
|
||||
|
||||
private static void RenderServiceCallSection(IReadOnlyList<ReplayEvent> events)
|
||||
{
|
||||
if (events.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
WriteColored(string.Format(SectionSeparator, "Service Calls"), ConsoleColor.Magenta);
|
||||
|
||||
foreach (var evt in events)
|
||||
{
|
||||
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
|
||||
WriteColored($" {timestamp} → {evt.Message}", ConsoleColor.DarkMagenta);
|
||||
}
|
||||
|
||||
WriteColored($"\n Total: {events.Count} service call(s) would have been made", ConsoleColor.DarkGray);
|
||||
}
|
||||
|
||||
private static void RenderSummary(ReplayTimeline timeline)
|
||||
{
|
||||
var allEvents = timeline.GetAllEvents();
|
||||
|
||||
Console.WriteLine();
|
||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
||||
WriteColored(" REPLAY SUMMARY", ConsoleColor.White);
|
||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
||||
|
||||
var decisions = allEvents.Count(e => e.EventType == ReplayEventType.Decision);
|
||||
var serviceCalls = allEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
|
||||
var warnings = allEvents.Count(e => e.EventType == ReplayEventType.Warning);
|
||||
var anomalies = allEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
|
||||
|
||||
WriteColored($" Total events: {allEvents.Count}", ConsoleColor.Gray);
|
||||
WriteColored($" Decisions: {decisions}", ConsoleColor.Cyan);
|
||||
WriteColored($" Service calls: {serviceCalls}", ConsoleColor.Magenta);
|
||||
WriteColored($" Warnings: {warnings}", ConsoleColor.DarkYellow);
|
||||
WriteColored($" Anomalies: {anomalies}", ConsoleColor.Red);
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
private static void WriteSectionSummary(IReadOnlyList<ReplayEvent> events)
|
||||
{
|
||||
var decisions = events.Count(e => e.EventType == ReplayEventType.Decision);
|
||||
var warnings = events.Count(e => e.EventType == ReplayEventType.Warning);
|
||||
var stateChanges = events.Count(e => e.EventType == ReplayEventType.StateChange);
|
||||
|
||||
var parts = new List<string>();
|
||||
if (decisions > 0) parts.Add($"{decisions} decision(s)");
|
||||
if (stateChanges > 0) parts.Add($"{stateChanges} state change(s)");
|
||||
if (warnings > 0) parts.Add($"{warnings} warning(s)");
|
||||
|
||||
if (parts.Count > 0)
|
||||
{
|
||||
WriteColored($"\n Summary: {string.Join(", ", parts)}", ConsoleColor.DarkGray);
|
||||
}
|
||||
}
|
||||
|
||||
private static ConsoleColor GetEventColor(ReplayEventType eventType) =>
|
||||
eventType switch
|
||||
{
|
||||
ReplayEventType.Decision => ConsoleColor.Green,
|
||||
ReplayEventType.StateChange => ConsoleColor.Cyan,
|
||||
ReplayEventType.Warning => ConsoleColor.DarkYellow,
|
||||
ReplayEventType.ServiceCall => ConsoleColor.Magenta,
|
||||
ReplayEventType.Anomaly => ConsoleColor.Red,
|
||||
_ => ConsoleColor.Gray
|
||||
};
|
||||
|
||||
private static string GetEventPrefix(ReplayEventType eventType) =>
|
||||
eventType switch
|
||||
{
|
||||
ReplayEventType.Decision => "→ ",
|
||||
ReplayEventType.Warning => "⚠ ",
|
||||
ReplayEventType.Anomaly => "⚠ ANOMALY: ",
|
||||
ReplayEventType.ServiceCall => "⤷ ",
|
||||
_ => ""
|
||||
};
|
||||
|
||||
private static void WriteColored(string text, ConsoleColor color)
|
||||
{
|
||||
var previousColor = Console.ForegroundColor;
|
||||
Console.ForegroundColor = color;
|
||||
Console.WriteLine(text);
|
||||
Console.ForegroundColor = previousColor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
||||
|
||||
public sealed class ReplayEvent
|
||||
{
|
||||
public required DateTimeOffset Timestamp { get; init; }
|
||||
public required string Monitor { get; init; }
|
||||
public required ReplayEventType EventType { get; init; }
|
||||
public required string Message { get; init; }
|
||||
public string? Details { get; init; }
|
||||
}
|
||||
|
||||
public enum ReplayEventType
|
||||
{
|
||||
Info,
|
||||
Decision,
|
||||
StateChange,
|
||||
Warning,
|
||||
ServiceCall,
|
||||
Anomaly
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
||||
|
||||
public sealed class ReplayTimeline
|
||||
{
|
||||
private readonly ConcurrentBag<ReplayEvent> _events = [];
|
||||
|
||||
public void AddEvent(ReplayEvent replayEvent)
|
||||
{
|
||||
_events.Add(replayEvent);
|
||||
}
|
||||
|
||||
public IReadOnlyList<ReplayEvent> GetEventsByMonitor(string monitor) =>
|
||||
_events
|
||||
.Where(e => string.Equals(e.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(e => e.Timestamp)
|
||||
.ToList();
|
||||
|
||||
public IReadOnlyList<ReplayEvent> GetAllEvents() =>
|
||||
_events.OrderBy(e => e.Timestamp).ToList();
|
||||
|
||||
public IReadOnlyList<string> GetMonitors() =>
|
||||
_events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList();
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
using System.Globalization;
|
||||
using BoilerMonitor.Models;
|
||||
using BoilerMonitor.Models.Enums;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
{
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly IBoilerControlService _boilerControlService;
|
||||
private readonly IBoilerRunTimeTracker _tracker;
|
||||
private readonly IWaterReadyService _waterReadyService;
|
||||
private readonly ILogger<BoilerReplayRunner> _logger;
|
||||
private readonly ReplayOptions _replayOptions;
|
||||
private readonly BoilerMonitorOptions _boilerOptions;
|
||||
|
||||
public string MonitorName => "Boiler";
|
||||
|
||||
public BoilerReplayRunner(
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
IBoilerControlService boilerControlService,
|
||||
IBoilerRunTimeTracker tracker,
|
||||
IWaterReadyService waterReadyService,
|
||||
ILogger<BoilerReplayRunner> logger,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
IOptions<BoilerMonitorOptions> boilerOptions)
|
||||
{
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_boilerControlService = boilerControlService;
|
||||
_tracker = tracker;
|
||||
_waterReadyService = waterReadyService;
|
||||
_logger = logger;
|
||||
_replayOptions = replayOptions.Value;
|
||||
_boilerOptions = boilerOptions.Value;
|
||||
}
|
||||
|
||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogInformation("Starting Boiler replay");
|
||||
|
||||
var currentTime = _replayOptions.StartTime;
|
||||
var pollInterval = TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultPollIntervalSeconds);
|
||||
var heatingThreshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
|
||||
BoilerAction? lastAction = null;
|
||||
var lastWaterReady = false;
|
||||
|
||||
var boilerPowerEntityId = ReadConfigEntityState(
|
||||
BoilerMonitorConsts.ConfigPowerEntityId, _replayOptions.StartTime);
|
||||
var boilerSwitchEntityId = ReadConfigEntityState(
|
||||
BoilerMonitorConsts.ConfigSwitchEntityId, _replayOptions.StartTime);
|
||||
|
||||
if (string.IsNullOrEmpty(boilerPowerEntityId) || string.IsNullOrEmpty(boilerSwitchEntityId))
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Warning,
|
||||
Message = "Boiler not configured (missing power/switch entity IDs), skipping replay"
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var configThresholdState = ReadConfigEntityState(
|
||||
BoilerMonitorConsts.ConfigHeatingThresholdEntityId, _replayOptions.StartTime);
|
||||
if (!string.IsNullOrEmpty(configThresholdState) &&
|
||||
double.TryParse(configThresholdState, CultureInfo.InvariantCulture, out var configuredThreshold))
|
||||
{
|
||||
heatingThreshold = configuredThreshold;
|
||||
}
|
||||
|
||||
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_timeProvider.AdvanceTo(currentTime);
|
||||
|
||||
var powerEntry = _timeline.GetStateAt(boilerPowerEntityId, currentTime);
|
||||
var switchEntry = _timeline.GetStateAt(boilerSwitchEntityId, currentTime);
|
||||
var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime);
|
||||
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime);
|
||||
var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime);
|
||||
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime);
|
||||
|
||||
var boilerPowerWatts = ParseDouble(powerEntry?.State);
|
||||
var boilerSwitchState = switchEntry?.State;
|
||||
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= heatingThreshold;
|
||||
|
||||
_tracker.RecordPollResult(isHeating, pollInterval);
|
||||
|
||||
var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap");
|
||||
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
||||
var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
||||
var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0;
|
||||
|
||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold);
|
||||
|
||||
if (!lastWaterReady && waterReady)
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.StateChange,
|
||||
Message = $"Water ready detected (power: {boilerPowerWatts:F1}W, threshold: {heatingThreshold}W)"
|
||||
});
|
||||
}
|
||||
lastWaterReady = waterReady;
|
||||
|
||||
var snapshot = _tracker.GetSnapshot();
|
||||
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
||||
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
||||
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
||||
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
|
||||
: 0.0;
|
||||
|
||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||
var action = _boilerControlService.DetermineAction(
|
||||
effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
|
||||
|
||||
if (action != BoilerAction.NoChange && action != lastAction)
|
||||
{
|
||||
var actionMessage = action switch
|
||||
{
|
||||
BoilerAction.TurnOn => $"TURN ON (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
|
||||
BoilerAction.TurnOff => $"TURN OFF (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
|
||||
_ => action.ToString()
|
||||
};
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Decision,
|
||||
Message = actionMessage,
|
||||
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
|
||||
});
|
||||
|
||||
if (action == BoilerAction.TurnOn)
|
||||
{
|
||||
_waterReadyService.NotifyTurnedOn();
|
||||
}
|
||||
}
|
||||
|
||||
lastAction = action;
|
||||
currentTime = currentTime.Add(pollInterval);
|
||||
}
|
||||
|
||||
var finalSnapshot = _tracker.GetSnapshot();
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = _replayOptions.EndTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = $"Final: {finalSnapshot.AccumulatedRunTime:hh\\:mm\\:ss} total runtime, {finalSnapshot.SessionCount} session(s)"
|
||||
});
|
||||
|
||||
_logger.LogInformation("Boiler replay complete");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private string? ReadConfigEntityState(string entityId, DateTimeOffset timestamp)
|
||||
{
|
||||
var entry = _timeline.GetStateAt(entityId, timestamp);
|
||||
return entry?.State;
|
||||
}
|
||||
|
||||
private static bool ReadAttributeBool(HistoryStateEntry? entry, string attributeName)
|
||||
{
|
||||
if (entry?.Attributes is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!entry.Attributes.TryGetValue(attributeName, out var value))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return value switch
|
||||
{
|
||||
bool b => b,
|
||||
string s => bool.TryParse(s, out var parsed) && parsed,
|
||||
double d => d != 0,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
private static double? ParseDouble(string? value)
|
||||
{
|
||||
if (value is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
public interface IMonitorReplayRunner
|
||||
{
|
||||
string MonitorName { get; }
|
||||
Task RunAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using LightMonitor.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using LightMonitorManager.Models;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
{
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ILogger<LightReplayRunner> _logger;
|
||||
private readonly ReplayOptions _replayOptions;
|
||||
private readonly LightMonitorOptions _lightOptions;
|
||||
|
||||
public string MonitorName => "Light";
|
||||
|
||||
public LightReplayRunner(
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ILogger<LightReplayRunner> logger,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
IOptions<LightMonitorOptions> lightOptions)
|
||||
{
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_logger = logger;
|
||||
_replayOptions = replayOptions.Value;
|
||||
_lightOptions = lightOptions.Value;
|
||||
}
|
||||
|
||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogInformation("Starting Light replay");
|
||||
|
||||
ReplaySunEvents(cancellationToken);
|
||||
ReplayPersonArrivals(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Light replay complete");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void ReplaySunEvents(CancellationToken cancellationToken)
|
||||
{
|
||||
var sunHistory = _timeline.GetEntityHistory(_lightOptions.SunEntityId);
|
||||
string? previousSunState = null;
|
||||
|
||||
foreach (var entry in sunHistory)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) break;
|
||||
|
||||
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_timeProvider.AdvanceTo(entry.LastChanged);
|
||||
|
||||
var anyoneHome = IsAnyoneHome(entry.LastChanged);
|
||||
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
|
||||
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (anyoneHome && !lightAlreadyOn)
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = entry.LastChanged,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Decision,
|
||||
Message = "TURN ON light (sun below horizon + someone home)"
|
||||
});
|
||||
}
|
||||
else if (!anyoneHome)
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = entry.LastChanged,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = "Sun below horizon but nobody home — light stays off"
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = entry.LastChanged,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = "Sun below horizon but light already on"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
previousSunState = entry.State;
|
||||
}
|
||||
}
|
||||
|
||||
private void ReplayPersonArrivals(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var personEntityId in _lightOptions.PersonEntityIds)
|
||||
{
|
||||
var personHistory = _timeline.GetEntityHistory(personEntityId);
|
||||
string? previousState = null;
|
||||
|
||||
foreach (var entry in personHistory)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) break;
|
||||
|
||||
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (string.Equals(entry.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(previousState, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_timeProvider.AdvanceTo(entry.LastChanged);
|
||||
|
||||
var sunEntry = _timeline.GetStateAt(_lightOptions.SunEntityId, entry.LastChanged);
|
||||
var isDark = string.Equals(sunEntry?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
|
||||
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
|
||||
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (isDark && !lightAlreadyOn)
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = entry.LastChanged,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Decision,
|
||||
Message = $"TURN ON light ({personEntityId} arrived home + dark outside)"
|
||||
});
|
||||
}
|
||||
else if (isDark)
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = entry.LastChanged,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = $"{personEntityId} arrived home (dark) but light already on"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
previousState = entry.State;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsAnyoneHome(DateTimeOffset timestamp)
|
||||
{
|
||||
foreach (var personEntityId in _lightOptions.PersonEntityIds)
|
||||
{
|
||||
var entry = _timeline.GetStateAt(personEntityId, timestamp);
|
||||
if (string.Equals(entry?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using System.Globalization;
|
||||
using BoilerMonitor.Models;
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NordPool.Models;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
public sealed class NordPoolReplayRunner : IMonitorReplayRunner
|
||||
{
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
||||
private readonly ILogger<NordPoolReplayRunner> _logger;
|
||||
private readonly ReplayOptions _options;
|
||||
|
||||
public string MonitorName => "NordPool";
|
||||
|
||||
public NordPoolReplayRunner(
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ICheapestIntervalsFinder cheapestIntervalsFinder,
|
||||
ILogger<NordPoolReplayRunner> logger,
|
||||
IOptions<ReplayOptions> options)
|
||||
{
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_cheapestIntervalsFinder = cheapestIntervalsFinder;
|
||||
_logger = logger;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogInformation("Starting NordPool replay");
|
||||
|
||||
var currentTime = _options.StartTime;
|
||||
var interval = TimeSpan.FromMinutes(NordPoolConsts.MinutesPerInterval);
|
||||
double? lastReportedPrice = null;
|
||||
|
||||
while (currentTime <= _options.EndTime && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_timeProvider.AdvanceTo(currentTime);
|
||||
|
||||
var priceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
||||
if (priceEntry?.State is not null &&
|
||||
double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice))
|
||||
{
|
||||
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.001)
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = $"Price: {currentPrice:F2} ct/kWh"
|
||||
});
|
||||
lastReportedPrice = currentPrice;
|
||||
}
|
||||
}
|
||||
|
||||
var boilerConfig = ReadBoilerConfig(currentTime);
|
||||
if (boilerConfig is not null)
|
||||
{
|
||||
var prices = BuildNordPoolPriceFromHistory(currentTime);
|
||||
if (prices.Prices is { Count: > 0 })
|
||||
{
|
||||
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
|
||||
var effectiveIntervalCount = boilerConfig.SkipPriceCap
|
||||
? NordPoolConsts.MaxDailyIntervals
|
||||
: boilerConfig.IntervalCount;
|
||||
|
||||
var cheapest = _cheapestIntervalsFinder.FindCheapestIntervals(
|
||||
prices, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline);
|
||||
|
||||
var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap(
|
||||
cheapest, currentTime.LocalDateTime);
|
||||
|
||||
if (isNowCheap)
|
||||
{
|
||||
var currentInterval = cheapest.FirstOrDefault(i =>
|
||||
currentTime.LocalDateTime >= i.Start && currentTime.LocalDateTime < i.End);
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Decision,
|
||||
Message = $"CHEAP interval active (rank #{currentInterval?.Rank}, price: {currentInterval?.Price:F2} ct/kWh)",
|
||||
Details = $"Total cheap intervals: {cheapest.Count}"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
currentTime = currentTime.Add(interval);
|
||||
}
|
||||
|
||||
_logger.LogInformation("NordPool replay complete");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private BoilerConfig? ReadBoilerConfig(DateTimeOffset timestamp)
|
||||
{
|
||||
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, timestamp);
|
||||
var priceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerPriceCapEntityId, timestamp);
|
||||
var readyByEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerReadyByEntityId, timestamp);
|
||||
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, timestamp);
|
||||
|
||||
if (dailyHoursEntry?.State is null || priceCapEntry?.State is null || readyByEntry?.State is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!double.TryParse(dailyHoursEntry.State, CultureInfo.InvariantCulture, out var dailyHours) ||
|
||||
!double.TryParse(priceCapEntry.State, CultureInfo.InvariantCulture, out var priceCap))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var intervalCount = (int)(dailyHours * NordPoolConsts.IntervalsPerHour);
|
||||
|
||||
if (!TimeSpan.TryParse(readyByEntry.State, CultureInfo.InvariantCulture, out var readyByTime))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var deadline = timestamp.LocalDateTime.Date.Add(readyByTime);
|
||||
if (deadline < timestamp.LocalDateTime)
|
||||
{
|
||||
deadline = deadline.AddDays(1);
|
||||
}
|
||||
|
||||
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
return new BoilerConfig
|
||||
{
|
||||
IntervalCount = intervalCount,
|
||||
PriceCap = priceCap,
|
||||
Deadline = deadline,
|
||||
SkipPriceCap = skipPriceCap
|
||||
};
|
||||
}
|
||||
|
||||
private NordPoolPrice BuildNordPoolPriceFromHistory(DateTimeOffset timestamp)
|
||||
{
|
||||
var nordPoolSensorEntries = _timeline.GetEntityHistory("sensor.nordpool_kwh_lt_eur_3_10_0");
|
||||
var todayDate = timestamp.LocalDateTime.Date;
|
||||
|
||||
var todayPrices = nordPoolSensorEntries
|
||||
.Where(e => e.LastChanged.LocalDateTime.Date == todayDate)
|
||||
.Where(e => e.State is not null && double.TryParse(e.State, CultureInfo.InvariantCulture, out _))
|
||||
.Select(e => new NordPoolDayPrice
|
||||
{
|
||||
Start = e.LastChanged.LocalDateTime,
|
||||
End = e.LastChanged.LocalDateTime.AddMinutes(NordPoolConsts.MinutesPerInterval),
|
||||
Price = double.Parse(e.State!, CultureInfo.InvariantCulture)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return new NordPoolPrice { Prices = todayPrices };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using System.Globalization;
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NordPool.Models;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
public sealed class PowerReplayRunner : IMonitorReplayRunner
|
||||
{
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly IOtherPowerCalculationService _calculationService;
|
||||
private readonly IPowerCostCalculationService _costService;
|
||||
private readonly ILogger<PowerReplayRunner> _logger;
|
||||
private readonly ReplayOptions _replayOptions;
|
||||
private readonly PowerMonitorOptions _powerOptions;
|
||||
|
||||
public string MonitorName => "Power";
|
||||
|
||||
public PowerReplayRunner(
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
IOtherPowerCalculationService calculationService,
|
||||
IPowerCostCalculationService costService,
|
||||
ILogger<PowerReplayRunner> logger,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
IOptions<PowerMonitorOptions> powerOptions)
|
||||
{
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_calculationService = calculationService;
|
||||
_costService = costService;
|
||||
_logger = logger;
|
||||
_replayOptions = replayOptions.Value;
|
||||
_powerOptions = powerOptions.Value;
|
||||
}
|
||||
|
||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogInformation("Starting Power replay");
|
||||
|
||||
var currentTime = _replayOptions.StartTime;
|
||||
var pollInterval = TimeSpan.FromSeconds(_powerOptions.PollIntervalSeconds);
|
||||
DateTime? anomalyStartTime = null;
|
||||
|
||||
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_timeProvider.AdvanceTo(currentTime);
|
||||
|
||||
var mainMeterEntry = _timeline.GetStateAt(_powerOptions.MainMeterEntityId, currentTime);
|
||||
var totalPower = ParseDouble(mainMeterEntry?.State);
|
||||
|
||||
if (!totalPower.HasValue)
|
||||
{
|
||||
currentTime = currentTime.Add(pollInterval);
|
||||
continue;
|
||||
}
|
||||
|
||||
var deviceReadings = DiscoverAndReadDevicePower(currentTime);
|
||||
var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings);
|
||||
|
||||
var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
||||
var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0;
|
||||
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, _powerOptions.PollIntervalSeconds, currentTime.LocalDateTime);
|
||||
|
||||
var isAnomaly = calculation.SmoothedOtherPowerWatts > _powerOptions.AnomalyThresholdWatts;
|
||||
if (isAnomaly && anomalyStartTime is null)
|
||||
{
|
||||
anomalyStartTime = currentTime.LocalDateTime;
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Anomaly,
|
||||
Message = $"Other power {calculation.SmoothedOtherPowerWatts:F0}W exceeds threshold {_powerOptions.AnomalyThresholdWatts}W",
|
||||
Details = $"Total: {calculation.TotalPowerWatts:F0}W, Known: {calculation.KnownDevicesSumWatts:F0}W"
|
||||
});
|
||||
}
|
||||
else if (!isAnomaly && anomalyStartTime is not null)
|
||||
{
|
||||
var duration = currentTime.LocalDateTime - anomalyStartTime.Value;
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = $"Anomaly resolved after {duration:mm\\:ss}"
|
||||
});
|
||||
anomalyStartTime = null;
|
||||
}
|
||||
|
||||
currentTime = currentTime.Add(pollInterval);
|
||||
}
|
||||
|
||||
var totalCost = _costService.GetTotalCostSnapshot();
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = _replayOptions.EndTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = $"Final: Total daily cost {totalCost.CostDaily:F4} EUR"
|
||||
});
|
||||
|
||||
_logger.LogInformation("Power replay complete");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private IReadOnlyDictionary<string, double> DiscoverAndReadDevicePower(DateTimeOffset timestamp)
|
||||
{
|
||||
var readings = new Dictionary<string, double>();
|
||||
|
||||
var allEntities = _timeline.GetEntityIds();
|
||||
foreach (var entityId in allEntities)
|
||||
{
|
||||
if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) ||
|
||||
!entityId.EndsWith("_power", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (string.Equals(entityId, _powerOptions.MainMeterEntityId, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var entry = _timeline.GetStateAt(entityId, timestamp);
|
||||
var value = ParseDouble(entry?.State);
|
||||
if (value.HasValue)
|
||||
{
|
||||
readings[entityId] = value.Value;
|
||||
}
|
||||
}
|
||||
|
||||
return readings;
|
||||
}
|
||||
|
||||
private static double? ParseDouble(string? value)
|
||||
{
|
||||
if (value is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Globalization;
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ShowerMonitor.Models.Enums;
|
||||
using ShowerMonitorManager.Interface;
|
||||
using ShowerMonitorManager.Models;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
public sealed class ShowerReplayRunner : IMonitorReplayRunner
|
||||
{
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly IShowerDetectionService _detectionService;
|
||||
private readonly IExhaustFanControlService _fanControlService;
|
||||
private readonly ILogger<ShowerReplayRunner> _logger;
|
||||
private readonly ReplayOptions _replayOptions;
|
||||
private readonly ShowerMonitorOptions _showerOptions;
|
||||
|
||||
public string MonitorName => "Shower";
|
||||
|
||||
public ShowerReplayRunner(
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
IShowerDetectionService detectionService,
|
||||
IExhaustFanControlService fanControlService,
|
||||
ILogger<ShowerReplayRunner> logger,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
IOptions<ShowerMonitorOptions> showerOptions)
|
||||
{
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_detectionService = detectionService;
|
||||
_fanControlService = fanControlService;
|
||||
_logger = logger;
|
||||
_replayOptions = replayOptions.Value;
|
||||
_showerOptions = showerOptions.Value;
|
||||
}
|
||||
|
||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_logger.LogInformation("Starting Shower replay");
|
||||
|
||||
var currentTime = _replayOptions.StartTime;
|
||||
var pollInterval = TimeSpan.FromSeconds(_showerOptions.PollIntervalSeconds);
|
||||
var previousState = ShowerState.Idle;
|
||||
|
||||
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_timeProvider.AdvanceTo(currentTime);
|
||||
|
||||
var bathroomEntry = _timeline.GetStateAt(_showerOptions.BathroomHumidityEntityId, currentTime);
|
||||
var homeEntry = _timeline.GetStateAt(_showerOptions.MainHomeHumidityEntityId, currentTime);
|
||||
|
||||
var bathroomHumidity = ParseDouble(bathroomEntry?.State);
|
||||
var homeHumidity = ParseDouble(homeEntry?.State);
|
||||
|
||||
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
|
||||
{
|
||||
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
|
||||
var differential = bathroomHumidity.Value - homeHumidity.Value;
|
||||
|
||||
_fanControlService.Evaluate(state, currentTime);
|
||||
|
||||
if (state != previousState)
|
||||
{
|
||||
var eventType = state switch
|
||||
{
|
||||
ShowerState.Active => ReplayEventType.Decision,
|
||||
ShowerState.Completed => ReplayEventType.StateChange,
|
||||
_ => ReplayEventType.Info
|
||||
};
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = eventType,
|
||||
Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
|
||||
Details = GetStateChangeDetails(state)
|
||||
});
|
||||
|
||||
previousState = state;
|
||||
}
|
||||
}
|
||||
|
||||
currentTime = currentTime.Add(pollInterval);
|
||||
}
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = _replayOptions.EndTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = $"Final: {_detectionService.TodaySessionCount} session(s) detected"
|
||||
});
|
||||
|
||||
_logger.LogInformation("Shower replay complete");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private string? GetStateChangeDetails(ShowerState state) =>
|
||||
state switch
|
||||
{
|
||||
ShowerState.Completed when _detectionService.LastCompletedSession is not null =>
|
||||
$"Duration: {_detectionService.LastCompletedSession.Duration:mm\\:ss}, Peak humidity: {_detectionService.LastCompletedSession.PeakHumidity:F1}%",
|
||||
_ => null
|
||||
};
|
||||
|
||||
private static double? ParseDouble(string? value)
|
||||
{
|
||||
if (value is null or "unavailable" or "unknown")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"HomeAssistant": {
|
||||
"Host": "homeassistant.local",
|
||||
"Port": 8123,
|
||||
"Token": "<your-long-lived-access-token>",
|
||||
"Ssl": false
|
||||
},
|
||||
"Replay": {
|
||||
"StartTime": "2026-03-30T00:00:00+02:00",
|
||||
"EndTime": "2026-03-31T00:00:00+02:00",
|
||||
"Monitors": {
|
||||
"NordPool": true,
|
||||
"Boiler": true,
|
||||
"Shower": true,
|
||||
"Power": false,
|
||||
"Light": true
|
||||
}
|
||||
},
|
||||
"BoilerMonitor": {
|
||||
"Enabled": true,
|
||||
"CleanupEntitiesOnStartup": false
|
||||
},
|
||||
"ShowerMonitor": {
|
||||
"Enabled": true,
|
||||
"CleanupEntitiesOnStartup": false,
|
||||
"BathroomHumidityEntityId": "sensor.bathroom_humidity",
|
||||
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
|
||||
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
|
||||
"ExhaustFanEntityId": "switch.exhaust_fan",
|
||||
"PollIntervalSeconds": 30,
|
||||
"SpikeRateThreshold": 4.0,
|
||||
"MinDifferentialHumidity": 8.0,
|
||||
"PeakHumidityThreshold": 58.0,
|
||||
"ConfirmationWindowMinutes": 2,
|
||||
"RecoveryDifferentialThreshold": 5.0,
|
||||
"MaxShowerDurationMinutes": 60,
|
||||
"FanRunAfterShowerMinutes": 10,
|
||||
"RateWindowSize": 5
|
||||
},
|
||||
"LightMonitor": {
|
||||
"Enabled": true,
|
||||
"LightEntityId": "light.sonoff_1002214d40",
|
||||
"SunEntityId": "sun.sun",
|
||||
"PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"]
|
||||
},
|
||||
"PowerMonitor": {
|
||||
"Enabled": false,
|
||||
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
||||
"PollIntervalSeconds": 1,
|
||||
"SmoothingWindowSize": 10,
|
||||
"AnomalyThresholdWatts": 500,
|
||||
"ExcludedSensorPatterns": [
|
||||
"sensor.nordpool_*",
|
||||
"sensor.powermonitor_*"
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user