feat: add PowerCostCalculationService with per-device cost accumulators
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,256 @@
|
||||
using FluentAssertions;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerCostCalculationServiceTests
|
||||
{
|
||||
private readonly PowerCostCalculationService _sut = new();
|
||||
|
||||
private static PowerCalculationResult CreateResult(
|
||||
double totalWatts = 1000,
|
||||
double smoothedOtherWatts = 200,
|
||||
Dictionary<string, double>? deviceReadings = null)
|
||||
{
|
||||
var readings = deviceReadings ?? new Dictionary<string, double>
|
||||
{
|
||||
["sensor.device_a_power"] = 500,
|
||||
["sensor.device_b_power"] = 300
|
||||
};
|
||||
|
||||
return new PowerCalculationResult
|
||||
{
|
||||
TotalPowerWatts = totalWatts,
|
||||
KnownDevicesSumWatts = readings.Values.Sum(),
|
||||
RawOtherPowerWatts = smoothedOtherWatts,
|
||||
SmoothedOtherPowerWatts = smoothedOtherWatts,
|
||||
DataQuality = "ok",
|
||||
DevicePowerReadings = readings
|
||||
};
|
||||
}
|
||||
|
||||
#region CalculateCostIncrement
|
||||
|
||||
[Fact]
|
||||
public void CalculateCostIncrement_ShouldComputeCorrectCost()
|
||||
{
|
||||
var cost = PowerCostCalculationService.CalculateCostIncrement(
|
||||
powerWatts: 1000,
|
||||
pricePerKwh: 0.10,
|
||||
pollIntervalSeconds: PowerMonitorConsts.DefaultPollIntervalSeconds);
|
||||
|
||||
var expected = (1000.0 / PowerMonitorConsts.WattsPerKilowatt)
|
||||
* 0.10
|
||||
* ((double)PowerMonitorConsts.DefaultPollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
cost.Should().BeApproximately(expected, 0.000001);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CalculateCostIncrement_WithZeroPower_ShouldReturnZero()
|
||||
{
|
||||
var cost = PowerCostCalculationService.CalculateCostIncrement(0, 0.10, 15);
|
||||
cost.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CalculateCostIncrement_WithZeroPrice_ShouldReturnZero()
|
||||
{
|
||||
var cost = PowerCostCalculationService.CalculateCostIncrement(1000, 0, 15);
|
||||
cost.Should().Be(0);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region RecordCosts
|
||||
|
||||
[Fact]
|
||||
public void RecordCosts_ShouldCreateTotalAndOtherSnapshots()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result = CreateResult();
|
||||
|
||||
_sut.RecordCosts(result, 0.10, 15, now);
|
||||
|
||||
var totalSnapshot = _sut.GetTotalCostSnapshot();
|
||||
totalSnapshot.CostDaily.Should().BeGreaterThan(0);
|
||||
|
||||
var otherSnapshot = _sut.GetOtherCostSnapshot();
|
||||
otherSnapshot.CostDaily.Should().BeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordCosts_ShouldCreateDeviceSnapshots()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result = CreateResult();
|
||||
|
||||
_sut.RecordCosts(result, 0.10, 15, now);
|
||||
|
||||
var deviceA = _sut.GetDeviceCostSnapshot("sensor.device_a_power");
|
||||
deviceA.CostDaily.Should().BeGreaterThan(0);
|
||||
|
||||
var deviceB = _sut.GetDeviceCostSnapshot("sensor.device_b_power");
|
||||
deviceB.CostDaily.Should().BeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordCosts_TotalCostShouldBeHigherThanOtherCost()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result = CreateResult(totalWatts: 1000, smoothedOtherWatts: 200);
|
||||
|
||||
_sut.RecordCosts(result, 0.10, 15, now);
|
||||
|
||||
var total = _sut.GetTotalCostSnapshot();
|
||||
var other = _sut.GetOtherCostSnapshot();
|
||||
total.CostDaily.Should().BeGreaterThan(other.CostDaily);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordCosts_MultipleCalls_ShouldAccumulate()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result = CreateResult();
|
||||
|
||||
_sut.RecordCosts(result, 0.10, 15, now);
|
||||
var firstCost = _sut.GetTotalCostSnapshot().CostDaily;
|
||||
|
||||
_sut.RecordCosts(result, 0.10, 15, now.AddSeconds(15));
|
||||
var secondCost = _sut.GetTotalCostSnapshot().CostDaily;
|
||||
|
||||
secondCost.Should().BeApproximately(firstCost * 2, 0.000001);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordCosts_NewDeviceAppearing_ShouldCreateAccumulator()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result1 = CreateResult(deviceReadings: new Dictionary<string, double>
|
||||
{
|
||||
["sensor.device_a_power"] = 500
|
||||
});
|
||||
|
||||
_sut.RecordCosts(result1, 0.10, 15, now);
|
||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
|
||||
|
||||
var result2 = CreateResult(deviceReadings: new Dictionary<string, double>
|
||||
{
|
||||
["sensor.device_a_power"] = 500,
|
||||
["sensor.device_b_power"] = 300
|
||||
});
|
||||
|
||||
_sut.RecordCosts(result2, 0.10, 15, now.AddSeconds(15));
|
||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Price management
|
||||
|
||||
[Fact]
|
||||
public void RecordCosts_WithValidPrice_ShouldUpdateLastKnownPrice()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result = CreateResult();
|
||||
|
||||
_sut.RecordCosts(result, 0.15, 15, now);
|
||||
|
||||
_sut.LastKnownPrice.Should().Be(0.15);
|
||||
_sut.PriceSource.Should().Be("live");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordCosts_WithZeroPrice_ShouldUseFallback()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result = CreateResult();
|
||||
|
||||
_sut.RecordCosts(result, 0.10, 15, now);
|
||||
_sut.RecordCosts(result, 0, 15, now.AddSeconds(15));
|
||||
|
||||
_sut.LastKnownPrice.Should().Be(0.10);
|
||||
_sut.PriceSource.Should().Be("live");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetPrice_ShouldUpdatePriceAndMarkAsStale()
|
||||
{
|
||||
_sut.SetPrice(0.20);
|
||||
|
||||
_sut.LastKnownPrice.Should().Be(0.20);
|
||||
_sut.PriceSource.Should().Be("stale");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetAllDeviceCostSnapshots
|
||||
|
||||
[Fact]
|
||||
public void GetAllDeviceCostSnapshots_WhenEmpty_ShouldReturnEmpty()
|
||||
{
|
||||
_sut.GetAllDeviceCostSnapshots().Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDeviceCostSnapshot_UnknownDevice_ShouldReturnEmptySnapshot()
|
||||
{
|
||||
var snapshot = _sut.GetDeviceCostSnapshot("sensor.unknown");
|
||||
snapshot.CostDaily.Should().Be(0);
|
||||
snapshot.PartialWindow.Should().BeTrue();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Snapshot defaults
|
||||
|
||||
[Fact]
|
||||
public void GetTotalCostSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot()
|
||||
{
|
||||
var snapshot = _sut.GetTotalCostSnapshot();
|
||||
snapshot.CostDaily.Should().Be(0);
|
||||
snapshot.PartialWindow.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetOtherCostSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot()
|
||||
{
|
||||
var snapshot = _sut.GetOtherCostSnapshot();
|
||||
snapshot.CostDaily.Should().Be(0);
|
||||
snapshot.PartialWindow.Should().BeTrue();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Thread safety
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData()
|
||||
{
|
||||
var now = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
var result = CreateResult(totalWatts: 1000, smoothedOtherWatts: 200);
|
||||
const int callsPerThread = 100;
|
||||
const int threadCount = 10;
|
||||
|
||||
var tasks = Enumerable.Range(0, threadCount)
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++)
|
||||
{
|
||||
_sut.RecordCosts(result, 0.10, 15, now.AddSeconds(1));
|
||||
}
|
||||
}))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
var total = _sut.GetTotalCostSnapshot();
|
||||
total.CostDaily.Should().BeGreaterThan(0);
|
||||
|
||||
var devices = _sut.GetAllDeviceCostSnapshots();
|
||||
devices.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerCostCalculationService
|
||||
{
|
||||
void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now);
|
||||
CostSnapshot GetTotalCostSnapshot();
|
||||
CostSnapshot GetOtherCostSnapshot();
|
||||
CostSnapshot GetDeviceCostSnapshot(string entityId);
|
||||
IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots();
|
||||
double LastKnownPrice { get; }
|
||||
string PriceSource { get; }
|
||||
void SetPrice(double price);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Collections.Concurrent;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public sealed class PowerCostCalculationService : IPowerCostCalculationService
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
|
||||
private CostAccumulator? _totalAccumulator;
|
||||
private CostAccumulator? _otherAccumulator;
|
||||
|
||||
private double _lastKnownPrice;
|
||||
private string _priceSource = "live";
|
||||
private readonly object _priceLock = new();
|
||||
|
||||
public double LastKnownPrice
|
||||
{
|
||||
get { lock (_priceLock) { return _lastKnownPrice; } }
|
||||
}
|
||||
|
||||
public string PriceSource
|
||||
{
|
||||
get { lock (_priceLock) { return _priceSource; } }
|
||||
}
|
||||
|
||||
public void SetPrice(double price)
|
||||
{
|
||||
lock (_priceLock)
|
||||
{
|
||||
_lastKnownPrice = price;
|
||||
_priceSource = "stale";
|
||||
}
|
||||
}
|
||||
|
||||
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now)
|
||||
{
|
||||
lock (_priceLock)
|
||||
{
|
||||
if (nordPoolPrice > 0)
|
||||
{
|
||||
_lastKnownPrice = nordPoolPrice;
|
||||
_priceSource = "live";
|
||||
}
|
||||
}
|
||||
|
||||
var effectivePrice = nordPoolPrice > 0 ? nordPoolPrice : LastKnownPrice;
|
||||
|
||||
var totalCost = CalculateCostIncrement(calculation.TotalPowerWatts, effectivePrice, pollIntervalSeconds);
|
||||
GetOrCreateTotalAccumulator(now).AddCost(totalCost, now);
|
||||
|
||||
var otherCost = CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
|
||||
GetOrCreateOtherAccumulator(now).AddCost(otherCost, now);
|
||||
|
||||
foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings)
|
||||
{
|
||||
var deviceCost = CalculateCostIncrement(powerWatts, effectivePrice, pollIntervalSeconds);
|
||||
var accumulator = _deviceAccumulators.GetOrAdd(entityId, _ => new CostAccumulator(now));
|
||||
accumulator.AddCost(deviceCost, now);
|
||||
}
|
||||
}
|
||||
|
||||
public CostSnapshot GetTotalCostSnapshot()
|
||||
{
|
||||
return _totalAccumulator?.GetSnapshot() ?? CreateEmptySnapshot();
|
||||
}
|
||||
|
||||
public CostSnapshot GetOtherCostSnapshot()
|
||||
{
|
||||
return _otherAccumulator?.GetSnapshot() ?? CreateEmptySnapshot();
|
||||
}
|
||||
|
||||
public CostSnapshot GetDeviceCostSnapshot(string entityId)
|
||||
{
|
||||
return _deviceAccumulators.TryGetValue(entityId, out var accumulator)
|
||||
? accumulator.GetSnapshot()
|
||||
: CreateEmptySnapshot();
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots()
|
||||
{
|
||||
return _deviceAccumulators.ToDictionary(
|
||||
kvp => kvp.Key,
|
||||
kvp => kvp.Value.GetSnapshot());
|
||||
}
|
||||
|
||||
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
|
||||
{
|
||||
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
|
||||
return powerKw * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
}
|
||||
|
||||
private CostAccumulator GetOrCreateTotalAccumulator(DateTime now)
|
||||
{
|
||||
return _totalAccumulator ??= new CostAccumulator(now);
|
||||
}
|
||||
|
||||
private CostAccumulator GetOrCreateOtherAccumulator(DateTime now)
|
||||
{
|
||||
return _otherAccumulator ??= new CostAccumulator(now);
|
||||
}
|
||||
|
||||
private static CostSnapshot CreateEmptySnapshot()
|
||||
{
|
||||
return new CostSnapshot { PartialWindow = true };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user