Heavily improved the overall performance and async handling

- added a queuing manager for all messages
- tcp now keeps the connection after the first handshake
- async tasks are now run by the time order they were added
- minor bugfixes
This commit is contained in:
Felix Weiß
2022-07-15 15:53:26 +02:00
parent cdae9a60fb
commit 6c411d7318
9 changed files with 302 additions and 246 deletions

View File

@@ -40,18 +40,30 @@ namespace Examples {
await Task.Delay(2000); await Task.Delay(2000);
Console.WriteLine("Testregister was toggled"); await interf.SetRegisterAsync(nameof(registers.TestInt32), 100);
_ = Task.Factory.StartNew(async () => {
while(true) {
for (int i = 0; i < 5; i++) {
var bytes = await interf.ReadByteRange(1020, 20);
await interf.SetRegisterAsync(nameof(registers.TestBool1), !registers.TestBool1);
await interf.SetRegisterAsync(nameof(registers.TestInt32), registers.TestInt32 + 100);
await Task.Delay(1333);
}
await Task.Delay(10000);
}
});
//adds 10 each time the plc connects to the PLCs INT regíster //adds 10 each time the plc connects to the PLCs INT regíster
interf.SetRegister(nameof(registers.TestInt16), (short)(registers.TestInt16 + 10)); //interf.SetRegister(nameof(registers.TestInt16), (short)(registers.TestInt16 + 10));
//adds 1 each time the plc connects to the PLCs DINT regíster //adds 1 each time the plc connects to the PLCs DINT regíster
interf.SetRegister(nameof(registers.TestInt32), (registers.TestInt32 + 1)); //interf.SetRegister(nameof(registers.TestInt32), (registers.TestInt32 + 1));
//adds 11.11 each time the plc connects to the PLCs REAL regíster //adds 11.11 each time the plc connects to the PLCs REAL regíster
interf.SetRegister(nameof(registers.TestFloat32), (float)(registers.TestFloat32 + 11.11)); //interf.SetRegister(nameof(registers.TestFloat32), (float)(registers.TestFloat32 + 11.11));
//writes 'Hello' to the PLCs string register //writes 'Hello' to the PLCs string register
interf.SetRegister(nameof(registers.TestString2), "Hello"); //interf.SetRegister(nameof(registers.TestString2), "Hello");
//set the current second to the PLCs TIME register //set the current second to the PLCs TIME register
interf.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second)); //interf.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second));
}); });

View File

@@ -18,11 +18,11 @@ namespace Examples {
public bool TestBoolInputXD { get; private set; } public bool TestBoolInputXD { get; private set; }
//corresponds to a DT1101 - DT1104 string register in the PLC with (STRING[4]) //corresponds to a DT1101 - DT1104 string register in the PLC with (STRING[4])
[Register(1101, 4)] //[Register(1101, 4)]
public string TestString1 { get; private set; } //public string TestString1 { get; private set; }
//corresponds to a DT7000 16 bit int register in the PLC //corresponds to a DT7000 16 bit int register in the PLC
[Register(7000)] [Register(899)]
public short TestInt16 { get; private set; } public short TestInt16 { get; private set; }
//corresponds to a DTD7001 - DTD7002 32 bit int register in the PLC //corresponds to a DTD7001 - DTD7002 32 bit int register in the PLC

View File

@@ -33,63 +33,27 @@ namespace MewtocolNet {
/// </summary> /// </summary>
internal void AttachPoller () { internal void AttachPoller () {
if (ContinousReaderRunning) return; if (ContinousReaderRunning)
return;
Task.Factory.StartNew(async () => {
cTokenAutoUpdater = new CancellationTokenSource(); cTokenAutoUpdater = new CancellationTokenSource();
Logger.Log("Poller is attaching", LogLevel.Info, this); Logger.Log("Poller is attaching", LogLevel.Info, this);
try { int it = 0;
Task.Factory.StartNew(async () => { while (it < Registers.Count + 1) {
var plcinf = await GetPLCInfoAsync(); if (it >= Registers.Count) {
if (plcinf == null) { it = 0;
Logger.Log("PLC not reachable, stopping logger", LogLevel.Info, this); //invoke cycle polled event
return; InvokePolledCycleDone();
continue;
} }
PolledCycle += MewtocolInterface_PolledCycle; var reg = Registers[it];
void MewtocolInterface_PolledCycle () {
StringBuilder stringBuilder = new StringBuilder();
foreach (var reg in GetAllRegisters()) {
string address = $"{reg.GetRegisterString()}{reg.GetStartingMemoryArea()}".PadRight(8, (char)32);
stringBuilder.AppendLine($"{address}{(reg.Name != null ? $" ({reg.Name})" : "")}: {reg.GetValueString()}");
}
Logger.Log($"Registers loaded are: \n" +
$"--------------------\n" +
$"{stringBuilder.ToString()}" +
$"--------------------",
LogLevel.Verbose, this);
Logger.Log("Logger did its first cycle successfully", LogLevel.Info, this);
PolledCycle -= MewtocolInterface_PolledCycle;
}
ContinousReaderRunning = true;
int getPLCinfoCycleCount = 0;
while (ContinousReaderRunning) {
//do priority tasks first
if (PriorityTasks != null && PriorityTasks.Count > 0) {
try {
await PriorityTasks?.FirstOrDefault(x => !x.IsCompleted);
} catch (NullReferenceException) { }
} else if (getPLCinfoCycleCount > 25) {
await GetPLCInfoAsync();
getPLCinfoCycleCount = 0;
}
foreach (var reg in Registers) {
if (reg is NRegister<short> shortReg) { if (reg is NRegister<short> shortReg) {
var lastVal = shortReg.Value; var lastVal = shortReg.Value;
@@ -146,21 +110,13 @@ namespace MewtocolNet {
if (lastVal != readout) { if (lastVal != readout) {
InvokeRegisterChanged(stringReg); InvokeRegisterChanged(stringReg);
} }
}
it++;
} }
} });
getPLCinfoCycleCount++;
//invoke cycle polled event
InvokePolledCycleDone();
}
}, cTokenAutoUpdater.Token);
} catch (TaskCanceledException) { }
} }

View File

@@ -75,7 +75,7 @@ namespace MewtocolNet {
var res = new Regex(@"\%([0-9]{2})\$RD.{8}(.*)...").Match(_onString); var res = new Regex(@"\%([0-9]{2})\$RD.{8}(.*)...").Match(_onString);
if(res.Success) { if(res.Success) {
string val = res.Groups[2].Value; string val = res.Groups[2].Value;
return val.GetStringFromAsciiHex().Trim(); return val.GetStringFromAsciiHex()?.Trim();
} }
return null; return null;
} }
@@ -143,7 +143,7 @@ namespace MewtocolNet {
internal static string GetStringFromAsciiHex (this string input) { internal static string GetStringFromAsciiHex (this string input) {
if (input.Length % 2 != 0) if (input.Length % 2 != 0)
throw new ArgumentException("input not a hex string"); return null;
byte[] bytes = new byte[input.Length / 2]; byte[] bytes = new byte[input.Length / 2];
for (int i = 0; i < input.Length; i += 2) { for (int i = 0; i < input.Length; i += 2) {
String hex = input.Substring(i, 2); String hex = input.Substring(i, 2);
@@ -158,6 +158,8 @@ namespace MewtocolNet {
} }
internal static byte[] HexStringToByteArray(this string hex) { internal static byte[] HexStringToByteArray(this string hex) {
if (hex == null)
return null;
return Enumerable.Range(0, hex.Length) return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0) .Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))

View File

@@ -12,6 +12,9 @@ using MewtocolNet.Logging;
using System.Collections; using System.Collections;
using System.Diagnostics; using System.Diagnostics;
using System.ComponentModel; using System.ComponentModel;
using System.Net;
using System.Threading;
using MewtocolNet.Queue;
namespace MewtocolNet { namespace MewtocolNet {
@@ -86,7 +89,7 @@ namespace MewtocolNet {
/// </summary> /// </summary>
public int StationNumber => stationNumber; public int StationNumber => stationNumber;
private int cycleTimeMs; private int cycleTimeMs = 25;
/// <summary> /// <summary>
/// The duration of the last message cycle /// The duration of the last message cycle
/// </summary> /// </summary>
@@ -98,9 +101,10 @@ namespace MewtocolNet {
} }
} }
internal NetworkStream stream;
internal List<Task> PriorityTasks { get; set; } = new List<Task>(); internal TcpClient client;
internal readonly SerialQueue queue = new SerialQueue();
private int RecBufferSize = 64;
internal int SendExceptionsInRow = 0; internal int SendExceptionsInRow = 0;
#region Initialization #region Initialization
@@ -205,8 +209,6 @@ namespace MewtocolNet {
OnMajorSocketException(); OnMajorSocketException();
PriorityTasks.Clear();
} }
/// <summary> /// <summary>
@@ -335,8 +337,11 @@ namespace MewtocolNet {
var bytes = BitConverter.GetBytes(reg16.Value); var bytes = BitConverter.GetBytes(reg16.Value);
BitArray bitAr = new BitArray(bytes); BitArray bitAr = new BitArray(bytes);
if (bitIndex < bitAr.Length && bitIndex >= 0) {
prop.SetValue(collection, bitAr[bitIndex]); prop.SetValue(collection, bitAr[bitIndex]);
collection.TriggerPropertyChanged(prop.Name); collection.TriggerPropertyChanged(prop.Name);
}
} else if (bitWiseFound != null && reg is NRegister<int> reg32) { } else if (bitWiseFound != null && reg is NRegister<int> reg32) {
var casted = (RegisterAttribute)bitWiseFound; var casted = (RegisterAttribute)bitWiseFound;
@@ -542,6 +547,25 @@ namespace MewtocolNet {
#region Low level command handling #region Low level command handling
private async Task ConnectTCP () {
var targetIP = IPAddress.Parse(ip);
client = new TcpClient() {
ReceiveBufferSize = RecBufferSize,
NoDelay = false,
ExclusiveAddressUse = true
};
await client.ConnectAsync(targetIP, port);
stream = client.GetStream();
stream.ReadTimeout = 1000;
Console.WriteLine($"Connected {client.Connected}");
}
/// <summary> /// <summary>
/// Calculates checksum and sends a command to the PLC then awaits results /// Calculates checksum and sends a command to the PLC then awaits results
/// </summary> /// </summary>
@@ -553,27 +577,9 @@ namespace MewtocolNet {
_msg += "\r"; _msg += "\r";
//send request //send request
try {
string response = null; var response = await queue.Enqueue(() => SendSingleBlock(_msg));
if (ContinousReaderRunning) {
//if the poller is active then add all messages to a qeueue
var awaittask = SendSingleBlock(_msg);
PriorityTasks.Add(awaittask);
await awaittask;
PriorityTasks.Remove(awaittask);
response = awaittask.Result;
} else {
//poller not active let the user manage message timing
response = await SendSingleBlock(_msg);
}
if (response == null) { if (response == null) {
return new CommandResult { return new CommandResult {
@@ -591,7 +597,7 @@ namespace MewtocolNet {
string eDes = Links.LinkedData.ErrorCodes[Convert.ToInt32(eCode)]; string eDes = Links.LinkedData.ErrorCodes[Convert.ToInt32(eCode)];
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Response is: {response}"); Console.WriteLine($"Response is: {response}");
Console.WriteLine($"Error on command {_msg.Replace("\r", "")} the PLC returned error code: {eCode}, {eDes}"); Logger.Log($"Error on command {_msg.Replace("\r", "")} the PLC returned error code: {eCode}, {eDes}", LogLevel.Error);
Console.ResetColor(); Console.ResetColor();
return new CommandResult { return new CommandResult {
Success = false, Success = false,
@@ -606,49 +612,58 @@ namespace MewtocolNet {
Response = response.ToString() Response = response.ToString()
}; };
} catch {
return new CommandResult {
Success = false,
Error = "0000",
ErrorDescription = "null result"
};
}
} }
private async Task<string> SendSingleBlock (string _blockString) { private async Task<string> SendSingleBlock (string _blockString) {
Stopwatch sw = Stopwatch.StartNew(); if (client == null || !client.Connected ) {
await ConnectTCP();
using (TcpClient client = new TcpClient() { ReceiveBufferSize = 64, NoDelay = true, ExclusiveAddressUse = true }) { if (!client.Connected)
return null;
try { }
await client.ConnectAsync(ip, port);
using (NetworkStream stream = client.GetStream()) {
var message = _blockString.ToHexASCIIBytes(); var message = _blockString.ToHexASCIIBytes();
var messageAscii = BitConverter.ToString(message).Replace("-", " ");
//send request //send request
try {
using (var sendStream = new MemoryStream(message)) { using (var sendStream = new MemoryStream(message)) {
await sendStream.CopyToAsync(stream); await sendStream.CopyToAsync(stream);
Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this); Logger.Log($"[--------------------------------]", LogLevel.Critical, this);
//log message sent Logger.Log($"--> OUT MSG: {_blockString}", LogLevel.Critical, this);
ASCIIEncoding enc = new ASCIIEncoding();
string characters = enc.GetString(message);
}
} catch (IOException) {
Logger.Log($"Critical IO exception on send", LogLevel.Critical, this);
return null;
} catch (SocketException) {
OnMajorSocketException();
return null;
} }
//await result //await result
StringBuilder response = new StringBuilder(); StringBuilder response = new StringBuilder();
try { try {
byte[] responseBuffer = new byte[256];
byte[] responseBuffer = new byte[128 * 16];
bool endLineCode = false;
bool startMsgCode = false;
while (!endLineCode && !startMsgCode) {
do { do {
int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length); int bytes = await stream.ReadAsync(responseBuffer, 0, responseBuffer.Length);
endLineCode = responseBuffer.Any(x => x == 0x0D);
startMsgCode = responseBuffer.Count(x => x == 0x25) > 1;
if (!endLineCode && !startMsgCode) break;
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes)); response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
} }
while (stream.DataAvailable); while (stream.DataAvailable);
}
} catch (IOException) { } catch (IOException) {
Logger.Log($"Critical IO exception on receive", LogLevel.Critical, this); Logger.Log($"Critical IO exception on receive", LogLevel.Critical, this);
return null; return null;
@@ -657,23 +672,11 @@ namespace MewtocolNet {
return null; return null;
} }
sw.Stop(); if(!string.IsNullOrEmpty(response.ToString())) {
var curCycle = (int)sw.ElapsedMilliseconds; Logger.Log($"<-- IN MSG (TXT): {response} ({response.Length} bytes)", LogLevel.Critical, this);
if (Math.Abs(CycleTimeMs - curCycle) > 2) {
CycleTimeMs = curCycle;
}
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {response}", LogLevel.Critical, this);
return response.ToString(); return response.ToString();
} } else {
} catch (SocketException) {
OnMajorSocketException();
return null; return null;
}
} }
} }
@@ -709,4 +712,5 @@ namespace MewtocolNet {
} }
} }

View File

@@ -117,7 +117,6 @@ namespace MewtocolNet {
string startStr = start.ToString().PadLeft(5, '0'); string startStr = start.ToString().PadLeft(5, '0');
var wordLength = count / 2; var wordLength = count / 2;
bool wasOdd = false;
if (count % 2 != 0) if (count % 2 != 0)
wordLength++; wordLength++;
@@ -128,8 +127,13 @@ namespace MewtocolNet {
if(result.Success && !string.IsNullOrEmpty(result.Response)) { if(result.Success && !string.IsNullOrEmpty(result.Response)) {
var res = result;
var bytes = result.Response.ParseDTByteString(wordLength * 4).HexStringToByteArray(); var bytes = result.Response.ParseDTByteString(wordLength * 4).HexStringToByteArray();
if (bytes == null)
return null;
return bytes.BigToMixedEndian().Take(count).ToArray(); return bytes.BigToMixedEndian().Take(count).ToArray();
} }
@@ -196,7 +200,6 @@ namespace MewtocolNet {
/// </summary> /// </summary>
/// <typeparam name="T">Type of number (short, ushort, int, uint, float)</typeparam> /// <typeparam name="T">Type of number (short, ushort, int, uint, float)</typeparam>
/// <param name="_toRead">The register to read</param> /// <param name="_toRead">The register to read</param>
/// <param name="_stationNumber">Station number to access</param>
/// <returns>A result with the given NumberRegister containing the readback value and a result struct</returns> /// <returns>A result with the given NumberRegister containing the readback value and a result struct</returns>
public async Task<NRegisterResult<T>> ReadNumRegister<T> (NRegister<T> _toRead) { public async Task<NRegisterResult<T>> ReadNumRegister<T> (NRegister<T> _toRead) {
@@ -205,40 +208,47 @@ namespace MewtocolNet {
string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolIdent()}"; string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolIdent()}";
var result = await SendCommandAsync(requeststring); var result = await SendCommandAsync(requeststring);
if(!result.Success || string.IsNullOrEmpty(result.Response)) { var failedResult = new NRegisterResult<T> {
return new NRegisterResult<T> {
Result = result, Result = result,
Register = _toRead Register = _toRead
}; };
if (!result.Success || string.IsNullOrEmpty(result.Response)) {
return failedResult;
} }
if (numType == typeof(short)) { if (numType == typeof(short)) {
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder(); var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
if (resultBytes == null) return failedResult;
var val = short.Parse(resultBytes, NumberStyles.HexNumber); var val = short.Parse(resultBytes, NumberStyles.HexNumber);
_toRead.SetValueFromPLC(val); _toRead.SetValueFromPLC(val);
} else if (numType == typeof(ushort)) { } else if (numType == typeof(ushort)) {
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder(); var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
if (resultBytes == null) return failedResult;
var val = ushort.Parse(resultBytes, NumberStyles.HexNumber); var val = ushort.Parse(resultBytes, NumberStyles.HexNumber);
_toRead.SetValueFromPLC(val); _toRead.SetValueFromPLC(val);
} else if (numType == typeof(int)) { } else if (numType == typeof(int)) {
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder(); var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
if (resultBytes == null) return failedResult;
var val = int.Parse(resultBytes, NumberStyles.HexNumber); var val = int.Parse(resultBytes, NumberStyles.HexNumber);
_toRead.SetValueFromPLC(val); _toRead.SetValueFromPLC(val);
} else if (numType == typeof(uint)) { } else if (numType == typeof(uint)) {
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder(); var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
if (resultBytes == null) return failedResult;
var val = uint.Parse(resultBytes, NumberStyles.HexNumber); var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
_toRead.SetValueFromPLC(val); _toRead.SetValueFromPLC(val);
} else if (numType == typeof(float)) { } else if (numType == typeof(float)) {
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder(); var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
if (resultBytes == null) return failedResult;
//convert to unsigned int first //convert to unsigned int first
var val = uint.Parse(resultBytes, NumberStyles.HexNumber); var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
@@ -250,6 +260,7 @@ namespace MewtocolNet {
} else if (numType == typeof(TimeSpan)) { } else if (numType == typeof(TimeSpan)) {
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder(); var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
if (resultBytes == null) return failedResult;
//convert to unsigned int first //convert to unsigned int first
var vallong = long.Parse(resultBytes, NumberStyles.HexNumber); var vallong = long.Parse(resultBytes, NumberStyles.HexNumber);
var valMillis = vallong * 10; var valMillis = vallong * 10;

View File

@@ -145,7 +145,7 @@ namespace MewtocolNet.Registers {
return boolReg.Value.ToString(); return boolReg.Value.ToString();
} }
if (this is SRegister stringReg) { if (this is SRegister stringReg) {
return stringReg.Value.ToString(); return stringReg.Value ?? "";
} }
return "Type of the register is not supported."; return "Type of the register is not supported.";

View File

@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<PackageId>MewtocolNet</PackageId> <PackageId>MewtocolNet</PackageId>
<Version>0.4.3</Version> <Version>0.5.0</Version>
<Authors>Felix Weiss</Authors> <Authors>Felix Weiss</Authors>
<Company>Womed</Company> <Company>Womed</Company>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>

View File

@@ -0,0 +1,71 @@
using System;
using System.Threading.Tasks;
namespace MewtocolNet.Queue {
internal class SerialQueue {
readonly object _locker = new object();
readonly WeakReference<Task> _lastTask = new WeakReference<Task>(null);
internal Task Enqueue (Action action) {
return Enqueue<bool>(() => {
action();
return true;
});
}
internal Task<T> Enqueue<T> (Func<T> function) {
lock (_locker) {
Task lastTask;
Task<T> resultTask;
if (_lastTask.TryGetTarget(out lastTask)) {
resultTask = lastTask.ContinueWith(_ => function(), TaskContinuationOptions.ExecuteSynchronously);
} else {
resultTask = Task.Run(function);
}
_lastTask.SetTarget(resultTask);
return resultTask;
}
}
internal Task Enqueue (Func<Task> asyncAction) {
lock (_locker) {
Task lastTask;
Task resultTask;
if (_lastTask.TryGetTarget(out lastTask)) {
resultTask = lastTask.ContinueWith(_ => asyncAction(), TaskContinuationOptions.ExecuteSynchronously).Unwrap();
} else {
resultTask = Task.Run(asyncAction);
}
_lastTask.SetTarget(resultTask);
return resultTask;
}
}
internal Task<T> Enqueue<T> (Func<Task<T>> asyncFunction) {
lock (_locker) {
Task lastTask;
Task<T> resultTask;
if (_lastTask.TryGetTarget(out lastTask)) {
resultTask = lastTask.ContinueWith(_ => asyncFunction(), TaskContinuationOptions.ExecuteSynchronously).Unwrap();
} else {
resultTask = Task.Run(asyncFunction);
}
_lastTask.SetTarget(resultTask);
return resultTask;
}
}
}
}