Innovenergy_trunk/csharp/App/VrmGrabber/Database/Db.cs

300 lines
10 KiB
C#
Raw Normal View History

2023-04-27 14:59:45 +00:00
using System.Diagnostics.CodeAnalysis;
using System.IO.Enumeration;
2023-06-01 13:29:39 +00:00
using System.Runtime.InteropServices;
2023-09-08 09:56:49 +00:00
using System.Text.Json.Nodes;
using System.Web;
2023-05-11 13:41:41 +00:00
using CliWrap;
using CliWrap.Buffered;
using InnovEnergy.App.RemoteSupportConsole;
2023-04-27 14:59:45 +00:00
using InnovEnergy.Lib.Utils;
using InnovEnergy.Lib.Victron.VictronVRM;
using SQLite;
2023-05-04 15:22:58 +00:00
using static System.Text.Json.JsonSerializer;
2023-06-01 13:29:39 +00:00
using static InnovEnergy.App.VrmGrabber.Database.Systemd;
2023-05-04 15:22:58 +00:00
using Installation = InnovEnergy.App.VrmGrabber.DataTypes.Installation;
using VrmInstallation = InnovEnergy.Lib.Victron.VictronVRM.Installation;
using FILE=System.IO.File;
2023-04-27 14:59:45 +00:00
2023-05-04 15:22:58 +00:00
namespace InnovEnergy.App.VrmGrabber.Database;
2023-04-27 14:59:45 +00:00
2023-06-01 13:29:39 +00:00
public static class Systemd
{
[DllImport("libsystemd.so.0", CharSet = CharSet.Unicode)]
public static extern Int32 sd_notify(Int32 unsetEnvironment, String state);
}
public class InstallationDetails
{
public InstallationDetails(String? ip, IReadOnlyList<Detail> details)
{
Details = details;
Ip = ip;
}
public IReadOnlyList<Detail>? Details { get; set; }
public String? Ip { get; set; }
}
2023-04-27 14:59:45 +00:00
public static partial class Db
2023-04-27 14:59:45 +00:00
{
public static Dictionary<Installation, InstallationDetails> InstallationsAndDetails;
private const String DbPath = "./db.sqlite";
private static SQLiteConnection Connection { get; } = new SQLiteConnection(DbPath);
public static TableQuery<Installation> Installations => Connection.Table<Installation>();
public static void Init()
{
// used to force static constructor
}
static Db()
{
// on startup create/migrate tables
Connection.RunInTransaction(() => { Connection.CreateTable<Installation>(); });
}
2023-06-01 13:29:39 +00:00
public static async Task UpdateDetailsAndInstallations()
2023-04-27 14:59:45 +00:00
{
2023-06-01 13:29:39 +00:00
sd_notify(0, "READY=1");
do {
await UpdateInstallationsAndDetailsFromVrm(0);
}
2023-05-25 12:50:20 +00:00
while (true) ;
2023-04-27 14:59:45 +00:00
}
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")]
private static async Task UpdateInstallationsAndDetailsFromVrm(Int32 _)
2023-04-27 14:59:45 +00:00
{
2023-06-01 13:29:39 +00:00
var user = await GetVrmAccount();
var readOnlyInstallations = await user.GetInstallations();
var installations = readOnlyInstallations.ToList();
2023-08-23 09:31:30 +00:00
installations.Shuffle(); // This
foreach (var installation in installations)
{
Console.WriteLine(installation.Name);
sd_notify(0, "WATCHDOG=1");
var details = await GetInstallationDetails(installation);
// Thread.Sleep(1000);
await UpdateAlarms(installation);
var ip = Ip(details);
var updatedInstallation = new Installation(
installation.Name,
ip[0],
(Int64)installation.IdSite,
installation.Identifier,
details.Details.MachineSerial() ?? "Unknown",
2023-08-23 09:31:30 +00:00
HttpUtility.UrlEncode(installation.Name),
ip[1],
details.Details.Last().Json["timestamp"].ToString(),
Serialize(details.Details),
await NumberOfBatteries(ip[0], ip[1]),
2023-08-23 09:31:30 +00:00
await BatteryFirmwareVersion(ip[0], ip[1]),
"No updates"
);
if (ip[0] != "Unknown")
await UpdateInstallationName(installation, ip[0]);
if (GetInstallationByIdentifier(installation.Identifier) == null)
{
Create(updatedInstallation);
}
else
{
Update(updatedInstallation);
}
}
}
[RequiresUnreferencedCode(
"Calls System.Text.Json.JsonSerializer.SerializeToElement<TValue>(TValue, JsonSerializerOptions)")]
public static async Task<Boolean> UpdateAlarms(VrmInstallation installation)
2023-09-08 09:56:49 +00:00
{
// installation.GetDevices().batteryMonitor.setTemperatureAlarms(245,250,315,313);
var alarmJson = JsonNode.Parse(File.ReadAllText("./alarm.json"))!.AsObject();
2023-09-08 09:56:49 +00:00
var tags = await installation.GetTags();
if (tags.Contains("FM-AF09"))
{
// Console.WriteLine(installation.IdSite.ToString());
// await installation.GetAlarms();
2023-09-08 09:56:49 +00:00
return await installation.SetAlarms(alarmJson);
}
2023-09-08 09:56:49 +00:00
return true;
}
2023-06-01 13:29:39 +00:00
public static async Task<VrmAccount> GetVrmAccount()
{
var fileContent = await File.ReadAllTextAsync("./token.json");
var acc = Deserialize<AccToken>(fileContent);
var user = VrmAccount.Token(acc!.idUser, acc.token);
return user;
}
private static async Task<String> BatteryFirmwareVersion(String? ip, String? online)
{
if (ip is null or "Unknown" || online == "❌") return "Unknown";
var pathToBattery = await ExecuteBufferedAsyncCommandOnIp(ip, "dbus-send --system --dest=com.victronenergy.system --type=method_call --print-reply /ServiceMapping/com_victronenergy_battery_1 com.victronenergy.BusItem.GetText");
2023-05-25 12:49:40 +00:00
if (pathToBattery.Split('"')[1].StartsWith("Error")) return "Unknown";
2023-05-25 12:49:40 +00:00
var command = $"dbus-send --system --dest={pathToBattery.Split('"')[1]} --type=method_call --print-reply /FirmwareVersion com.victronenergy.BusItem.GetText";
var returnString = await ExecuteBufferedAsyncCommandOnIp(ip, command);
var returnStringShortened = returnString.Split('"')[1];
return returnStringShortened.Length > 10 ? "Unknown" : returnStringShortened;
}
private static async Task<String> NumberOfBatteries(String? ip, String? online)
{
if (ip is null or "Unknown" || online == "❌") return "Failed";
var pathToBattery = await ExecuteBufferedAsyncCommandOnIp(ip, "dbus-send --system --dest=com.victronenergy.system --type=method_call --print-reply /ServiceMapping/com_victronenergy_battery_1 com.victronenergy.BusItem.GetText");
if (pathToBattery.Split('"')[1].StartsWith("Error")) return "Failed";
2023-05-25 12:49:40 +00:00
var cmd = await ExecuteBufferedAsyncCommandOnIp(ip,$"dbus-send --system --dest={pathToBattery.Split('"')[1]} --type=method_call --print-reply /NbOfBatteries com.victronenergy.BusItem.GetText" );
var cmdResult = cmd.Split('"')[1];
return cmdResult; //No Batteries can be found
}
public static async Task<String> ExecuteBufferedAsyncCommandOnIp(String? ip, String command)
{
if (ip is null or "Unknown") return "Failed";
var cmd = await Cli.Wrap("ssh")
.WithArguments($@"root@{ip}")
2023-06-01 13:29:39 +00:00
.AppendArgument("-o StrictHostKeyChecking=no")
.AppendArgument(command)
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
2023-05-25 12:49:40 +00:00
return cmd.ExitCode == 0 ? cmd.StandardOutput : cmd.StandardError;
}
private static String?[] Ip(InstallationDetails details)
{
var online = "❌";
var lookup = details.Ip;
if (lookup == "Unknown")
{
var serial = details.Details.MachineSerial() ?? "Unknown";
if (serial != "Unknown" && FILE.Exists($@"/etc/openvpn/server/Salino/ccd/{serial}"))
lookup = FILE.ReadAllText($@"/etc/openvpn/server/Salino/ccd/{serial}").Split(' ')[1];
}
else
{
online = "✅";
}
return new[] { lookup, online };
2023-05-11 13:41:41 +00:00
}
private static async Task<InstallationDetails> GetInstallationDetails(VrmInstallation i)
2023-05-11 13:41:41 +00:00
{
await Task.Delay(1000);
2023-05-11 13:41:41 +00:00
try
{
var details = await i.GetDetails();
var ip = await VpnInfo.LookUpIp(i.Identifier, details.MachineSerial()) ?? "Unknown";
var installationDetails = new InstallationDetails(ip, details);
return installationDetails;
2023-05-11 13:41:41 +00:00
}
catch (Exception e)
{
Console.WriteLine(e);
}
return new InstallationDetails("Unknown", Array.Empty<Detail>());
2023-05-11 13:41:41 +00:00
}
private static async Task UpdateInstallationName(VrmInstallation installation, String? ip)
2023-05-11 13:41:41 +00:00
{
var oldNameInFileRequest = await Cli.Wrap("ssh")
2023-05-11 13:41:41 +00:00
.WithArguments($@"root@{ip}")
.AppendArgument("-o StrictHostKeyChecking=accept-new")
.AppendArgument("cat /data/innovenergy/openvpn/installation-name")
2023-05-11 13:41:41 +00:00
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
var oldNameInFileWithoutNewLine = oldNameInFileRequest.StandardOutput.TrimEnd();
if (oldNameInFileRequest.ExitCode == 0 && oldNameInFileWithoutNewLine != installation.Name)
{
var overwriteNameCommand = Cli.Wrap("ssh")
.WithArguments($@"root@{ip}")
.AppendArgument($"echo '{installation.Name}' > /data/innovenergy/openvpn/installation-name");
var overwriteNameResponse = await overwriteNameCommand
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
if (overwriteNameResponse.ExitCode != 0)
{
Console.WriteLine(overwriteNameResponse.StandardError);
Console.WriteLine("Renaming did not work");
}
else
{
var rebootAfterRename = await Cli.Wrap("ssh")
.WithArguments($@"root@{ip}")
.AppendArgument("reboot")
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
if (rebootAfterRename.ExitCode != 0)
{
Console.WriteLine(overwriteNameResponse.StandardError);
Console.WriteLine("Rebooting did not work");
}
else
{
Console.WriteLine($"Renamed and rebooted {installation.Name}");
}
}
2023-05-11 13:41:41 +00:00
}
2023-04-27 14:59:45 +00:00
}
private static Boolean RunTransaction(Func<Boolean> func)
{
var savepoint = Connection.SaveTransactionPoint();
var success = false;
try
{
success = func();
}
finally
{
if (success)
Connection.Release(savepoint);
else
Connection.RollbackTo(savepoint);
}
return success;
}
2023-04-27 14:59:45 +00:00
}
public class AccToken
{
public UInt64 idUser { get; init;}
public String token { get; init;}
}
/*
dbus-send --system --dest=com.victronenergy.battery.ttyUSB1 --print-reply /FirmwareVersion \
org.freedesktop.DBus.Properties.Get string:com.victronenergy.battery.ttyUSB1
*/