Innovenergy_trunk/csharp/App/BmsTunnel/BatteryTty.cs

96 lines
2.6 KiB
C#
Raw Normal View History

2023-02-16 12:57:06 +00:00
using CliWrap;
using CliWrap.Buffered;
using InnovEnergy.Lib.Utils;
using static InnovEnergy.App.BmsTunnel.CliPrograms;
2023-02-16 12:57:06 +00:00
namespace InnovEnergy.App.BmsTunnel;
2023-02-16 12:57:06 +00:00
using Nodes = IReadOnlyList<Byte>;
public static class BatteryTty
2023-02-16 12:57:06 +00:00
{
const String DevDir = "/dev";
2023-02-16 12:57:06 +00:00
public static async Task<String?> GetTty()
2023-02-16 12:57:06 +00:00
{
Console.WriteLine("searching battery connection...");
return await GetTtyFromDBus()
?? await GetTtyFromDev();
2023-02-16 12:57:06 +00:00
}
private static async Task<String?> GetTtyFromDev()
2023-02-16 12:57:06 +00:00
{
var ttys = await FileSystem
.Local
.GetFiles(DevDir, FileType.CharacterDevice);
2023-02-16 12:57:06 +00:00
var candidateTtys = ttys
.Where(f => f.StartsWith(DevDir + "/ttyUSB"))
2023-02-16 12:57:06 +00:00
.NotNull()
.ToList();
if (!candidateTtys.Any())
{
Console.WriteLine("no USB converter cable attached!");
return null;
}
if (candidateTtys.Count == 1)
return candidateTtys[0];
2023-02-16 12:57:06 +00:00
return "Select TTY:".ChooseFrom(candidateTtys);
2023-02-16 12:57:06 +00:00
}
private static async Task<String?> GetTtyFromDBus()
2023-02-16 12:57:06 +00:00
{
var tty = await LsDBus
.ExecuteBufferedAsync()
.Select(ParseBatteryTty);
if (tty == null)
return null;
Console.WriteLine("found battery on DBus");
return $"{DevDir}/{tty}";
2023-02-16 12:57:06 +00:00
}
private static CommandTask<Nodes> GetNodes(String tty)
2023-02-16 12:57:06 +00:00
{
const String defaultArgs = "--system --print-reply --type=method_call / com.victronenergy.BusItem.GetValue";
return DBusSend
.AppendArgument($"--dest=com.victronenergy.battery.{tty}")
.AppendArgument(defaultArgs)
.ExecuteBufferedAsync()
.Select(ParseBatteryNodes);
}
private static Nodes ParseBatteryNodes(BufferedCommandResult result)
{
return result
.StandardOutput
.Split(Environment.NewLine)
.Where(l => l.Contains("_Battery/"))
.Select(l => l.Split('/')[1])
.Where(n => Byte.TryParse(n, out _))
.Select(Byte.Parse)
.Distinct()
.OrderBy(n => n)
.ToList();
}
private static String? ParseBatteryTty(BufferedCommandResult result)
{
return result
.StandardOutput
.Split(Environment.NewLine)
.Where(l => l.Contains("com.victronenergy.battery."))
.SelectMany(l => l.Split('.'))
.LastOrDefault();
}
}