Added new console for all examples later on

This commit is contained in:
Felix Weiß
2023-07-06 18:51:54 +02:00
parent 6d3b5adf7d
commit 616d102dea
22 changed files with 609 additions and 193 deletions

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using CommandLine;
using MewtocolNet;
using MewtocolNet.ComCassette;
using Spectre.Console;
namespace MewTerminal.Commands;
[Verb("clear", HelpText = "Clears console", Hidden = true)]
internal class ClearCommand : CommandLineExcecuteable {
public override void Run() {
Console.Clear();
}
}

View File

@@ -0,0 +1,41 @@
using CommandLine.Text;
using CommandLine;
using MewtocolNet.Logging;
namespace MewTerminal.Commands;
public abstract class CommandLineExcecuteable {
static UnParserSettings UnparserSet = new UnParserSettings {
PreferShortName = true,
};
[Option('v', "verbosity", HelpText = "Sets the Loglevel verbosity", Default = LogLevel.None)]
public LogLevel LogLevel { get; set; } = LogLevel.None;
[Usage]
public static IEnumerable<Example> Examples {
get {
return new List<Example>() {
new Example(
helpText: "Sanning from adapter with ip 127.0.0.1 and logging all critical messages",
formatStyle: UnparserSet,
sample: new ScanCommand {
IPSource = "127.0.0.1",
LogLevel = LogLevel.Critical,
}),
new Example(
helpText: "Scanning from all adapters and logging only errors",
formatStyle: UnparserSet,
sample: new ScanCommand {
LogLevel = LogLevel.Error,
}),
};
}
}
public virtual void Run() { }
public virtual Task RunAsync () => Task.CompletedTask;
}

View File

@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using CommandLine;
using MewtocolNet;
using MewtocolNet.ComCassette;
using MewtocolNet.Logging;
using Spectre.Console;
namespace MewTerminal.Commands;
[Verb("scan", HelpText = "Scans all network PLCs")]
internal class ScanCommand : CommandLineExcecuteable {
[Option("ip", HelpText = "IP of the source adapter" )]
public string? IPSource { get; set; }
[Option("timeout", Default = 100)]
public int? TimeoutMS { get; set; }
[Option("plc", Required = false, HelpText = "Gets the PLC types")]
public bool GetPLCTypes { get; set; }
private class PLCCassetteTypeInfo {
public CassetteInformation Cassette { get; set; }
public PLCInfo PLCInf { get; set; }
}
public override async Task RunAsync () {
await AnsiConsole.Status()
.Spinner(Spinner.Known.Dots)
.StartAsync("Scanning...", async ctx => {
var query = await CassetteFinder.FindClientsAsync(IPSource, TimeoutMS ?? 100);
var found = query.Select(x => new PLCCassetteTypeInfo { Cassette = x }).ToList();
if (found.Count > 0 && GetPLCTypes) {
foreach (var item in found) {
ctx.Status($"Getting cassette PLC {item.Cassette.IPAddress}:{item.Cassette.Port}")
.Spinner(Spinner.Known.Dots);
var dev = Mewtocol.Ethernet(item.Cassette.IPAddress, item.Cassette.Port);
dev.ConnectTimeout = 1000;
await dev.ConnectAsync();
item.PLCInf = dev.PlcInfo;
dev.Disconnect();
}
}
if (found.Count() > 0) {
AnsiConsole.MarkupLineInterpolated($"✅ Found {found.Count()} devices...");
} else {
AnsiConsole.MarkupLineInterpolated($"❌ Found no devices");
return;
}
if (found.Any(x => x.PLCInf != PLCInfo.None)) {
AnsiConsole.Write(found.Select(x => new {
x.Cassette.Name,
PLC = x.PLCInf.TypeCode.ToName(),
IsRun = x.PLCInf.OperationMode.HasFlag(OPMode.Run),
IP = x.Cassette.IPAddress,
x.Cassette.Port,
DHCP = x.Cassette.UsesDHCP,
MAC = x.Cassette.MacAddress,
Ver = x.Cassette.FirmwareVersion,
x.Cassette.Status,
}).ToTable());
} else {
AnsiConsole.Write(found.Select(x => new {
x.Cassette.Name,
IP = x.Cassette.IPAddress,
x.Cassette.Port,
DHCP = x.Cassette.UsesDHCP,
MAC = x.Cassette.MacAddress,
Ver = x.Cassette.FirmwareVersion,
x.Cassette.Status,
}).ToTable());
}
});
}
}

View File

@@ -0,0 +1,54 @@
using Spectre.Console;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MewTerminal;
internal static class Helpers {
internal static Table ToTable<T> (this IEnumerable<T> data, params string[] markups) {
// Create a table
var table = new Table();
var type = typeof(T);
var props = type.GetProperties();
bool isFirst = true;
foreach (var item in data) {
var rowVals = new List<string>();
foreach (var prop in props) {
if(isFirst) table.AddColumn(prop.Name);
var propVal = prop.GetValue(item);
string strVal = propVal?.ToString() ?? "null";
if (propVal is byte[] bArr) {
strVal = string.Join(" ", bArr.Select(x => x.ToString("X2")));
}
strVal = strVal.Replace("[", "");
strVal = strVal.Replace("]", "");
rowVals.Add(strVal);
}
isFirst = false;
table.AddRow(rowVals.ToArray());
}
return table;
}
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="Spectre.Console" Version="0.47.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MewtocolNet\MewtocolNet.csproj" />
</ItemGroup>
</Project>

86
MewTerminal/Program.cs Normal file
View File

@@ -0,0 +1,86 @@
using CommandLine;
using CommandLine.Text;
using MewTerminal.Commands;
using MewtocolNet.Logging;
using Spectre.Console;
using System.Reflection;
namespace MewTerminal;
internal class Program {
static void Main(string[] args) {
Logger.OnNewLogMessage((dt, lv, msg) => {
AnsiConsole.WriteLine($"{msg}");
});
#if DEBUG
Console.Clear();
var firstArg = new string[] { "help" };
start:
if(firstArg == null) {
Console.WriteLine("Enter arguments [DEBUG MODE]");
args = Console.ReadLine().SplitArgs();
}
//print help first time
InitParser(firstArg ?? args);
firstArg = null;
goto start;
#else
InitParser(args);
#endif
}
private static Type[] LoadVerbs() {
var lst = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.GetCustomAttribute<VerbAttribute>() != null)
.ToArray();
return lst;
}
static void InitParser (string[] args) {
var types = LoadVerbs();
var parseRes = Parser.Default.ParseArguments(args, types);
var helpText = HelpText.AutoBuild(parseRes, h => {
h.AddEnumValuesToHelpText = true;
return h;
}, e => e);
parseRes.WithNotParsed(err => {
});
if(parseRes?.Value != null && parseRes.Value is CommandLineExcecuteable exc) {
Logger.LogLevel = exc.LogLevel;
exc.Run();
var task = Task.Run(exc.RunAsync);
task.Wait();
}
}
}