mirror of
https://github.com/OpenLogics/MewtocolNet.git
synced 2025-12-06 03:01:24 +00:00
Added new console for all examples later on
This commit is contained in:
@@ -126,7 +126,7 @@ public class ExampleScenarios {
|
||||
}
|
||||
|
||||
//await first register data
|
||||
await interf.AwaitFirstDataAsync();
|
||||
await interf.AwaitFirstDataCycleAsync();
|
||||
|
||||
_ = Task.Factory.StartNew(async () => {
|
||||
|
||||
|
||||
19
MewTerminal/Commands/ClearCommand.cs
Normal file
19
MewTerminal/Commands/ClearCommand.cs
Normal 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();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
41
MewTerminal/Commands/CommandLineExcecuteable.cs
Normal file
41
MewTerminal/Commands/CommandLineExcecuteable.cs
Normal 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;
|
||||
|
||||
}
|
||||
102
MewTerminal/Commands/ScanCommand.cs
Normal file
102
MewTerminal/Commands/ScanCommand.cs
Normal 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());
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
54
MewTerminal/Helpers/Helpers.cs
Normal file
54
MewTerminal/Helpers/Helpers.cs
Normal 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;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
19
MewTerminal/MewTerminal.csproj
Normal file
19
MewTerminal/MewTerminal.csproj
Normal 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
86
MewTerminal/Program.cs
Normal 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();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -11,7 +11,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MewtocolTests", "MewtocolTe
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MewExplorer", "MewExplorer\MewExplorer.csproj", "{F243F38A-76D3-4C38-BAE6-C61729479661}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DocBuilder", "DocBuilder\DocBuilder.csproj", "{50F2D23F-C875-4006-A0B6-7F5A181BC944}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DocBuilder", "DocBuilder\DocBuilder.csproj", "{50F2D23F-C875-4006-A0B6-7F5A181BC944}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MewTerminal", "MewTerminal\MewTerminal.csproj", "{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@@ -89,6 +91,18 @@ Global
|
||||
{50F2D23F-C875-4006-A0B6-7F5A181BC944}.Release|x64.Build.0 = Release|Any CPU
|
||||
{50F2D23F-C875-4006-A0B6-7F5A181BC944}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{50F2D23F-C875-4006-A0B6-7F5A181BC944}.Release|x86.Build.0 = Release|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Release|x64.Build.0 = Release|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{D1E751C6-296F-4CF1-AE28-C6D4388C7CF1}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using MewtocolNet.Helpers;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
@@ -20,8 +21,7 @@ namespace MewtocolNet.ComCassette {
|
||||
|
||||
var from = new IPEndPoint(IPAddress.Any, 0);
|
||||
|
||||
List<CassetteInformation> cassettesFound = new List<CassetteInformation>();
|
||||
List<Task<List<CassetteInformation>>> interfacesTasks = new List<Task<List<CassetteInformation>>>();
|
||||
var interfacesTasks = new List<Task<List<CassetteInformation>>>();
|
||||
|
||||
var usableInterfaces = GetUseableNetInterfaces();
|
||||
|
||||
@@ -56,10 +56,21 @@ namespace MewtocolNet.ComCassette {
|
||||
//run the interface querys
|
||||
var grouped = await Task.WhenAll(interfacesTasks);
|
||||
|
||||
foreach (var item in grouped)
|
||||
cassettesFound.AddRange(item);
|
||||
var decomposed = new List<CassetteInformation>();
|
||||
|
||||
return cassettesFound;
|
||||
foreach (var grp in grouped) {
|
||||
|
||||
foreach (var cassette in grp) {
|
||||
|
||||
if (decomposed.Any(x => x.MacAddress.SequenceEqual(cassette.MacAddress))) continue;
|
||||
|
||||
decomposed.Add(cassette);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return decomposed;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace MewtocolNet {
|
||||
|
||||
/// <summary>
|
||||
/// Contains information about the plc and its cpu
|
||||
/// </summary>
|
||||
public struct CpuInfo {
|
||||
|
||||
/// <summary>
|
||||
/// The cpu type of the plc
|
||||
/// </summary>
|
||||
public CpuType Cputype { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Program capacity in 1K steps
|
||||
/// </summary>
|
||||
public int ProgramCapacity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Version of the cpu
|
||||
/// </summary>
|
||||
public string CpuVersion { get; set; }
|
||||
|
||||
internal static CpuInfo BuildFromHexString(string _cpuType, string _cpuVersion, string _progCapacity) {
|
||||
|
||||
CpuInfo retInf = new CpuInfo();
|
||||
|
||||
retInf.ProgramCapacity = Convert.ToInt32(_progCapacity);
|
||||
retInf.CpuVersion = _cpuVersion.Insert(1, ".");
|
||||
return retInf;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
31
MewtocolNet/Helpers/LinqHelpers.cs
Normal file
31
MewtocolNet/Helpers/LinqHelpers.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace MewtocolNet.Helpers {
|
||||
|
||||
internal static class LinqHelpers {
|
||||
|
||||
internal static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) {
|
||||
return DistinctBy(source, keySelector, null);
|
||||
}
|
||||
|
||||
internal static IEnumerable<TSource> DistinctBy<TSource, TKey>
|
||||
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) {
|
||||
|
||||
if (source == null) throw new ArgumentNullException(nameof(source));
|
||||
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
|
||||
|
||||
return _(); IEnumerable<TSource> _() {
|
||||
var knownKeys = new HashSet<TKey>(comparer);
|
||||
foreach (var element in source) {
|
||||
if (knownKeys.Add(keySelector(element)))
|
||||
yield return element;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -323,7 +323,9 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
public static string ToName(this PlcType plcT) {
|
||||
|
||||
return string.Join(" or ", ParsedPlcName.LegacyPlcDeconstruct(plcT).Select(x => x.WholeName));
|
||||
if (plcT == 0) return "Unknown";
|
||||
|
||||
return string.Join(" or ", ParsedPlcName.PlcDeconstruct(plcT).Select(x => x.WholeName));
|
||||
|
||||
}
|
||||
|
||||
@@ -332,7 +334,9 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
public static ParsedPlcName[] ToNameDecompose (this PlcType legacyT) {
|
||||
|
||||
return ParsedPlcName.LegacyPlcDeconstruct(legacyT);
|
||||
if ((int)legacyT == 0) return Array.Empty<ParsedPlcName>();
|
||||
|
||||
return ParsedPlcName.PlcDeconstruct(legacyT);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -35,9 +35,9 @@ namespace MewtocolNet {
|
||||
/// <inheritdoc/>
|
||||
public override string ToString() => WholeName;
|
||||
|
||||
internal static ParsedPlcName[] LegacyPlcDeconstruct<T> (T legacyT) {
|
||||
internal static ParsedPlcName[] PlcDeconstruct (PlcType plcT) {
|
||||
|
||||
string wholeStr = legacyT.ToString();
|
||||
string wholeStr = plcT.ToString();
|
||||
|
||||
var split = wholeStr.Replace("_OR_", "|").Split('|');
|
||||
var reg = new Regex(@"(?<group>[A-Za-z0-9]*)_(?<size>[A-Za-z0-9]*)(?:__)?(?<additional>.*)");
|
||||
|
||||
@@ -83,7 +83,7 @@ namespace MewtocolNet {
|
||||
/// Use this to await the first poll iteration after connecting,
|
||||
/// This also completes if the initial connection fails
|
||||
/// </summary>
|
||||
Task AwaitFirstDataAsync();
|
||||
Task AwaitFirstDataCycleAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Runs a single poller cycle manually,
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
/// </summary>
|
||||
public enum LogLevel {
|
||||
|
||||
/// <summary>
|
||||
/// Logs nothing
|
||||
/// </summary>
|
||||
None = -1,
|
||||
/// <summary>
|
||||
/// Logs only errors
|
||||
/// </summary>
|
||||
|
||||
@@ -14,6 +14,10 @@ namespace MewtocolNet {
|
||||
|
||||
public string Error { get; private set; }
|
||||
|
||||
public static MewtocolFrameResponse Timeout => new MewtocolFrameResponse(403, "Request timed out");
|
||||
|
||||
public static MewtocolFrameResponse NotIntialized => new MewtocolFrameResponse(405, "PLC was not initialized");
|
||||
|
||||
public MewtocolFrameResponse (string response) {
|
||||
|
||||
Success = true;
|
||||
@@ -41,6 +45,16 @@ namespace MewtocolNet {
|
||||
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public static bool operator == (MewtocolFrameResponse c1, MewtocolFrameResponse c2) {
|
||||
return c1.Equals(c2);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public static bool operator != (MewtocolFrameResponse c1, MewtocolFrameResponse c2) {
|
||||
return !c1.Equals(c2);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ namespace MewtocolNet {
|
||||
public virtual async Task ConnectAsync() => throw new NotImplementedException();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task AwaitFirstDataAsync() => await firstPollTask;
|
||||
public async Task AwaitFirstDataCycleAsync() => await firstPollTask;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Disconnect() {
|
||||
@@ -196,7 +196,7 @@ namespace MewtocolNet {
|
||||
|
||||
if (await Task.WhenAny(tempResponse, Task.Delay(timeoutMs)) != tempResponse) {
|
||||
// timeout logic
|
||||
return new MewtocolFrameResponse(403, "Timed out");
|
||||
return MewtocolFrameResponse.Timeout;
|
||||
}
|
||||
|
||||
tcpMessagesSentThisCycle++;
|
||||
@@ -210,7 +210,7 @@ namespace MewtocolNet {
|
||||
|
||||
try {
|
||||
|
||||
if (stream == null) return new MewtocolFrameResponse(405, "PLC not initialized");
|
||||
if (stream == null) return MewtocolFrameResponse.NotIntialized;
|
||||
|
||||
if (useBcc)
|
||||
frame = $"{frame.BuildBCCFrame()}";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using MewtocolNet.Exceptions;
|
||||
using MewtocolNet.Logging;
|
||||
using MewtocolNet.Registers;
|
||||
using System;
|
||||
@@ -21,17 +22,41 @@ namespace MewtocolNet {
|
||||
/// <returns>A PLCInfo class</returns>
|
||||
public async Task<PLCInfo?> GetPLCInfoAsync(int timeout = -1) {
|
||||
|
||||
var regexRT = new Regex(@"\%EE\$RT(?<cputype>..)(?<cpuver>..)(?<cap>..)(?<op>..)..(?<flg>..)(?<sdiag>....).*", RegexOptions.IgnoreCase);
|
||||
|
||||
var regexEXRT = new Regex(@"\%EE\$EX00RT00(?<icnt>..)(?<mc>..)..(?<cap>..)(?<op>..)..(?<flg>..)(?<sdiag>....)(?<ver>..)(?<hwif>..)(?<nprog>.)(?<progsz>....)(?<hdsz>....)(?<sysregsz>....).*", RegexOptions.IgnoreCase);
|
||||
|
||||
var resRT = await SendCommandAsync("%EE#RT", timeoutMs: timeout);
|
||||
if (!resRT.Success) return null;
|
||||
|
||||
if (!resRT.Success) {
|
||||
|
||||
//timeouts are ok and dont throw
|
||||
if (resRT == MewtocolFrameResponse.Timeout) return null;
|
||||
|
||||
throw new MewtocolException(resRT.Error);
|
||||
|
||||
}
|
||||
|
||||
var resEXRT = await SendCommandAsync("%EE#EX00RT00", timeoutMs: timeout);
|
||||
|
||||
//timeouts are ok and dont throw
|
||||
if (!resRT.Success && resRT == MewtocolFrameResponse.Timeout) return null;
|
||||
|
||||
return null;
|
||||
PLCInfo plcInf;
|
||||
|
||||
//dont overwrite, use first
|
||||
if (!PLCInfo.TryFromRT(resRT.Response, out plcInf)) {
|
||||
|
||||
throw new MewtocolException("The RT message could not be parsed");
|
||||
|
||||
}
|
||||
|
||||
//overwrite first with EXRT
|
||||
if (resEXRT.Success && !plcInf.TryExtendFromEXRT(resEXRT.Response)) {
|
||||
|
||||
throw new MewtocolException("The EXRT message could not be parsed");
|
||||
|
||||
}
|
||||
|
||||
PlcInfo = plcInf;
|
||||
|
||||
return plcInf;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>netstandard2.0;net6.0;</TargetFrameworks>
|
||||
<TargetFrameworks>netstandard2.0;</TargetFrameworks>
|
||||
<PackageId>Mewtocol.NET</PackageId>
|
||||
<Version>0.7.1</Version>
|
||||
<Authors>Felix Weiss</Authors>
|
||||
|
||||
@@ -1,66 +1,111 @@
|
||||
namespace MewtocolNet {
|
||||
using MewtocolNet.PublicEnums;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace MewtocolNet {
|
||||
|
||||
public enum CpuType {
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds various informations about the PLC
|
||||
/// </summary>
|
||||
public struct PLCInfo {
|
||||
|
||||
/// <summary>
|
||||
/// Current error code of the PLC
|
||||
/// The type of the PLC named by Panasonic
|
||||
/// </summary>
|
||||
public string ErrorCode { get; internal set; }
|
||||
public PlcType TypeCode { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Current station number of the PLC
|
||||
/// Contains information about the PLCs operation modes as flags
|
||||
/// </summary>
|
||||
public int StationNumber { get; internal set; }
|
||||
public OPMode OperationMode { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Hardware information flags about the PLC
|
||||
/// </summary>
|
||||
public HWInformation HardwareInformation { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Program capacity in 1K steps
|
||||
/// </summary>
|
||||
public int ProgramCapacity { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Version of the cpu
|
||||
/// </summary>
|
||||
public string CpuVersion { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Current error code of the PLC
|
||||
/// </summary>
|
||||
public string SelfDiagnosticError { get; internal set; }
|
||||
|
||||
internal bool TryExtendFromEXRT (string msg) {
|
||||
|
||||
var regexEXRT = new Regex(@"\%EE\$EX00RT00(?<icnt>..)(?<mc>..)..(?<cap>..)(?<op>..)..(?<flg>..)(?<sdiag>....)(?<ver>..)(?<hwif>..)(?<nprog>.)(?<progsz>....)(?<hdsz>....)(?<sysregsz>....).*", RegexOptions.IgnoreCase);
|
||||
var match = regexEXRT.Match(msg);
|
||||
if(match.Success) {
|
||||
|
||||
byte typeCodeByte = byte.Parse(match.Groups["mc"].Value, NumberStyles.HexNumber);
|
||||
|
||||
this.TypeCode = (PlcType)typeCodeByte;
|
||||
this.CpuVersion = match.Groups["ver"].Value;
|
||||
this.HardwareInformation = (HWInformation)byte.Parse(match.Groups["hwif"].Value, NumberStyles.HexNumber);
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
internal static bool TryFromRT (string msg, out PLCInfo inf) {
|
||||
|
||||
var regexRT = new Regex(@"\%EE\$RT(?<cputype>..)(?<cpuver>..)(?<cap>..)(?<op>..)..(?<flg>..)(?<sdiag>....).*", RegexOptions.IgnoreCase);
|
||||
var match = regexRT.Match(msg);
|
||||
if (match.Success) {
|
||||
|
||||
byte typeCodeByte = byte.Parse(match.Groups["cputype"].Value, NumberStyles.HexNumber);
|
||||
|
||||
inf = new PLCInfo {
|
||||
TypeCode = (PlcType)typeCodeByte,
|
||||
CpuVersion = match.Groups["cpuver"].Value,
|
||||
ProgramCapacity = int.Parse(match.Groups["cap"].Value),
|
||||
SelfDiagnosticError = match.Groups["sdiag"].Value,
|
||||
OperationMode = (OPMode)byte.Parse(match.Groups["op"].Value, NumberStyles.HexNumber),
|
||||
};
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
inf = default(PLCInfo);
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains generic information about the plc
|
||||
/// Plc info when its not connected
|
||||
/// </summary>
|
||||
public class PLCInfoOld
|
||||
{
|
||||
public static PLCInfo None => new PLCInfo() {
|
||||
|
||||
/// <summary>
|
||||
/// Contains information about the PLCs cpu
|
||||
/// </summary>
|
||||
public CpuInfo CpuInformation { get; set; }
|
||||
/// <summary>
|
||||
/// Contains information about the PLCs operation modes
|
||||
/// </summary>
|
||||
public PLCMode OperationMode { get; set; }
|
||||
SelfDiagnosticError = "",
|
||||
CpuVersion = "",
|
||||
HardwareInformation = 0,
|
||||
OperationMode = 0,
|
||||
ProgramCapacity = 0,
|
||||
TypeCode = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Current error code of the PLC
|
||||
/// </summary>
|
||||
public string ErrorCode { get; set; }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Current station number of the PLC
|
||||
/// </summary>
|
||||
public int StationNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Generates a string containing some of the most important informations
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override string ToString() {
|
||||
|
||||
return $"Type: {CpuInformation.Cputype},\n" +
|
||||
$"Capacity: {CpuInformation.ProgramCapacity}k\n" +
|
||||
$"CPU v: {CpuInformation.CpuVersion}\n" +
|
||||
$"Station Num: {StationNumber}\n" +
|
||||
$"--------------------------------\n" +
|
||||
$"OP Mode: {(OperationMode.RunMode ? "Run" : "Prog")}\n" +
|
||||
$"Error Code: {ErrorCode}";
|
||||
/// <inheritdoc/>
|
||||
public static bool operator == (PLCInfo c1, PLCInfo c2) {
|
||||
return c1.Equals(c2);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public static bool operator != (PLCInfo c1, PLCInfo c2) {
|
||||
return !c1.Equals(c2);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace MewtocolNet {
|
||||
|
||||
/// <summary>
|
||||
/// All modes
|
||||
/// </summary>
|
||||
public struct PLCMode {
|
||||
|
||||
/// <summary>
|
||||
/// PLC is running
|
||||
/// </summary>
|
||||
public bool RunMode { get; set; }
|
||||
/// <summary>
|
||||
/// PLC is in test
|
||||
/// </summary>
|
||||
public bool TestRunMode { get; set; }
|
||||
/// <summary>
|
||||
/// BreakExcecuting
|
||||
/// </summary>
|
||||
public bool BreakExcecuting { get; set; }
|
||||
/// <summary>
|
||||
/// BreakValid
|
||||
/// </summary>
|
||||
public bool BreakValid { get; set; }
|
||||
/// <summary>
|
||||
/// PLC output is enabled
|
||||
/// </summary>
|
||||
public bool OutputEnabled { get; set; }
|
||||
/// <summary>
|
||||
/// PLC runs step per step
|
||||
/// </summary>
|
||||
public bool StepRunMode { get; set; }
|
||||
/// <summary>
|
||||
/// Message executing
|
||||
/// </summary>
|
||||
public bool MessageExecuting { get; set; }
|
||||
/// <summary>
|
||||
/// PLC is in remote mode
|
||||
/// </summary>
|
||||
public bool RemoteMode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets operation mode from 2 digit hex number
|
||||
/// </summary>
|
||||
internal static PLCMode BuildFromHex(string _hexString) {
|
||||
|
||||
string lower = Convert.ToString(Convert.ToInt32(_hexString.Substring(0, 1)), 2).PadLeft(4, '0');
|
||||
string higher = Convert.ToString(Convert.ToInt32(_hexString.Substring(1, 1)), 2).PadLeft(4, '0');
|
||||
string combined = lower + higher;
|
||||
|
||||
var retMode = new PLCMode();
|
||||
|
||||
for (int i = 0; i < 8; i++) {
|
||||
char digit = combined[i];
|
||||
bool state = false;
|
||||
if (digit.ToString() == "1")
|
||||
state = true;
|
||||
switch (i) {
|
||||
case 0:
|
||||
retMode.RunMode = state;
|
||||
break;
|
||||
case 1:
|
||||
retMode.TestRunMode = state;
|
||||
break;
|
||||
case 2:
|
||||
retMode.BreakExcecuting = state;
|
||||
break;
|
||||
case 3:
|
||||
retMode.BreakValid = state;
|
||||
break;
|
||||
case 4:
|
||||
retMode.OutputEnabled = state;
|
||||
break;
|
||||
case 5:
|
||||
retMode.StepRunMode = state;
|
||||
break;
|
||||
case 6:
|
||||
retMode.MessageExecuting = state;
|
||||
break;
|
||||
case 7:
|
||||
retMode.RemoteMode = state;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return retMode;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
77
MewtocolNet/PublicEnums/HWInformation.cs
Normal file
77
MewtocolNet/PublicEnums/HWInformation.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace MewtocolNet.PublicEnums {
|
||||
|
||||
/// <summary>
|
||||
/// Contains hardware information about the device as flags
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum HWInformation : byte {
|
||||
|
||||
/// <summary>
|
||||
/// Has user ROM
|
||||
/// </summary>
|
||||
UserROM = 1,
|
||||
/// <summary>
|
||||
/// Has IC card
|
||||
/// </summary>
|
||||
ICCard = 2,
|
||||
/// <summary>
|
||||
/// Has general purpose memory
|
||||
/// </summary>
|
||||
GeneralPurposeMemory = 4,
|
||||
/// <summary>
|
||||
/// Is CPU ultra high speed type
|
||||
/// </summary>
|
||||
UltraHighSpeed = 8,
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Descibes the operation mode of the device as flags
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum OPMode : byte {
|
||||
|
||||
/// <summary>
|
||||
/// No operation mode flag active
|
||||
/// </summary>
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// Is in RUN mode, otherwise its PROG Mode
|
||||
/// </summary>
|
||||
RunMode = 1,
|
||||
/// <summary>
|
||||
/// Is in test mode, otherwise ok
|
||||
/// </summary>
|
||||
TestMode = 2,
|
||||
/// <summary>
|
||||
/// Is BRK/1 step executed
|
||||
/// </summary>
|
||||
BreakPointPerOneStep = 4,
|
||||
/// <summary>
|
||||
/// Is BRK command enabled
|
||||
/// </summary>
|
||||
BreakEnabled = 16,
|
||||
/// <summary>
|
||||
/// Is outputting to external device
|
||||
/// </summary>
|
||||
ExternalOutput = 32,
|
||||
/// <summary>
|
||||
/// Is 1 step exec enabled
|
||||
/// </summary>
|
||||
OneStepExecEnabled = 64,
|
||||
/// <summary>
|
||||
/// Is a message displayed?
|
||||
/// </summary>
|
||||
MessageInstructionDisplayed = 128,
|
||||
/// <summary>
|
||||
/// Is in remote mode
|
||||
/// </summary>
|
||||
RemoteMode = 255,
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user