119 lines
2.8 KiB
C#
119 lines
2.8 KiB
C#
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
|
|
public sealed class HistoryTimeline
|
|
{
|
|
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
|
|
private bool _sorted;
|
|
|
|
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
|
|
{
|
|
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
|
{
|
|
list = [];
|
|
_entityTimelines[entityId] = list;
|
|
}
|
|
|
|
list.AddRange(entries);
|
|
_sorted = false;
|
|
}
|
|
|
|
public void AddEntriesBulk(string entityId, List<HistoryStateEntry> entries)
|
|
{
|
|
if (entries.Count == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
|
{
|
|
_entityTimelines[entityId] = entries;
|
|
}
|
|
else
|
|
{
|
|
list.AddRange(entries);
|
|
}
|
|
|
|
_sorted = false;
|
|
}
|
|
|
|
public void FinalizeSort()
|
|
{
|
|
if (_sorted)
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var entries in _entityTimelines.Values)
|
|
{
|
|
entries.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
|
}
|
|
|
|
_sorted = true;
|
|
}
|
|
|
|
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
|
|
{
|
|
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var index = BinarySearchFloor(entries, timestamp);
|
|
return index >= 0 ? entries[index] : null;
|
|
}
|
|
|
|
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);
|
|
|
|
public void Clear()
|
|
{
|
|
_entityTimelines.Clear();
|
|
_sorted = false;
|
|
}
|
|
|
|
private static int BinarySearchFloor(List<HistoryStateEntry> entries, DateTimeOffset timestamp)
|
|
{
|
|
var lo = 0;
|
|
var hi = entries.Count - 1;
|
|
var result = -1;
|
|
|
|
while (lo <= hi)
|
|
{
|
|
var mid = lo + (hi - lo) / 2;
|
|
|
|
if (entries[mid].LastChanged <= timestamp)
|
|
{
|
|
result = mid;
|
|
lo = mid + 1;
|
|
}
|
|
else
|
|
{
|
|
hi = mid - 1;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
}
|