Innovenergy_trunk/csharp/Lib/Victron/VictronVRM/VrmAccount.cs

74 lines
2.1 KiB
C#

using System.Text.Json.Nodes;
using InnovEnergy.Lib.Utils;
namespace InnovEnergy.Lib.Victron.VictronVRM;
public class VrmAccount : IDisposable
{
public String Auth { get; }
public UInt64 UserId { get; }
private VrmAccount(UInt64 userId, String auth)
{
Auth = auth;
UserId = userId;
}
public static VrmAccount Token(UInt64 userId, String token)
{
return new VrmAccount(userId, $"Token {token}");
}
public static async Task<VrmAccount> Login(String username, String password)
{
var credentials = new JsonObject
{
["username"] = username,
["password"] = password,
};
var login = await Requests.LoginRequest.TryPostJson(credentials);
var idUser = login.GetUInt64("idUser");
var token = login.GetString("token");
return new VrmAccount(idUser, $"Bearer {token}");
}
private async Task Logout() => await this.LogoutRequest().TryPostJson();
public async Task<IReadOnlyList<Installation>> GetInstallations()
{
var reply = await this.AllInstallationsRequest().TryGetJson();
var vrmReply = new Reply(reply);
if (!vrmReply.Success)
throw new Exception(nameof(GetInstallations) + " failed");
return vrmReply
.Records
.Select(r => new Installation(this, r!))
.ToArray(vrmReply.Records.Count);
}
public async Task<Installation> GetInstallation(Int64 installationId)
{
var reply = await this.SpecificInstallationRequest((UInt64)installationId).TryGetJson();
var vrmReply = new Reply(reply);
if (!vrmReply.Success)
throw new Exception(nameof(GetInstallations) + " failed");
return vrmReply
.Records
.Select(r => new Installation(this, r!))
.First(i => i.IdSite == (UInt64)installationId);
}
public void Dispose()
{
if (IsLoggedIn)
Logout().Wait();
}
private Boolean IsLoggedIn => Auth.StartsWith("Bearer ");
}