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

@@ -126,7 +126,7 @@ public class ExampleScenarios {
} }
//await first register data //await first register data
await interf.AwaitFirstDataAsync(); await interf.AwaitFirstDataCycleAsync();
_ = Task.Factory.StartNew(async () => { _ = Task.Factory.StartNew(async () => {

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();
}
}
}

View File

@@ -11,7 +11,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MewtocolTests", "MewtocolTe
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MewExplorer", "MewExplorer\MewExplorer.csproj", "{F243F38A-76D3-4C38-BAE6-C61729479661}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MewExplorer", "MewExplorer\MewExplorer.csproj", "{F243F38A-76D3-4C38-BAE6-C61729479661}"
EndProject 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 EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution 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|x64.Build.0 = Release|Any CPU
{50F2D23F-C875-4006-A0B6-7F5A181BC944}.Release|x86.ActiveCfg = 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 {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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -1,4 +1,5 @@
using System; using MewtocolNet.Helpers;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
@@ -20,8 +21,7 @@ namespace MewtocolNet.ComCassette {
var from = new IPEndPoint(IPAddress.Any, 0); var from = new IPEndPoint(IPAddress.Any, 0);
List<CassetteInformation> cassettesFound = new List<CassetteInformation>(); var interfacesTasks = new List<Task<List<CassetteInformation>>>();
List<Task<List<CassetteInformation>>> interfacesTasks = new List<Task<List<CassetteInformation>>>();
var usableInterfaces = GetUseableNetInterfaces(); var usableInterfaces = GetUseableNetInterfaces();
@@ -56,10 +56,21 @@ namespace MewtocolNet.ComCassette {
//run the interface querys //run the interface querys
var grouped = await Task.WhenAll(interfacesTasks); var grouped = await Task.WhenAll(interfacesTasks);
foreach (var item in grouped) var decomposed = new List<CassetteInformation>();
cassettesFound.AddRange(item);
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;
} }

View File

@@ -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;
}
}
}

View 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;
}
}
}
}
}

View File

@@ -323,7 +323,9 @@ namespace MewtocolNet {
/// </summary> /// </summary>
public static string ToName(this PlcType plcT) { 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> /// </summary>
public static ParsedPlcName[] ToNameDecompose (this PlcType legacyT) { public static ParsedPlcName[] ToNameDecompose (this PlcType legacyT) {
return ParsedPlcName.LegacyPlcDeconstruct(legacyT); if ((int)legacyT == 0) return Array.Empty<ParsedPlcName>();
return ParsedPlcName.PlcDeconstruct(legacyT);
} }

View File

@@ -35,9 +35,9 @@ namespace MewtocolNet {
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() => WholeName; 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 split = wholeStr.Replace("_OR_", "|").Split('|');
var reg = new Regex(@"(?<group>[A-Za-z0-9]*)_(?<size>[A-Za-z0-9]*)(?:__)?(?<additional>.*)"); var reg = new Regex(@"(?<group>[A-Za-z0-9]*)_(?<size>[A-Za-z0-9]*)(?:__)?(?<additional>.*)");

View File

@@ -83,7 +83,7 @@ namespace MewtocolNet {
/// Use this to await the first poll iteration after connecting, /// Use this to await the first poll iteration after connecting,
/// This also completes if the initial connection fails /// This also completes if the initial connection fails
/// </summary> /// </summary>
Task AwaitFirstDataAsync(); Task AwaitFirstDataCycleAsync();
/// <summary> /// <summary>
/// Runs a single poller cycle manually, /// Runs a single poller cycle manually,

View File

@@ -5,6 +5,10 @@
/// </summary> /// </summary>
public enum LogLevel { public enum LogLevel {
/// <summary>
/// Logs nothing
/// </summary>
None = -1,
/// <summary> /// <summary>
/// Logs only errors /// Logs only errors
/// </summary> /// </summary>

View File

@@ -14,6 +14,10 @@ namespace MewtocolNet {
public string Error { get; private set; } 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) { public MewtocolFrameResponse (string response) {
Success = true; 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);
}
} }
} }

View File

@@ -159,7 +159,7 @@ namespace MewtocolNet {
public virtual async Task ConnectAsync() => throw new NotImplementedException(); public virtual async Task ConnectAsync() => throw new NotImplementedException();
/// <inheritdoc/> /// <inheritdoc/>
public async Task AwaitFirstDataAsync() => await firstPollTask; public async Task AwaitFirstDataCycleAsync() => await firstPollTask;
/// <inheritdoc/> /// <inheritdoc/>
public void Disconnect() { public void Disconnect() {
@@ -196,7 +196,7 @@ namespace MewtocolNet {
if (await Task.WhenAny(tempResponse, Task.Delay(timeoutMs)) != tempResponse) { if (await Task.WhenAny(tempResponse, Task.Delay(timeoutMs)) != tempResponse) {
// timeout logic // timeout logic
return new MewtocolFrameResponse(403, "Timed out"); return MewtocolFrameResponse.Timeout;
} }
tcpMessagesSentThisCycle++; tcpMessagesSentThisCycle++;
@@ -210,7 +210,7 @@ namespace MewtocolNet {
try { try {
if (stream == null) return new MewtocolFrameResponse(405, "PLC not initialized"); if (stream == null) return MewtocolFrameResponse.NotIntialized;
if (useBcc) if (useBcc)
frame = $"{frame.BuildBCCFrame()}"; frame = $"{frame.BuildBCCFrame()}";

View File

@@ -1,3 +1,4 @@
using MewtocolNet.Exceptions;
using MewtocolNet.Logging; using MewtocolNet.Logging;
using MewtocolNet.Registers; using MewtocolNet.Registers;
using System; using System;
@@ -21,17 +22,41 @@ namespace MewtocolNet {
/// <returns>A PLCInfo class</returns> /// <returns>A PLCInfo class</returns>
public async Task<PLCInfo?> GetPLCInfoAsync(int timeout = -1) { 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); 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); 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;
} }

View File

@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>netstandard2.0;net6.0;</TargetFrameworks> <TargetFrameworks>netstandard2.0;</TargetFrameworks>
<PackageId>Mewtocol.NET</PackageId> <PackageId>Mewtocol.NET</PackageId>
<Version>0.7.1</Version> <Version>0.7.1</Version>
<Authors>Felix Weiss</Authors> <Authors>Felix Weiss</Authors>

View File

@@ -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 { public struct PLCInfo {
/// <summary> /// <summary>
/// Current error code of the PLC /// The type of the PLC named by Panasonic
/// </summary> /// </summary>
public string ErrorCode { get; internal set; } public PlcType TypeCode { get; private set; }
/// <summary> /// <summary>
/// Current station number of the PLC /// Contains information about the PLCs operation modes as flags
/// </summary> /// </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> /// <summary>
/// Contains generic information about the plc /// Plc info when its not connected
/// </summary> /// </summary>
public class PLCInfoOld public static PLCInfo None => new PLCInfo() {
{
/// <summary> SelfDiagnosticError = "",
/// Contains information about the PLCs cpu CpuVersion = "",
/// </summary> HardwareInformation = 0,
public CpuInfo CpuInformation { get; set; } OperationMode = 0,
/// <summary> ProgramCapacity = 0,
/// Contains information about the PLCs operation modes TypeCode = 0,
/// </summary>
public PLCMode OperationMode { get; set; }
/// <summary> };
/// Current error code of the PLC
/// </summary>
public string ErrorCode { get; set; }
/// <summary> /// <inheritdoc/>
/// Current station number of the PLC public static bool operator == (PLCInfo c1, PLCInfo c2) {
/// </summary> return c1.Equals(c2);
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);
} }
} }

View File

@@ -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;
}
}
}

View 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,
}
}