Files
HomeAssistant/PowerMonitor.Manager/Models/CostAccumulator.cs
T
gitea_admin 24729ee267 Apply code formatting cleanup across monitor projects
- Reindent appsettings.json and the MSBuild project files
- Collapse single-statement guard blocks and tidy using and member order
- Normalize XML doc indentation and file endings
- Reorder BatteryMonitor test-data helpers and move the exclusion tests into
  their own region
- Carry the same formatting through the boiler config, control, entity and
  test files
2026-11-30 11:52:06 +02:00

108 lines
3.0 KiB
C#

namespace PowerMonitorManager.Models;
public sealed class CostAccumulator(DateTime now)
{
private readonly Lock _lock = new();
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;
}
}