Files
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

253 lines
9.1 KiB
C#

#region
using System.Text.Json;
using PowerMonitor.Models;
using PowerMonitorManager;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitor.Manager.Tests;
/// <summary>
/// Shared, deterministic datasets and builders used by the PowerMonitor tests.
/// Keeping the builders and generated series here avoids copy-pasted setup and
/// hard-coded clocks across test classes.
/// </summary>
internal static class PowerMonitorTestData
{
public const double DefaultTotalWatts = 341.97;
public const double DefaultSmoothedOtherWatts = 131.04;
public const double DefaultPricePerKwh = 0.1791;
public const string BoilerSwitchEntityId = "switch.sonoff_1002230e32";
public const string AutoManagementEntityId = "switch.boilermonitor_auto_management";
public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power";
public static readonly DateTime FixedNow = new DateTime(2026, 3, 17, 10, 0, 0);
public static readonly DateTime FixedDayStart = new DateTime(2026, 3, 17, 0, 0, 0);
public static readonly DateTimeOffset FixedUtcNow = new DateTimeOffset(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
/// <summary>
/// Two-device reading set used by the cost calculation tests.
/// </summary>
public static IReadOnlyDictionary<string, double> CreateCostDeviceReadings()
{
return new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 101.0,
["sensor.sonoff_10018909cb_power"] = 109.93
};
}
/// <summary>
/// Realistic seven-device reading set used by the entity projection tests.
/// </summary>
private static Dictionary<string, double> CreateDeviceReadings()
{
return new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93,
["sensor.tv_power"] = 101.0,
["sensor.akvariumas_power"] = 21.0,
["sensor.sonoff_1002230a48_power"] = 20.06,
["sensor.temp_power"] = 14.0,
["sensor.balkony_laps_power"] = 9.39
};
}
public static IReadOnlyDictionary<string, double> CreateReadings(params (string EntityId, double Watts)[] readings)
{
return readings.ToDictionary(r => r.EntityId, r => r.Watts);
}
public static PowerCalculationResult CreateCalculation(
double totalWatts = DefaultTotalWatts,
double smoothedOtherWatts = DefaultSmoothedOtherWatts,
IReadOnlyDictionary<string, double>? deviceReadings = null,
string dataQuality = "ok")
{
var readings = deviceReadings ?? CreateCostDeviceReadings();
return new PowerCalculationResult
{
TotalPowerWatts = totalWatts,
KnownDevicesSumWatts = readings.Values.Sum(),
RawOtherPowerWatts = smoothedOtherWatts,
SmoothedOtherPowerWatts = smoothedOtherWatts,
DataQuality = dataQuality,
DevicePowerReadings = readings
};
}
private static CostSnapshot CreateCostSnapshot(
double cost15Min = 0.001,
double cost1Hour = 0.004,
double costDaily = 0.03,
double costMonthly = 0.9,
bool partialWindow = true)
{
return new CostSnapshot
{
Cost15Min = cost15Min,
Cost1Hour = cost1Hour,
CostDaily = costDaily,
CostMonthly = costMonthly,
PartialWindow = partialWindow
};
}
public static PowerUpdateContext CreateUpdateContext(
bool isAnomaly = false,
double totalWatts = DefaultTotalWatts,
double smoothedOtherWatts = 128.5,
string systemStatus = "ok",
IReadOnlyDictionary<string, double>? deviceReadings = null,
double currentNordPoolPrice = DefaultPricePerKwh,
string priceSource = "live")
{
var readings = deviceReadings ?? CreateDeviceReadings();
var deviceCosts = readings
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
0.0005 * (index + 1),
0.002 * (index + 1),
0.03 * (index + 1),
0.9 * (index + 1))))
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
return new PowerUpdateContext
{
Calculation = CreateCalculation(totalWatts, smoothedOtherWatts, readings),
CurrentNordPoolPrice = currentNordPoolPrice,
PriceUnit = "EUR/kWh",
PriceSource = priceSource,
DeviceCosts = deviceCosts,
TotalCost = CreateCostSnapshot(0.02, 0.08, 1.00, 30.0),
OtherCost = CreateCostSnapshot(0.008, 0.031, 0.38, 11.4),
IsAnomaly = isAnomaly,
AnomalyDuration = TimeSpan.Zero,
AnomalyThresholdWatts = PowerMonitorConsts.DefaultAnomalyThresholdWatts,
TrackedSensorCount = readings.Count,
DegradedSensors = [],
SystemStatus = systemStatus
};
}
public static PowerMonitorOptions CreateOptions(Action<PowerMonitorOptions>? configure = null)
{
var options = new PowerMonitorOptions
{
Enabled = true,
MainMeterEntityId = MainMeterEntityId,
ExcludedSensorPatterns = ["sensor.nordpool_*", "sensor.powermonitor_*"]
};
configure?.Invoke(options);
return options;
}
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null)
{
return CreateOptions(options =>
{
options.EnforceLimitEnabled = true;
options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts;
options.RecoverySeconds = PowerMonitorConsts.DefaultRecoverySeconds;
options.LimitCooldownSeconds = PowerMonitorConsts.DefaultLimitCooldownSeconds;
options.EnforceSwitchOffEntityIds = [BoilerSwitchEntityId];
options.PauseAndRestoreEntityIds = [AutoManagementEntityId];
configure?.Invoke(options);
});
}
public static PowerSensorInfo CreateSensor(
string entityId,
string? friendlyName = null,
string? deviceName = null,
string unitOfMeasurement = PowerMonitorConsts.WattUnit)
{
return new PowerSensorInfo
{
EntityId = entityId,
FriendlyName = friendlyName ?? entityId,
DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId),
UnitOfMeasurement = unitOfMeasurement
};
}
public static JsonElement CreateAttributesJson(
string? deviceClass,
string? unitOfMeasurement,
string? friendlyName)
{
var attributes = new Dictionary<string, object?>();
if (deviceClass is not null)
{
attributes["device_class"] = deviceClass;
}
if (unitOfMeasurement is not null)
{
attributes["unit_of_measurement"] = unitOfMeasurement;
}
if (friendlyName is not null)
{
attributes["friendly_name"] = friendlyName;
}
return JsonSerializer.SerializeToElement(attributes);
}
/// <summary>
/// Deterministic, strictly positive and monotonically increasing power samples
/// used by the looping scenarios.
/// </summary>
public static IReadOnlyList<double> CreatePowerSampleSeries(int count = 96)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
];
}
/// <summary>
/// Deterministic, strictly positive hourly tariff series (EUR/kWh).
/// </summary>
private static IReadOnlyList<double> CreateTariffPriceSeries(int count = 24)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
];
}
public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart)
{
var prices = CreateTariffPriceSeries();
return
[
.. Enumerable.Range(0, prices.Count)
.Select(hour => (dayStart.AddHours(hour), prices[hour]))
];
}
public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => start.AddMinutes(i * intervalMinutes))
];
}
}