mirror of
https://github.com/OpenLogics/MewtocolNet.git
synced 2025-12-06 11:11:23 +00:00
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f15d565029 | ||
|
|
0ac0198223 | ||
|
|
3c450eea97 | ||
|
|
fe2d2b9fb9 | ||
|
|
6c411d7318 | ||
|
|
cdae9a60fb | ||
|
|
b1c2cdb70e | ||
|
|
95bfcf94de | ||
|
|
0a93df287d | ||
|
|
18384ff964 | ||
|
|
e4ddad685a | ||
|
|
e953938a65 | ||
|
|
83f17a4eae |
@@ -2,69 +2,135 @@
|
||||
using System.Threading.Tasks;
|
||||
using MewtocolNet;
|
||||
using MewtocolNet.Logging;
|
||||
using MewtocolNet.Registers;
|
||||
|
||||
namespace Examples {
|
||||
namespace Examples;
|
||||
|
||||
class Program {
|
||||
class Program {
|
||||
|
||||
static void Main(string[] args) {
|
||||
static void Main(string[] args) {
|
||||
|
||||
Task.Factory.StartNew(async () => {
|
||||
Console.WriteLine("Enter your scenario number:\n" +
|
||||
"1 = Permanent connection\n" +
|
||||
"2 = Dispose connection");
|
||||
|
||||
//attaching the logger
|
||||
Logger.LogLevel = LogLevel.Verbose;
|
||||
Logger.OnNewLogMessage((date, msg) => {
|
||||
Console.WriteLine($"{date.ToString("HH:mm:ss")} {msg}");
|
||||
});
|
||||
var line = Console.ReadLine();
|
||||
|
||||
//setting up a new PLC interface and register collection
|
||||
MewtocolInterface interf = new MewtocolInterface("10.237.191.3");
|
||||
TestRegisters registers = new TestRegisters();
|
||||
if(line == "1") {
|
||||
Scenario1();
|
||||
}
|
||||
|
||||
//attaching the register collection and an automatic poller
|
||||
interf.WithRegisterCollection(registers).WithPoller();
|
||||
if (line == "2") {
|
||||
Scenario2();
|
||||
}
|
||||
|
||||
await interf.ConnectAsync(
|
||||
(plcinf) => {
|
||||
Console.ReadLine();
|
||||
}
|
||||
|
||||
//reading a value from the register collection
|
||||
Console.WriteLine($"BitValue is: {registers.BitValue}");
|
||||
static void Scenario1 () {
|
||||
|
||||
interf.GetRegister(nameof(registers.TestBool1)).PropertyChanged += (s, e) => {
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.WriteLine(interf.GetRegister(nameof(registers.TestBool1)).StringValue);
|
||||
Console.ResetColor();
|
||||
};
|
||||
|
||||
//writing a value to the registers
|
||||
Task.Factory.StartNew(async () => {
|
||||
|
||||
//set plc to run mode if not already
|
||||
await interf.SetOperationMode(OPMode.Run);
|
||||
|
||||
await Task.Delay(2000);
|
||||
|
||||
Console.WriteLine("Testregister was toggled");
|
||||
|
||||
//adds 10 each time the plc connects to the PLCs INT regíster
|
||||
interf.SetRegister(nameof(registers.TestInt16), (short)(registers.TestInt16 + 10));
|
||||
//adds 1 each time the plc connects to the PLCs DINT regíster
|
||||
interf.SetRegister(nameof(registers.TestInt32), (registers.TestInt32 + 1));
|
||||
//adds 11.11 each time the plc connects to the PLCs REAL regíster
|
||||
interf.SetRegister(nameof(registers.TestFloat32), (float)(registers.TestFloat32 + 11.11));
|
||||
//writes 'Hello' to the PLCs string register
|
||||
interf.SetRegister(nameof(registers.TestString2), "Hello");
|
||||
//set the current second to the PLCs TIME register
|
||||
interf.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second));
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
);
|
||||
Task.Factory.StartNew(async () => {
|
||||
|
||||
//attaching the logger
|
||||
Logger.LogLevel = LogLevel.Critical;
|
||||
Logger.OnNewLogMessage((date, msg) => {
|
||||
Console.WriteLine($"{date.ToString("HH:mm:ss")} {msg}");
|
||||
});
|
||||
|
||||
Console.ReadLine();
|
||||
}
|
||||
//setting up a new PLC interface and register collection
|
||||
MewtocolInterface interf = new MewtocolInterface("10.237.191.3");
|
||||
TestRegisters registers = new TestRegisters();
|
||||
|
||||
//attaching the register collection and an automatic poller
|
||||
interf.WithRegisterCollection(registers).WithPoller();
|
||||
|
||||
await interf.ConnectAsync(
|
||||
(plcinf) => {
|
||||
|
||||
//reading a value from the register collection
|
||||
Console.WriteLine($"BitValue is: {registers.BitValue}");
|
||||
Console.WriteLine($"TestEnum is: {registers.TestEnum}");
|
||||
|
||||
//writing a value to the registers
|
||||
Task.Factory.StartNew(async () => {
|
||||
|
||||
//set plc to run mode if not already
|
||||
await interf.SetOperationMode(OPMode.Run);
|
||||
|
||||
|
||||
int startAdress = 10000;
|
||||
int entryByteSize = 20 * 20;
|
||||
|
||||
var bytes = await interf.ReadByteRange(startAdress, entryByteSize);
|
||||
Console.WriteLine($"Bytes: {string.Join('-', bytes)}");
|
||||
|
||||
await Task.Delay(2000);
|
||||
|
||||
await interf.SetRegisterAsync(nameof(registers.TestInt32), 100);
|
||||
|
||||
//adds 10 each time the plc connects to the PLCs INT regíster
|
||||
interf.SetRegister(nameof(registers.TestInt16), (short)(registers.TestInt16 + 10));
|
||||
//adds 1 each time the plc connects to the PLCs DINT regíster
|
||||
interf.SetRegister(nameof(registers.TestInt32), (registers.TestInt32 + 1));
|
||||
//adds 11.11 each time the plc connects to the PLCs REAL regíster
|
||||
interf.SetRegister(nameof(registers.TestFloat32), (float)(registers.TestFloat32 + 11.11));
|
||||
//writes 'Hello' to the PLCs string register
|
||||
interf.SetRegister(nameof(registers.TestString2), "Hello");
|
||||
//set the current second to the PLCs TIME register
|
||||
interf.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second));
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
static void Scenario2 () {
|
||||
|
||||
Logger.LogLevel = LogLevel.Critical;
|
||||
Logger.OnNewLogMessage((date, msg) => {
|
||||
Console.WriteLine($"{date.ToString("HH:mm:ss")} {msg}");
|
||||
});
|
||||
|
||||
Task.Factory.StartNew(async () => {
|
||||
|
||||
using(var interf = new MewtocolInterface("10.237.191.3")) {
|
||||
|
||||
await interf.ConnectAsync();
|
||||
|
||||
if(interf.IsConnected) {
|
||||
|
||||
var plcInf = await interf.GetPLCInfoAsync();
|
||||
Console.WriteLine(plcInf);
|
||||
|
||||
}
|
||||
|
||||
interf.Disconnect();
|
||||
|
||||
}
|
||||
|
||||
|
||||
using (var interf = new MewtocolInterface("10.237.191.3")) {
|
||||
|
||||
await interf.ConnectAsync();
|
||||
|
||||
if (interf.IsConnected) {
|
||||
|
||||
var plcInf = await interf.GetPLCInfoAsync();
|
||||
Console.WriteLine(plcInf);
|
||||
|
||||
}
|
||||
|
||||
interf.Disconnect();
|
||||
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -10,16 +10,19 @@ namespace Examples {
|
||||
[Register(1000, RegisterType.R)]
|
||||
public bool TestBool1 { get; private set; }
|
||||
|
||||
[Register(1000)]
|
||||
public int TestDuplicate { get; private set; }
|
||||
|
||||
//corresponds to a XD input of the PLC
|
||||
[Register(RegisterType.X, SpecialAddress.D)]
|
||||
public bool TestBoolInputXD { get; private set; }
|
||||
|
||||
//corresponds to a DT1101 - DT1104 string register in the PLC with (STRING[4])
|
||||
[Register(1101, 4)]
|
||||
public string TestString1 { get; private set; }
|
||||
//[Register(1101, 4)]
|
||||
//public string TestString1 { get; private set; }
|
||||
|
||||
//corresponds to a DT7000 16 bit int register in the PLC
|
||||
[Register(7000)]
|
||||
[Register(899)]
|
||||
public short TestInt16 { get; private set; }
|
||||
|
||||
//corresponds to a DTD7001 - DTD7002 32 bit int register in the PLC
|
||||
@@ -50,5 +53,21 @@ namespace Examples {
|
||||
[Register(7012)]
|
||||
public TimeSpan TestTime { get; private set; }
|
||||
|
||||
public enum CurrentState {
|
||||
Undefined = 0,
|
||||
State1 = 1,
|
||||
State2 = 2,
|
||||
//State3 = 3,
|
||||
State4 = 4,
|
||||
State5 = 5,
|
||||
StateBetween = 100,
|
||||
State6 = 6,
|
||||
State7 = 7,
|
||||
}
|
||||
|
||||
[Register(50)]
|
||||
public CurrentState TestEnum { get; private set; }
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ namespace MewtocolNet {
|
||||
public partial class MewtocolInterface {
|
||||
|
||||
internal event Action PolledCycle;
|
||||
internal CancellationTokenSource cTokenAutoUpdater;
|
||||
internal bool ContinousReaderRunning;
|
||||
internal bool usePoller = false;
|
||||
|
||||
@@ -24,7 +23,6 @@ namespace MewtocolNet {
|
||||
internal void KillPoller () {
|
||||
|
||||
ContinousReaderRunning = false;
|
||||
cTokenAutoUpdater?.Cancel();
|
||||
|
||||
}
|
||||
|
||||
@@ -33,134 +31,95 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
internal void AttachPoller () {
|
||||
|
||||
if (ContinousReaderRunning) return;
|
||||
if (ContinousReaderRunning)
|
||||
return;
|
||||
|
||||
cTokenAutoUpdater = new CancellationTokenSource();
|
||||
Task.Factory.StartNew(async () => {
|
||||
|
||||
Logger.Log("Poller is attaching", LogLevel.Info, this);
|
||||
Logger.Log("Poller is attaching", LogLevel.Info, this);
|
||||
|
||||
try {
|
||||
int it = 0;
|
||||
ContinousReaderRunning = true;
|
||||
|
||||
Task.Factory.StartNew(async () => {
|
||||
|
||||
var plcinf = await GetPLCInfoAsync();
|
||||
if (plcinf == null) {
|
||||
Logger.Log("PLC not reachable, stopping logger", LogLevel.Info, this);
|
||||
return;
|
||||
}
|
||||
|
||||
PolledCycle += MewtocolInterface_PolledCycle;
|
||||
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.Count > 0) {
|
||||
|
||||
await PriorityTasks.FirstOrDefault(x => !x.IsCompleted);
|
||||
|
||||
} else if (getPLCinfoCycleCount > 25) {
|
||||
|
||||
await GetPLCInfoAsync();
|
||||
getPLCinfoCycleCount = 0;
|
||||
|
||||
}
|
||||
|
||||
foreach (var registerPair in Registers) {
|
||||
|
||||
var reg = registerPair.Value;
|
||||
|
||||
if (reg is NRegister<short> shortReg) {
|
||||
var lastVal = shortReg.Value;
|
||||
var readout = (await ReadNumRegister(shortReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(shortReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<ushort> ushortReg) {
|
||||
var lastVal = ushortReg.Value;
|
||||
var readout = (await ReadNumRegister(ushortReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(ushortReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<int> intReg) {
|
||||
var lastVal = intReg.Value;
|
||||
var readout = (await ReadNumRegister(intReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(intReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<uint> uintReg) {
|
||||
var lastVal = uintReg.Value;
|
||||
var readout = (await ReadNumRegister(uintReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(uintReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<float> floatReg) {
|
||||
var lastVal = floatReg.Value;
|
||||
var readout = (await ReadNumRegister(floatReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(floatReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<TimeSpan> tsReg) {
|
||||
var lastVal = tsReg.Value;
|
||||
var readout = (await ReadNumRegister(tsReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(tsReg);
|
||||
}
|
||||
}
|
||||
if (reg is BRegister boolReg) {
|
||||
var lastVal = boolReg.Value;
|
||||
var readout = (await ReadBoolRegister(boolReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(boolReg);
|
||||
}
|
||||
}
|
||||
if (reg is SRegister stringReg) {
|
||||
var lastVal = stringReg.Value;
|
||||
var readout = (await ReadStringRegister(stringReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(stringReg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
getPLCinfoCycleCount++;
|
||||
while (ContinousReaderRunning) {
|
||||
|
||||
if (it >= Registers.Count + 1) {
|
||||
it = 0;
|
||||
//invoke cycle polled event
|
||||
InvokePolledCycleDone();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
}, cTokenAutoUpdater.Token);
|
||||
if (it >= Registers.Count) {
|
||||
await GetPLCInfoAsync();
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
|
||||
} catch (TaskCanceledException) { }
|
||||
var reg = Registers[it];
|
||||
|
||||
if (reg is NRegister<short> shortReg) {
|
||||
var lastVal = shortReg.Value;
|
||||
var readout = (await ReadNumRegister(shortReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(shortReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<ushort> ushortReg) {
|
||||
var lastVal = ushortReg.Value;
|
||||
var readout = (await ReadNumRegister(ushortReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(ushortReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<int> intReg) {
|
||||
var lastVal = intReg.Value;
|
||||
var readout = (await ReadNumRegister(intReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(intReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<uint> uintReg) {
|
||||
var lastVal = uintReg.Value;
|
||||
var readout = (await ReadNumRegister(uintReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(uintReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<float> floatReg) {
|
||||
var lastVal = floatReg.Value;
|
||||
var readout = (await ReadNumRegister(floatReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(floatReg);
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<TimeSpan> tsReg) {
|
||||
var lastVal = tsReg.Value;
|
||||
var readout = (await ReadNumRegister(tsReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(tsReg);
|
||||
}
|
||||
}
|
||||
if (reg is BRegister boolReg) {
|
||||
var lastVal = boolReg.Value;
|
||||
var readout = (await ReadBoolRegister(boolReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(boolReg);
|
||||
}
|
||||
}
|
||||
if (reg is SRegister stringReg) {
|
||||
var lastVal = stringReg.Value;
|
||||
var readout = (await ReadStringRegister(stringReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(stringReg);
|
||||
}
|
||||
}
|
||||
|
||||
it++;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@@ -208,7 +167,7 @@ namespace MewtocolNet {
|
||||
toAdd = new BRegister(_address, _type, _name);
|
||||
}
|
||||
|
||||
Registers.Add(_address, toAdd);
|
||||
Registers.Add(toAdd);
|
||||
|
||||
}
|
||||
|
||||
@@ -238,7 +197,7 @@ namespace MewtocolNet {
|
||||
}
|
||||
|
||||
toAdd.collectionType = _colType;
|
||||
Registers.Add(_address, toAdd);
|
||||
Registers.Add(toAdd);
|
||||
|
||||
}
|
||||
|
||||
@@ -259,7 +218,7 @@ namespace MewtocolNet {
|
||||
public void AddRegister (SpecialAddress _spAddress, RegisterType _type, string _name = null) {
|
||||
|
||||
//as bool registers
|
||||
Registers.Add((int)_spAddress, new BRegister(_spAddress, _type, _name));
|
||||
Registers.Add(new BRegister(_spAddress, _type, _name));
|
||||
|
||||
}
|
||||
|
||||
@@ -270,7 +229,7 @@ namespace MewtocolNet {
|
||||
reg.collectionType = _colType;
|
||||
|
||||
//as bool registers
|
||||
Registers.Add((int)_spAddress, reg);
|
||||
Registers.Add(reg);
|
||||
|
||||
}
|
||||
|
||||
@@ -299,35 +258,38 @@ namespace MewtocolNet {
|
||||
throw new NotSupportedException($"_lenght parameter only allowed for register of type string");
|
||||
}
|
||||
|
||||
if (Registers.Any(x => x.Key == _address)) {
|
||||
throw new NotSupportedException($"Cannot add a register multiple times, " +
|
||||
$"make sure that all register attributes or AddRegister assignments have different adresses.");
|
||||
}
|
||||
Register toAdd;
|
||||
|
||||
if (regType == typeof(short)) {
|
||||
Registers.Add(_address, new NRegister<short>(_address, _name));
|
||||
toAdd = new NRegister<short>(_address, _name);
|
||||
} else if (regType == typeof(ushort)) {
|
||||
Registers.Add(_address, new NRegister<ushort>(_address, _name));
|
||||
toAdd = new NRegister<ushort>(_address, _name);
|
||||
} else if (regType == typeof(int)) {
|
||||
Registers.Add(_address, new NRegister<int>(_address, _name));
|
||||
toAdd = new NRegister<int>(_address, _name);
|
||||
} else if (regType == typeof(uint)) {
|
||||
Registers.Add(_address, new NRegister<uint>(_address, _name));
|
||||
toAdd = new NRegister<uint>(_address, _name);
|
||||
} else if (regType == typeof(float)) {
|
||||
Registers.Add(_address, new NRegister<float>(_address, _name));
|
||||
toAdd = new NRegister<float>(_address, _name);
|
||||
} else if (regType == typeof(string)) {
|
||||
Registers.Add(_address, new SRegister(_address, _length, _name));
|
||||
toAdd = new SRegister(_address, _length, _name);
|
||||
} else if (regType == typeof(TimeSpan)) {
|
||||
Registers.Add(_address, new NRegister<TimeSpan>(_address, _name));
|
||||
toAdd = new NRegister<TimeSpan>(_address, _name);
|
||||
} else if (regType == typeof(bool)) {
|
||||
Registers.Add(_address, new BRegister(_address, RegisterType.R, _name));
|
||||
toAdd = new BRegister(_address, RegisterType.R, _name);
|
||||
} else {
|
||||
throw new NotSupportedException($"The type {regType} is not allowed for Registers \n" +
|
||||
$"Allowed are: short, ushort, int, uint, float and string");
|
||||
}
|
||||
|
||||
|
||||
if (Registers.Any(x => x.GetRegisterPLCName() == toAdd.GetRegisterPLCName())) {
|
||||
throw new NotSupportedException($"Cannot add a register multiple times, " +
|
||||
$"make sure that all register attributes or AddRegister assignments have different adresses.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal void AddRegister<T> (Type _colType, int _address, int _length = 1, string _name = null, bool _isBitwise = false) {
|
||||
internal void AddRegister<T> (Type _colType, int _address, int _length = 1, string _name = null, bool _isBitwise = false, Type _enumType = null) {
|
||||
|
||||
Type regType = typeof(T);
|
||||
|
||||
@@ -335,12 +297,7 @@ namespace MewtocolNet {
|
||||
throw new NotSupportedException($"_lenght parameter only allowed for register of type string");
|
||||
}
|
||||
|
||||
if (Registers.Any(x => x.Key == _address) && !_isBitwise) {
|
||||
throw new NotSupportedException($"Cannot add a register multiple times, " +
|
||||
$"make sure that all register attributes or AddRegister assignments have different adresses.");
|
||||
}
|
||||
|
||||
if (Registers.Any(x => x.Key == _address) && _isBitwise) {
|
||||
if (Registers.Any(x => x.MemoryAdress == _address) && _isBitwise) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -351,7 +308,7 @@ namespace MewtocolNet {
|
||||
} else if (regType == typeof(ushort)) {
|
||||
reg = new NRegister<ushort>(_address, _name);
|
||||
} else if (regType == typeof(int)) {
|
||||
reg = new NRegister<int>(_address, _name, _isBitwise);
|
||||
reg = new NRegister<int>(_address, _name, _isBitwise, _enumType);
|
||||
} else if (regType == typeof(uint)) {
|
||||
reg = new NRegister<uint>(_address, _name);
|
||||
} else if (regType == typeof(float)) {
|
||||
@@ -364,15 +321,19 @@ namespace MewtocolNet {
|
||||
reg = new BRegister(_address, RegisterType.R, _name);
|
||||
}
|
||||
|
||||
|
||||
if (reg == null) {
|
||||
throw new NotSupportedException($"The type {regType} is not allowed for Registers \n" +
|
||||
$"Allowed are: short, ushort, int, uint, float and string");
|
||||
} else {
|
||||
|
||||
reg.collectionType = _colType;
|
||||
|
||||
Registers.Add(_address, reg);
|
||||
if (Registers.Any(x => x.GetRegisterPLCName() == reg.GetRegisterPLCName()) && !_isBitwise) {
|
||||
throw new NotSupportedException($"Cannot add a register multiple times, " +
|
||||
$"make sure that all register attributes or AddRegister assignments have different adresses.");
|
||||
}
|
||||
|
||||
reg.collectionType = _colType;
|
||||
Registers.Add(reg);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -387,7 +348,7 @@ namespace MewtocolNet {
|
||||
/// <returns></returns>
|
||||
public Register GetRegister (string name) {
|
||||
|
||||
return Registers.FirstOrDefault(x => x.Value.Name == name).Value;
|
||||
return Registers.FirstOrDefault(x => x.Name == name);
|
||||
|
||||
}
|
||||
|
||||
@@ -398,8 +359,8 @@ namespace MewtocolNet {
|
||||
/// <returns>A casted register or the <code>default</code> value</returns>
|
||||
public T GetRegister<T> (string name) where T : Register {
|
||||
try {
|
||||
var reg = Registers.FirstOrDefault(x => x.Value.Name == name);
|
||||
return reg.Value as T;
|
||||
var reg = Registers.FirstOrDefault(x => x.Name == name);
|
||||
return reg as T;
|
||||
} catch (InvalidCastException) {
|
||||
return default(T);
|
||||
}
|
||||
@@ -414,7 +375,7 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
public List<Register> GetAllRegisters () {
|
||||
|
||||
return Registers.Values.ToList();
|
||||
return Registers;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ namespace MewtocolNet {
|
||||
var res = new Regex(@"\%([0-9]{2})\$RD.{8}(.*)...").Match(_onString);
|
||||
if(res.Success) {
|
||||
string val = res.Groups[2].Value;
|
||||
return val.GetStringFromAsciiHex().Trim();
|
||||
return val.GetStringFromAsciiHex()?.Trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -143,7 +143,7 @@ namespace MewtocolNet {
|
||||
|
||||
internal static string GetStringFromAsciiHex (this string input) {
|
||||
if (input.Length % 2 != 0)
|
||||
throw new ArgumentException("input not a hex string");
|
||||
return null;
|
||||
byte[] bytes = new byte[input.Length / 2];
|
||||
for (int i = 0; i < input.Length; i += 2) {
|
||||
String hex = input.Substring(i, 2);
|
||||
@@ -158,6 +158,8 @@ namespace MewtocolNet {
|
||||
}
|
||||
|
||||
internal static byte[] HexStringToByteArray(this string hex) {
|
||||
if (hex == null)
|
||||
return null;
|
||||
return Enumerable.Range(0, hex.Length)
|
||||
.Where(x => x % 2 == 0)
|
||||
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
|
||||
|
||||
@@ -12,13 +12,16 @@ using MewtocolNet.Logging;
|
||||
using System.Collections;
|
||||
using System.Diagnostics;
|
||||
using System.ComponentModel;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using MewtocolNet.Queue;
|
||||
|
||||
namespace MewtocolNet {
|
||||
|
||||
/// <summary>
|
||||
/// The PLC com interface class
|
||||
/// </summary>
|
||||
public partial class MewtocolInterface : INotifyPropertyChanged {
|
||||
public partial class MewtocolInterface : INotifyPropertyChanged, IDisposable {
|
||||
|
||||
/// <summary>
|
||||
/// Gets triggered when the PLC connection was established
|
||||
@@ -40,6 +43,15 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
|
||||
private int connectTimeout = 1000;
|
||||
/// <summary>
|
||||
/// The initial connection timeout in milliseconds
|
||||
/// </summary>
|
||||
public int ConnectTimeout {
|
||||
get { return connectTimeout; }
|
||||
set { connectTimeout = value; }
|
||||
}
|
||||
|
||||
private bool isConnected;
|
||||
/// <summary>
|
||||
/// The current connection state of the interface
|
||||
@@ -52,6 +64,16 @@ namespace MewtocolNet {
|
||||
}
|
||||
}
|
||||
|
||||
private bool disposed;
|
||||
/// <summary>
|
||||
/// True if the current interface was disposed
|
||||
/// </summary>
|
||||
public bool Disposed {
|
||||
get { return disposed; }
|
||||
private set { disposed = value; }
|
||||
}
|
||||
|
||||
|
||||
private PLCInfo plcInfo;
|
||||
/// <summary>
|
||||
/// Generic information about the connected PLC
|
||||
@@ -67,11 +89,12 @@ namespace MewtocolNet {
|
||||
/// <summary>
|
||||
/// The registered data registers of the PLC
|
||||
/// </summary>
|
||||
public Dictionary<int, Register> Registers { get; set; } = new Dictionary<int, Register>();
|
||||
public List<Register> Registers { get; set; } = new List<Register>();
|
||||
|
||||
private string ip;
|
||||
private int port;
|
||||
private int stationNumber;
|
||||
private int cycleTimeMs = 25;
|
||||
|
||||
/// <summary>
|
||||
/// The current IP of the PLC connection
|
||||
@@ -86,7 +109,6 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
public int StationNumber => stationNumber;
|
||||
|
||||
private int cycleTimeMs;
|
||||
/// <summary>
|
||||
/// The duration of the last message cycle
|
||||
/// </summary>
|
||||
@@ -98,8 +120,12 @@ namespace MewtocolNet {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal List<Task> PriorityTasks { get; set; } = new List<Task>();
|
||||
internal NetworkStream stream;
|
||||
internal TcpClient client;
|
||||
internal readonly SerialQueue queue = new SerialQueue();
|
||||
private int RecBufferSize = 128;
|
||||
internal int SendExceptionsInRow = 0;
|
||||
internal bool ImportantTaskRunning = false;
|
||||
|
||||
#region Initialization
|
||||
|
||||
@@ -129,7 +155,6 @@ namespace MewtocolNet {
|
||||
RegisterChanged += (o) => {
|
||||
|
||||
string address = $"{o.GetRegisterString()}{o.MemoryAdress}".PadRight(5, (char)32);
|
||||
;
|
||||
|
||||
Logger.Log($"{address} " +
|
||||
$"{(o.Name != null ? $"({o.Name}) " : "")}" +
|
||||
@@ -193,6 +218,35 @@ namespace MewtocolNet {
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the connections parameters of the PLC, only applyable when the connection is offline
|
||||
/// </summary>
|
||||
/// <param name="_ip">Ip adress</param>
|
||||
/// <param name="_port">Port number</param>
|
||||
/// <param name="_station">Station number</param>
|
||||
public void ChangeConnectionSettings (string _ip, int _port, int _station = 1) {
|
||||
|
||||
if (IsConnected)
|
||||
throw new Exception("Cannot change the connection settings while the PLC is connected");
|
||||
|
||||
ip = _ip;
|
||||
port = _port;
|
||||
stationNumber = _station;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the connection all cyclic polling
|
||||
/// </summary>
|
||||
public void Disconnect () {
|
||||
|
||||
if (!IsConnected)
|
||||
return;
|
||||
|
||||
OnMajorSocketExceptionWhileConnected();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attaches a poller to the interface that continously
|
||||
/// polls the registered data registers and writes the values to them
|
||||
@@ -207,6 +261,70 @@ namespace MewtocolNet {
|
||||
|
||||
#endregion
|
||||
|
||||
#region TCP connection state handling
|
||||
|
||||
private async Task ConnectTCP () {
|
||||
|
||||
if (!IPAddress.TryParse(ip, out var targetIP)) {
|
||||
throw new ArgumentException("The IP adress of the PLC was no valid format");
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
client = new TcpClient() {
|
||||
ReceiveBufferSize = RecBufferSize,
|
||||
NoDelay = false,
|
||||
ExclusiveAddressUse = true,
|
||||
};
|
||||
|
||||
var result = client.BeginConnect(targetIP, port, null, null);
|
||||
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(ConnectTimeout));
|
||||
|
||||
if(!success) {
|
||||
OnMajorSocketExceptionWhileConnecting();
|
||||
return;
|
||||
}
|
||||
|
||||
stream = client.GetStream();
|
||||
stream.ReadTimeout = 1000;
|
||||
|
||||
Console.WriteLine($"Connected {client.Connected}");
|
||||
await Task.CompletedTask;
|
||||
|
||||
} catch (SocketException) {
|
||||
|
||||
OnMajorSocketExceptionWhileConnecting();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void OnMajorSocketExceptionWhileConnecting () {
|
||||
|
||||
Logger.Log("The PLC connection timed out", LogLevel.Error, this);
|
||||
CycleTimeMs = 0;
|
||||
IsConnected = false;
|
||||
KillPoller();
|
||||
|
||||
}
|
||||
|
||||
private void OnMajorSocketExceptionWhileConnected () {
|
||||
|
||||
if (IsConnected) {
|
||||
|
||||
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
|
||||
CycleTimeMs = 0;
|
||||
IsConnected = false;
|
||||
Disconnected?.Invoke();
|
||||
KillPoller();
|
||||
client.Close();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Register Collection
|
||||
|
||||
/// <summary>
|
||||
@@ -264,6 +382,10 @@ namespace MewtocolNet {
|
||||
AddRegister<string>(collection.GetType(), cAttribute.MemoryArea, cAttribute.StringLength, _name: propName);
|
||||
}
|
||||
|
||||
if (prop.PropertyType.IsEnum) {
|
||||
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: propName, _enumType: prop.PropertyType);
|
||||
}
|
||||
|
||||
//read number as bit array
|
||||
if (prop.PropertyType == typeof(BitArray)) {
|
||||
|
||||
@@ -278,18 +400,13 @@ namespace MewtocolNet {
|
||||
//read number as bit array by invdividual properties
|
||||
if (prop.PropertyType == typeof(bool) && cAttribute.AssignedBitIndex != -1) {
|
||||
|
||||
if (cAttribute.BitCount == BitCount.B16) {
|
||||
AddRegister<short>(collection.GetType(), cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||
} else {
|
||||
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||
}
|
||||
//var bitwiseCount = Registers.Count(x => x.Value.isUsedBitwise);
|
||||
|
||||
//attach for bools to be read when bitregister
|
||||
//RegisterChanged += (reg) => {
|
||||
// if (reg.Name == propName) {
|
||||
// prop.SetValue()
|
||||
// }
|
||||
//};
|
||||
if (cAttribute.BitCount == BitCount.B16) {
|
||||
AddRegister<short>(collection.GetType(), cAttribute.MemoryArea, _name: $"Auto_Bitwise_DT{cAttribute.MemoryArea}", _isBitwise: true);
|
||||
} else {
|
||||
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: $"Auto_Bitwise_DDT{cAttribute.MemoryArea}", _isBitwise: true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -320,8 +437,11 @@ namespace MewtocolNet {
|
||||
|
||||
var bytes = BitConverter.GetBytes(reg16.Value);
|
||||
BitArray bitAr = new BitArray(bytes);
|
||||
prop.SetValue(collection, bitAr[bitIndex]);
|
||||
collection.TriggerPropertyChanged(prop.Name);
|
||||
|
||||
if (bitIndex < bitAr.Length && bitIndex >= 0) {
|
||||
prop.SetValue(collection, bitAr[bitIndex]);
|
||||
collection.TriggerPropertyChanged(prop.Name);
|
||||
}
|
||||
|
||||
} else if (bitWiseFound != null && reg is NRegister<int> reg32) {
|
||||
var casted = (RegisterAttribute)bitWiseFound;
|
||||
@@ -381,6 +501,14 @@ namespace MewtocolNet {
|
||||
foundToUpdate.SetValue(collection, ((NRegister<float>)reg).Value);
|
||||
}
|
||||
|
||||
if (foundToUpdate.PropertyType.IsEnum) {
|
||||
foundToUpdate.SetValue(collection, ((NRegister<int>)reg).Value);
|
||||
}
|
||||
|
||||
if (foundToUpdate.PropertyType == typeof(TimeSpan)) {
|
||||
foundToUpdate.SetValue(collection, ((NRegister<TimeSpan>)reg).Value);
|
||||
}
|
||||
|
||||
//setting back strings
|
||||
|
||||
if (foundToUpdate.PropertyType == typeof(string)) {
|
||||
@@ -523,7 +651,6 @@ namespace MewtocolNet {
|
||||
/// Calculates checksum and sends a command to the PLC then awaits results
|
||||
/// </summary>
|
||||
/// <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>
|
||||
public async Task<CommandResult> SendCommandAsync (string _msg) {
|
||||
|
||||
@@ -531,29 +658,42 @@ namespace MewtocolNet {
|
||||
_msg += "\r";
|
||||
|
||||
//send request
|
||||
try {
|
||||
|
||||
string response = null;
|
||||
var response = await queue.Enqueue(() => SendSingleBlock(_msg));
|
||||
|
||||
if (ContinousReaderRunning) {
|
||||
if (response == null) {
|
||||
return new CommandResult {
|
||||
Success = false,
|
||||
Error = "0000",
|
||||
ErrorDescription = "null result"
|
||||
};
|
||||
}
|
||||
|
||||
//if the poller is active then add all messages to a qeueue
|
||||
//error catching
|
||||
Regex errorcheck = new Regex(@"\%[0-9]{2}\!([0-9]{2})", RegexOptions.IgnoreCase);
|
||||
Match m = errorcheck.Match(response.ToString());
|
||||
if (m.Success) {
|
||||
string eCode = m.Groups[1].Value;
|
||||
string eDes = Links.LinkedData.ErrorCodes[Convert.ToInt32(eCode)];
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine($"Response is: {response}");
|
||||
Logger.Log($"Error on command {_msg.Replace("\r", "")} the PLC returned error code: {eCode}, {eDes}", LogLevel.Error);
|
||||
Console.ResetColor();
|
||||
return new CommandResult {
|
||||
Success = false,
|
||||
Error = eCode,
|
||||
ErrorDescription = eDes
|
||||
};
|
||||
}
|
||||
|
||||
var awaittask = SendSingleBlock(_msg);
|
||||
PriorityTasks.Add(awaittask);
|
||||
awaittask.Wait();
|
||||
return new CommandResult {
|
||||
Success = true,
|
||||
Error = "0000",
|
||||
Response = response.ToString()
|
||||
};
|
||||
|
||||
PriorityTasks.Remove(awaittask);
|
||||
response = awaittask.Result;
|
||||
|
||||
} else {
|
||||
|
||||
//poller not active let the user manage message timing
|
||||
|
||||
response = await SendSingleBlock(_msg);
|
||||
|
||||
}
|
||||
|
||||
if (response == null) {
|
||||
} catch {
|
||||
return new CommandResult {
|
||||
Success = false,
|
||||
Error = "0000",
|
||||
@@ -561,87 +701,85 @@ namespace MewtocolNet {
|
||||
};
|
||||
}
|
||||
|
||||
//error catching
|
||||
Regex errorcheck = new Regex(@"\%[0-9]{2}\!([0-9]{2})", RegexOptions.IgnoreCase);
|
||||
Match m = errorcheck.Match(response.ToString());
|
||||
if (m.Success) {
|
||||
string eCode = m.Groups[1].Value;
|
||||
string eDes = Links.LinkedData.ErrorCodes[Convert.ToInt32(eCode)];
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine($"Response is: {response}");
|
||||
Console.WriteLine($"Error on command {_msg.Replace("\r", "")} the PLC returned error code: {eCode}, {eDes}");
|
||||
Console.ResetColor();
|
||||
return new CommandResult {
|
||||
Success = false,
|
||||
Error = eCode,
|
||||
ErrorDescription = eDes
|
||||
};
|
||||
}
|
||||
|
||||
return new CommandResult {
|
||||
Success = true,
|
||||
Error = "0000",
|
||||
Response = response.ToString()
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
private async Task<string> SendSingleBlock (string _blockString) {
|
||||
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
|
||||
using (TcpClient client = new TcpClient() { ReceiveBufferSize = 64, NoDelay = true, ExclusiveAddressUse = true }) {
|
||||
|
||||
try {
|
||||
|
||||
await client.ConnectAsync(ip, port);
|
||||
|
||||
using (NetworkStream stream = client.GetStream()) {
|
||||
var message = _blockString.ToHexASCIIBytes();
|
||||
var messageAscii = BitConverter.ToString(message).Replace("-", " ");
|
||||
//send request
|
||||
using (var sendStream = new MemoryStream(message)) {
|
||||
await sendStream.CopyToAsync(stream);
|
||||
Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this);
|
||||
//log message sent
|
||||
ASCIIEncoding enc = new ASCIIEncoding();
|
||||
string characters = enc.GetString(message);
|
||||
}
|
||||
//await result
|
||||
StringBuilder response = new StringBuilder();
|
||||
byte[] responseBuffer = new byte[256];
|
||||
do {
|
||||
int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length);
|
||||
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
|
||||
}
|
||||
while (stream.DataAvailable);
|
||||
sw.Stop();
|
||||
var curCycle = (int)sw.ElapsedMilliseconds;
|
||||
if (Math.Abs(CycleTimeMs - curCycle) > 2) {
|
||||
CycleTimeMs = curCycle;
|
||||
}
|
||||
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {_blockString}", LogLevel.Critical, this);
|
||||
return response.ToString();
|
||||
}
|
||||
|
||||
} catch (Exception) {
|
||||
|
||||
if (IsConnected) {
|
||||
CycleTimeMs = 0;
|
||||
IsConnected = false;
|
||||
Disconnected?.Invoke();
|
||||
}
|
||||
|
||||
KillPoller();
|
||||
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
|
||||
if (client == null || !client.Connected ) {
|
||||
await ConnectTCP();
|
||||
if (!client.Connected)
|
||||
return null;
|
||||
}
|
||||
|
||||
var message = _blockString.ToHexASCIIBytes();
|
||||
|
||||
//send request
|
||||
using (var sendStream = new MemoryStream(message)) {
|
||||
await sendStream.CopyToAsync(stream);
|
||||
Logger.Log($"[--------------------------------]", LogLevel.Critical, this);
|
||||
Logger.Log($"--> OUT MSG: {_blockString}", LogLevel.Critical, this);
|
||||
}
|
||||
|
||||
//await result
|
||||
StringBuilder response = new StringBuilder();
|
||||
try {
|
||||
|
||||
byte[] responseBuffer = new byte[128 * 16];
|
||||
|
||||
bool endLineCode = false;
|
||||
bool startMsgCode = false;
|
||||
|
||||
while (!endLineCode && !startMsgCode) {
|
||||
|
||||
do {
|
||||
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));
|
||||
}
|
||||
while (stream.DataAvailable);
|
||||
|
||||
}
|
||||
|
||||
} catch (IOException) {
|
||||
Logger.Log($"Critical IO exception on receive", LogLevel.Critical, this);
|
||||
return null;
|
||||
} catch (SocketException) {
|
||||
OnMajorSocketExceptionWhileConnected();
|
||||
return null;
|
||||
}
|
||||
|
||||
if(!string.IsNullOrEmpty(response.ToString())) {
|
||||
Logger.Log($"<-- IN MSG: {response}", LogLevel.Critical, this);
|
||||
return response.ToString();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Disposing
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the current interface and clears all its members
|
||||
/// </summary>
|
||||
public void Dispose () {
|
||||
|
||||
if (Disposed) return;
|
||||
|
||||
Disconnect();
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
|
||||
Disposed = true;
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -660,4 +798,5 @@ namespace MewtocolNet {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -115,26 +115,40 @@ namespace MewtocolNet {
|
||||
/// <returns>A byte array or null of there was an error</returns>
|
||||
public async Task<byte[]> ReadByteRange (int start, int count) {
|
||||
|
||||
string startStr = start.ToString().PadLeft(5, '0');
|
||||
var byteList = new List<byte>();
|
||||
|
||||
var wordLength = count / 2;
|
||||
bool wasOdd = false;
|
||||
if (count % 2 != 0)
|
||||
wordLength++;
|
||||
|
||||
string endStr = (start + wordLength - 1).ToString().PadLeft(5, '0');
|
||||
|
||||
string requeststring = $"%{GetStationNumber()}#RDD{startStr}{endStr}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
//read blocks of max 4 words per msg
|
||||
for (int i = 0; i < wordLength; i+=8) {
|
||||
|
||||
if(result.Success && !string.IsNullOrEmpty(result.Response)) {
|
||||
int curWordStart = start + i;
|
||||
int curWordEnd = curWordStart + 7;
|
||||
|
||||
var bytes = result.Response.ParseDTByteString(wordLength * 4).HexStringToByteArray();
|
||||
string startStr = curWordStart.ToString().PadLeft(5, '0');
|
||||
string endStr = (curWordEnd).ToString().PadLeft(5, '0');
|
||||
|
||||
return bytes.BigToMixedEndian().Take(count).ToArray();
|
||||
string requeststring = $"%{GetStationNumber()}#RDD{startStr}{endStr}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
if (result.Success && !string.IsNullOrEmpty(result.Response)) {
|
||||
|
||||
var bytes = result.Response.ParseDTByteString(8 * 4).HexStringToByteArray();
|
||||
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
byteList.AddRange(bytes.BigToMixedEndian().Take(count).ToArray());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return null;
|
||||
return byteList.ToArray();
|
||||
|
||||
}
|
||||
|
||||
@@ -183,7 +197,7 @@ namespace MewtocolNet {
|
||||
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}#WC");
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WC");
|
||||
|
||||
}
|
||||
|
||||
@@ -196,7 +210,6 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of number (short, ushort, int, uint, float)</typeparam>
|
||||
/// <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>
|
||||
public async Task<NRegisterResult<T>> ReadNumRegister<T> (NRegister<T> _toRead) {
|
||||
|
||||
@@ -205,40 +218,47 @@ namespace MewtocolNet {
|
||||
string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolIdent()}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
if(!result.Success || string.IsNullOrEmpty(result.Response)) {
|
||||
return new NRegisterResult<T> {
|
||||
Result = result,
|
||||
Register = _toRead
|
||||
};
|
||||
var failedResult = new NRegisterResult<T> {
|
||||
Result = result,
|
||||
Register = _toRead
|
||||
};
|
||||
|
||||
if (!result.Success || string.IsNullOrEmpty(result.Response)) {
|
||||
return failedResult;
|
||||
}
|
||||
|
||||
if (numType == typeof(short)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
||||
if (resultBytes == null) return failedResult;
|
||||
var val = short.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(ushort)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
||||
if (resultBytes == null) return failedResult;
|
||||
var val = ushort.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(int)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||
if (resultBytes == null) return failedResult;
|
||||
var val = int.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(uint)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||
if (resultBytes == null) return failedResult;
|
||||
var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(float)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||
if (resultBytes == null) return failedResult;
|
||||
//convert to unsigned int first
|
||||
var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
|
||||
@@ -250,6 +270,7 @@ namespace MewtocolNet {
|
||||
} else if (numType == typeof(TimeSpan)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||
if (resultBytes == null) return failedResult;
|
||||
//convert to unsigned int first
|
||||
var vallong = long.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
var valMillis = vallong * 10;
|
||||
@@ -313,7 +334,7 @@ namespace MewtocolNet {
|
||||
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}#WD");
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD");
|
||||
|
||||
}
|
||||
|
||||
@@ -369,7 +390,7 @@ namespace MewtocolNet {
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}#WD");
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -19,8 +19,33 @@ namespace MewtocolNet.Registers {
|
||||
/// Defines a register containing a number
|
||||
/// </summary>
|
||||
/// <param name="_adress">Memory start adress max 99999</param>
|
||||
/// <param name="_format">The format in which the variable is stored</param>
|
||||
public NRegister(int _adress, string _name = null, bool isBitwise = false) {
|
||||
/// <param name="_name">Name of the register</param>
|
||||
public NRegister (int _adress, string _name = null) {
|
||||
|
||||
if (_adress > 99999)
|
||||
throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||
memoryAdress = _adress;
|
||||
name = _name;
|
||||
Type numType = typeof(T);
|
||||
if (numType == typeof(short)) {
|
||||
memoryLength = 0;
|
||||
} else if (numType == typeof(ushort)) {
|
||||
memoryLength = 0;
|
||||
} else if (numType == typeof(int)) {
|
||||
memoryLength = 1;
|
||||
} else if (numType == typeof(uint)) {
|
||||
memoryLength = 1;
|
||||
} else if (numType == typeof(float)) {
|
||||
memoryLength = 1;
|
||||
} else if (numType == typeof(TimeSpan)) {
|
||||
memoryLength = 1;
|
||||
} else {
|
||||
throw new NotSupportedException($"The type {numType} is not allowed for Number Registers");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal NRegister(int _adress, string _name = null, bool isBitwise = false, Type _enumType = null) {
|
||||
|
||||
if (_adress > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||
memoryAdress = _adress;
|
||||
@@ -43,6 +68,7 @@ namespace MewtocolNet.Registers {
|
||||
}
|
||||
|
||||
isUsedBitwise = isBitwise;
|
||||
enumType = _enumType;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace MewtocolNet.Registers {
|
||||
using System;
|
||||
|
||||
namespace MewtocolNet.Registers {
|
||||
/// <summary>
|
||||
/// Result for a read/write operation
|
||||
/// </summary>
|
||||
@@ -11,6 +13,19 @@
|
||||
string errmsg = Result.Success ? "" : $", Error [{Result.ErrorDescription}]";
|
||||
return $"Result [{Result.Success}], Register [{Register.ToString()}]{errmsg}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trys to get the value of there is one
|
||||
/// </summary>
|
||||
public bool TryGetValue (out T value) {
|
||||
if(Result.Success) {
|
||||
value = Register.Value;
|
||||
return true;
|
||||
}
|
||||
value = default(T);
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ namespace MewtocolNet.Registers {
|
||||
public string ContainerName => GetContainerName();
|
||||
|
||||
internal bool isUsedBitwise { get; set; }
|
||||
internal Type enumType { get; set; }
|
||||
|
||||
internal Register () {
|
||||
ValueChanged += (obj) => {
|
||||
@@ -110,6 +111,18 @@ namespace MewtocolNet.Registers {
|
||||
/// <returns></returns>
|
||||
public string GetValueString () {
|
||||
|
||||
if (enumType != null && this is NRegister<int> intEnumReg) {
|
||||
var dict = new Dictionary<int, string>();
|
||||
foreach (var name in Enum.GetNames(enumType)) {
|
||||
dict.Add((int)Enum.Parse(enumType, name), name);
|
||||
}
|
||||
|
||||
if(dict.ContainsKey(intEnumReg.Value)) {
|
||||
return $"{intEnumReg.Value} ({dict[intEnumReg.Value]})";
|
||||
} else {
|
||||
return $"{intEnumReg.Value} (Missing Enum)";
|
||||
}
|
||||
}
|
||||
if (this is NRegister<short> shortReg) {
|
||||
return $"{shortReg.Value}{(isUsedBitwise ? $" [{shortReg.GetBitwise().ToBitString()}]" : "")}";
|
||||
}
|
||||
@@ -132,8 +145,7 @@ namespace MewtocolNet.Registers {
|
||||
return boolReg.Value.ToString();
|
||||
}
|
||||
if (this is SRegister stringReg) {
|
||||
return stringReg.Value.ToString();
|
||||
|
||||
return stringReg.Value ?? "";
|
||||
}
|
||||
|
||||
return "Type of the register is not supported.";
|
||||
@@ -212,6 +224,10 @@ namespace MewtocolNet.Registers {
|
||||
|
||||
internal string GetRegisterPLCName () {
|
||||
|
||||
if (this is BRegister bReg && bReg.SpecialAddress != SpecialAddress.None) {
|
||||
return $"{GetRegisterString()}{bReg.SpecialAddress}";
|
||||
}
|
||||
|
||||
return $"{GetRegisterString()}{MemoryAdress}";
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<PackageId>MewtocolNet</PackageId>
|
||||
<Version>0.3.5</Version>
|
||||
<Version>0.5.0</Version>
|
||||
<Authors>Felix Weiss</Authors>
|
||||
<Company>Womed</Company>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
|
||||
71
MewtocolNet/Queue/SerialQueue.cs
Normal file
71
MewtocolNet/Queue/SerialQueue.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -28,7 +28,7 @@ This software was written by WOLF Medizintechnik GmbH (@WOmed/dev).
|
||||
|
||||
## .NET Support
|
||||
|
||||
This library was written in **netstandard2.0** and should by compatible with a lot of .NET environments.
|
||||
This library was written in **netstandard2.0** and should be compatible with a lot of .NET environments.
|
||||
|
||||
For a full list of supported .NET clrs see [this page](https://docs.microsoft.com/de-de/dotnet/standard/net-standard?tabs=net-standard-2-0#select-net-standard-version)
|
||||
|
||||
@@ -53,7 +53,7 @@ Where is the RS232/Serial support?
|
||||
|
||||
Install this package by using [Nuget](https://www.nuget.org/packages/MewtocolNet/) or reference
|
||||
```XML
|
||||
<PackageReference Include="MewtocolNet" Version="0.3.0" />
|
||||
<PackageReference Include="MewtocolNet" Version="0.5.0" />
|
||||
```
|
||||
in your dependencies.
|
||||
Alternatively use the dotnet CLI and run
|
||||
|
||||
Reference in New Issue
Block a user