Files
HomeAssistant/PowerMonitor.Manager/Models/CostAccumulator.cs
T
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00

112 lines
3.0 KiB
C#

namespace PowerMonitorManager.Models;
public sealed class CostAccumulator(DateTime now)
{
private readonly Lock _lock = new Lock();
private double _cost15Min;
private double _cost1Hour;
private double _costDaily;
private double _costMonthly;
private DateTime _last15MinReset = now;
private DateTime _last1HourReset = now;
private DateTime _lastDailyReset = now;
private DateTime _lastMonthlyReset = now;
private bool _partialWindow = true;
private double _previous15Min;
private double _previous1Hour;
private double _previousDaily;
private double _previousMonthly;
public void AddCost(double costIncrement, DateTime now)
{
lock (_lock)
{
CheckAndResetWindows(now);
_cost15Min += costIncrement;
_cost1Hour += costIncrement;
_costDaily += costIncrement;
_costMonthly += costIncrement;
}
}
public CostSnapshot GetSnapshot()
{
lock (_lock)
{
return new CostSnapshot
{
Cost15Min = _cost15Min,
Cost1Hour = _cost1Hour,
CostDaily = _costDaily,
CostMonthly = _costMonthly,
Previous15Min = _previous15Min,
Previous1Hour = _previous1Hour,
PreviousDaily = _previousDaily,
PreviousMonthly = _previousMonthly,
PartialWindow = _partialWindow
};
}
}
private void CheckAndResetWindows(DateTime now)
{
if (IsNew15MinWindow(now, _last15MinReset))
{
_previous15Min = _cost15Min;
_cost15Min = 0;
_last15MinReset = now;
_partialWindow = false;
}
if (IsNewHourWindow(now, _last1HourReset))
{
_previous1Hour = _cost1Hour;
_cost1Hour = 0;
_last1HourReset = now;
}
if (IsNewDayWindow(now, _lastDailyReset))
{
_previousDaily = _costDaily;
_costDaily = 0;
_lastDailyReset = now;
}
if (!IsNewMonthWindow(now, _lastMonthlyReset))
{
return;
}
_previousMonthly = _costMonthly;
_costMonthly = 0;
_lastMonthlyReset = now;
}
internal static bool IsNew15MinWindow(DateTime now, DateTime lastReset)
{
var currentSlot = now.Minute / 15;
var lastSlot = lastReset.Minute / 15;
return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot;
}
internal static bool IsNewHourWindow(DateTime now, DateTime lastReset)
{
return now.Date != lastReset.Date || now.Hour != lastReset.Hour;
}
internal static bool IsNewDayWindow(DateTime now, DateTime lastReset)
{
return now.Date != lastReset.Date;
}
internal static bool IsNewMonthWindow(DateTime now, DateTime lastReset)
{
return now.Year != lastReset.Year || now.Month != lastReset.Month;
}
}