3 Commits

3 changed files with 74 additions and 26 deletions

View File

@@ -76,9 +76,11 @@ namespace MewtocolNet {
while (ContinousReaderRunning) { while (ContinousReaderRunning) {
//do priority tasks first //do priority tasks first
if (PriorityTasks.Count > 0) { if (PriorityTasks != null && PriorityTasks.Count > 0) {
await PriorityTasks.FirstOrDefault(x => !x.IsCompleted); try {
await PriorityTasks?.FirstOrDefault(x => !x.IsCompleted);
} catch (NullReferenceException) { }
} else if (getPLCinfoCycleCount > 25) { } else if (getPLCinfoCycleCount > 25) {

View File

@@ -101,6 +101,8 @@ namespace MewtocolNet {
internal List<Task> PriorityTasks { get; set; } = new List<Task>(); internal List<Task> PriorityTasks { get; set; } = new List<Task>();
internal int SendExceptionsInRow = 0;
#region Initialization #region Initialization
/// <summary> /// <summary>
@@ -193,6 +195,20 @@ namespace MewtocolNet {
} }
/// <summary>
/// Closes all permanent polling
/// </summary>
public void Disconnect () {
if (!IsConnected)
return;
OnMajorSocketException();
PriorityTasks.Clear();
}
/// <summary> /// <summary>
/// Attaches a poller to the interface that continously /// Attaches a poller to the interface that continously
/// polls the registered data registers and writes the values to them /// polls the registered data registers and writes the values to them
@@ -384,6 +400,10 @@ namespace MewtocolNet {
foundToUpdate.SetValue(collection, ((NRegister<int>)reg).Value); foundToUpdate.SetValue(collection, ((NRegister<int>)reg).Value);
} }
if (foundToUpdate.PropertyType == typeof(TimeSpan)) {
foundToUpdate.SetValue(collection, ((NRegister<TimeSpan>)reg).Value);
}
//setting back strings //setting back strings
if (foundToUpdate.PropertyType == typeof(string)) { if (foundToUpdate.PropertyType == typeof(string)) {
@@ -526,7 +546,6 @@ namespace MewtocolNet {
/// 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>
/// <param name="_msg">MEWTOCOL Formatted request string ex: %01#RT</param> /// <param name="_msg">MEWTOCOL Formatted request string ex: %01#RT</param>
/// <param name="_close">Auto close of frame [true]%01#RT01\r [false]%01#RT</param>
/// <returns>Returns the result</returns> /// <returns>Returns the result</returns>
public async Task<CommandResult> SendCommandAsync (string _msg) { public async Task<CommandResult> SendCommandAsync (string _msg) {
@@ -543,7 +562,7 @@ namespace MewtocolNet {
var awaittask = SendSingleBlock(_msg); var awaittask = SendSingleBlock(_msg);
PriorityTasks.Add(awaittask); PriorityTasks.Add(awaittask);
awaittask.Wait(); await awaittask;
PriorityTasks.Remove(awaittask); PriorityTasks.Remove(awaittask);
response = awaittask.Result; response = awaittask.Result;
@@ -600,43 +619,57 @@ namespace MewtocolNet {
await client.ConnectAsync(ip, port); await client.ConnectAsync(ip, port);
using (NetworkStream stream = client.GetStream()) { using (NetworkStream stream = client.GetStream()) {
var message = _blockString.ToHexASCIIBytes(); var message = _blockString.ToHexASCIIBytes();
var messageAscii = BitConverter.ToString(message).Replace("-", " "); var messageAscii = BitConverter.ToString(message).Replace("-", " ");
//send request //send request
using (var sendStream = new MemoryStream(message)) { try {
await sendStream.CopyToAsync(stream); using (var sendStream = new MemoryStream(message)) {
Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this); await sendStream.CopyToAsync(stream);
//log message sent Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this);
ASCIIEncoding enc = new ASCIIEncoding(); //log message sent
string characters = enc.GetString(message); 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();
byte[] responseBuffer = new byte[256]; try {
do { byte[] responseBuffer = new byte[256];
int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length); do {
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes)); int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length);
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
}
while (stream.DataAvailable);
} catch (IOException) {
Logger.Log($"Critical IO exception on receive", LogLevel.Critical, this);
return null;
} catch (SocketException) {
OnMajorSocketException();
return null;
} }
while (stream.DataAvailable);
sw.Stop(); sw.Stop();
var curCycle = (int)sw.ElapsedMilliseconds; var curCycle = (int)sw.ElapsedMilliseconds;
if (Math.Abs(CycleTimeMs - curCycle) > 2) { if (Math.Abs(CycleTimeMs - curCycle) > 2) {
CycleTimeMs = curCycle; CycleTimeMs = curCycle;
} }
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {_blockString}", LogLevel.Critical, this);
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {response}", LogLevel.Critical, this);
return response.ToString(); return response.ToString();
} }
} catch (Exception) { } catch (SocketException) {
if (IsConnected) { OnMajorSocketException();
CycleTimeMs = 0;
IsConnected = false;
Disconnected?.Invoke();
}
KillPoller();
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
return null; return null;
} }
@@ -645,6 +678,19 @@ namespace MewtocolNet {
} }
private void OnMajorSocketException () {
if (IsConnected) {
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
CycleTimeMs = 0;
IsConnected = false;
Disconnected?.Invoke();
KillPoller();
}
}
#endregion #endregion

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.0</Version> <Version>0.4.2</Version>
<Authors>Felix Weiss</Authors> <Authors>Felix Weiss</Authors>
<Company>Womed</Company> <Company>Womed</Company>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>