Create the hourly Data class

This commit is contained in:
atef 2023-12-14 16:40:34 +01:00
parent 137e9711c2
commit bc9b3b95b9
1 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,92 @@
using System.Text.Json;
using InnovEnergy.App.SaliMax.Devices;
using InnovEnergy.Lib.Utils;
using static System.Text.Json.JsonSerializer;
namespace InnovEnergy.App.SaliMax.AggregationService;
// shut up trim warnings
#pragma warning disable IL2026
public class HourlyData //TODO: let IE choose from config files (Json) and connect to GUI
{
private static String DefaultHDataPath => Path.Combine(Environment.CurrentDirectory, "HourlyData/config.json");
private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
public required Double MinSoc { get; set; }
public required Double MaxChargeBatteryVoltage { get; set; }
public required Double MinDischargeBatteryVoltage { get; set; }
private static String? LastSavedData { get; set; }
#if DEBUG
public static HourlyData Default => new()
{
MinSoc = 20,
MaxChargeBatteryVoltage = 0,
MinDischargeBatteryVoltage = 0
};
#else
public static HourlyData Default => new()
{
MinSoc = 20,
MaxChargeBatteryVoltage = 0,
MinDischargeBatteryVoltage = 0
};
#endif
public void Save(String? path = null)
{
var dataFilePath = path ?? DefaultHDataPath;
try
{
var jsonString = Serialize(this, JsonOptions);
if (LastSavedData == jsonString)
return;
LastSavedData = jsonString;
File.WriteAllText(dataFilePath, jsonString);
}
catch (Exception e)
{
$"Failed to write config file {dataFilePath}\n{e}".LogInfo();
throw;
}
}
public static HourlyData Load(String? path = null)
{
var dataFilePath = path ?? DefaultHDataPath;
try
{
var jsonString = File.ReadAllText(dataFilePath);
return Deserialize<HourlyData>(jsonString)!;
}
catch (Exception e)
{
$"Failed to read config file {dataFilePath}, using default config\n{e}".WriteLine();
return Default;
}
}
public static async Task<HourlyData> LoadAsync(String? path = null)
{
var dataFilePath = path ?? DefaultHDataPath;
try
{
var jsonString = await File.ReadAllTextAsync(dataFilePath);
return Deserialize<HourlyData>(jsonString)!;
}
catch (Exception e)
{
Console.WriteLine($"Couldn't read config file {dataFilePath}, using default config");
e.Message.WriteLine();
return Default;
}
}
}