mirror of
https://github.com/OpenLogics/MewtocolNet.git
synced 2025-12-06 11:11:23 +00:00
Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19159ed183 | ||
|
|
635823a66f | ||
|
|
c7a6559f97 | ||
|
|
88a453355c | ||
|
|
6f8f891760 | ||
|
|
8fb8d4989d | ||
|
|
45a9fa0520 | ||
|
|
772f8b89a4 | ||
|
|
6c7c368b55 | ||
|
|
38f0f9f523 | ||
|
|
c2aecb387a | ||
|
|
0e1f5cd12b | ||
|
|
f15d565029 | ||
|
|
0ac0198223 | ||
|
|
3c450eea97 | ||
|
|
fe2d2b9fb9 | ||
|
|
6c411d7318 | ||
|
|
cdae9a60fb | ||
|
|
b1c2cdb70e | ||
|
|
95bfcf94de | ||
|
|
0a93df287d | ||
|
|
18384ff964 | ||
|
|
e4ddad685a | ||
|
|
e953938a65 | ||
|
|
83f17a4eae | ||
|
|
4c719843f2 | ||
|
|
8f9e66d5d3 | ||
|
|
5cc222abcc | ||
|
|
14659ffaad | ||
|
|
ea106416ee | ||
|
|
0afa146712 | ||
|
|
325aa56d8a | ||
|
|
f4fad297fb | ||
|
|
664b32b92e | ||
|
|
a639a8eda8 | ||
|
|
23c2b0efb4 |
@@ -2,66 +2,206 @@
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using MewtocolNet;
|
using MewtocolNet;
|
||||||
using MewtocolNet.Logging;
|
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
|
var line = Console.ReadLine();
|
||||||
Logger.LogLevel = LogLevel.Verbose;
|
|
||||||
Logger.OnNewLogMessage((date, msg) => {
|
|
||||||
Console.WriteLine($"{date.ToString("HH:mm:ss")} {msg}");
|
|
||||||
});
|
|
||||||
|
|
||||||
//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
|
if(line == "1") {
|
||||||
interf.WithRegisterCollection(registers).WithPoller();
|
Scenario1();
|
||||||
|
|
||||||
await interf.ConnectAsync(
|
|
||||||
(plcinf) => {
|
|
||||||
|
|
||||||
//reading a value from the register collection
|
|
||||||
Console.WriteLine($"BitValue is: {registers.BitValue}");
|
|
||||||
|
|
||||||
//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);
|
|
||||||
|
|
||||||
//inverts the boolean register
|
|
||||||
await interf.SetRegisterAsync(nameof(registers.TestBool1), !registers.TestBool1);
|
|
||||||
|
|
||||||
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));
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
Console.ReadLine();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (line == "2") {
|
||||||
|
Scenario2();
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.ReadLine();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool isProgressReadout = false;
|
||||||
|
|
||||||
|
static void Scenario1 () {
|
||||||
|
|
||||||
|
Task.Factory.StartNew(async () => {
|
||||||
|
|
||||||
|
//attaching the logger
|
||||||
|
Logger.LogLevel = LogLevel.Critical;
|
||||||
|
Logger.OnNewLogMessage((date, msg) => {
|
||||||
|
Console.WriteLine($"{date.ToString("HH:mm:ss")} {msg}");
|
||||||
|
});
|
||||||
|
|
||||||
|
//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();
|
||||||
|
|
||||||
|
_ = Task.Factory.StartNew(async () => {
|
||||||
|
while (true) {
|
||||||
|
if (isProgressReadout) continue;
|
||||||
|
Console.Title = $"Polling Paused: {interf.PollingPaused}, " +
|
||||||
|
$"Speed UP: {interf.BytesPerSecondUpstream} B/s, " +
|
||||||
|
$"Speed DOWN: {interf.BytesPerSecondDownstream} B/s, " +
|
||||||
|
$"Poll delay: {interf.PollerDelayMs} ms, " +
|
||||||
|
$"Queued MSGs: {interf.QueuedMessages}";
|
||||||
|
await Task.Delay(1000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await interf.ConnectAsync((plcinf) => AfterConnect(interf, registers));
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
static void AfterConnect (MewtocolInterface interf, TestRegisters registers) {
|
||||||
|
|
||||||
|
//reading a value from the register collection
|
||||||
|
Console.WriteLine($"BitValue is: {registers.BitValue}");
|
||||||
|
Console.WriteLine($"TestEnum is: {registers.TestEnum}");
|
||||||
|
|
||||||
|
_ = Task.Factory.StartNew(async () => {
|
||||||
|
|
||||||
|
while(true) {
|
||||||
|
|
||||||
|
isProgressReadout = true;
|
||||||
|
|
||||||
|
await interf.ReadByteRange(1000, 2000, (p) => {
|
||||||
|
|
||||||
|
var totSteps = 10;
|
||||||
|
var cSteps = totSteps * p;
|
||||||
|
|
||||||
|
string progBar = "";
|
||||||
|
for (int i = 0; i < totSteps; i++) {
|
||||||
|
|
||||||
|
if(i < (int)cSteps) {
|
||||||
|
progBar += "⬛";
|
||||||
|
} else {
|
||||||
|
progBar += "⬜";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.Title = $"Prog read range: {(p * 100).ToString("N1")}% {progBar} Queued MSGs: {interf.QueuedMessages}";
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
isProgressReadout = false;
|
||||||
|
|
||||||
|
await Task.Delay(3000);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
//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));
|
||||||
|
|
||||||
|
//test pausing poller
|
||||||
|
|
||||||
|
bool pollerPaused = false;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
pollerPaused = !pollerPaused;
|
||||||
|
|
||||||
|
if (pollerPaused) {
|
||||||
|
Console.WriteLine("Pausing poller");
|
||||||
|
await interf.PausePollingAsync();
|
||||||
|
//interf.PollerDelayMs += 10;
|
||||||
|
Console.WriteLine("Paused poller");
|
||||||
|
} else {
|
||||||
|
interf.ResumePolling();
|
||||||
|
Console.WriteLine("Resumed poller");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
static void Scenario2 () {
|
||||||
|
|
||||||
|
Logger.LogLevel = LogLevel.Critical;
|
||||||
|
Logger.OnNewLogMessage((date, msg) => {
|
||||||
|
Console.WriteLine($"{date.ToString("HH:mm:ss")} {msg}");
|
||||||
|
});
|
||||||
|
|
||||||
|
Task.Factory.StartNew(async () => {
|
||||||
|
|
||||||
|
//automatic endpoint
|
||||||
|
using (var interf = new MewtocolInterface("10.237.191.3")) {
|
||||||
|
|
||||||
|
await interf.ConnectAsync();
|
||||||
|
|
||||||
|
if (interf.IsConnected) {
|
||||||
|
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
interf.Disconnect();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//manual endpoint
|
||||||
|
using (var interf = new MewtocolInterface("10.237.191.3")) {
|
||||||
|
|
||||||
|
interf.HostEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("10.237.191.77"), 0);
|
||||||
|
|
||||||
|
await interf.ConnectAsync();
|
||||||
|
|
||||||
|
if(interf.IsConnected) {
|
||||||
|
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
interf.Disconnect();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,19 +7,22 @@ namespace Examples {
|
|||||||
public class TestRegisters : RegisterCollectionBase {
|
public class TestRegisters : RegisterCollectionBase {
|
||||||
|
|
||||||
//corresponds to a R100 boolean register in the PLC
|
//corresponds to a R100 boolean register in the PLC
|
||||||
[Register(100, RegisterType.R)]
|
[Register(1000, RegisterType.R)]
|
||||||
public bool TestBool1 { get; private set; }
|
public bool TestBool1 { get; private set; }
|
||||||
|
|
||||||
|
[Register(1000)]
|
||||||
|
public int TestDuplicate { get; private set; }
|
||||||
|
|
||||||
//corresponds to a XD input of the PLC
|
//corresponds to a XD input of the PLC
|
||||||
[Register(RegisterType.X, SpecialAddress.D)]
|
[Register(RegisterType.X, SpecialAddress.D)]
|
||||||
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
|
||||||
@@ -42,11 +45,31 @@ namespace Examples {
|
|||||||
[Register(1204, 9, BitCount.B16)]
|
[Register(1204, 9, BitCount.B16)]
|
||||||
public bool BitValue { get; private set; }
|
public bool BitValue { get; private set; }
|
||||||
|
|
||||||
|
[Register(1204, 5, BitCount.B16)]
|
||||||
|
public bool FillTest { get; private set; }
|
||||||
|
|
||||||
//corresponds to a DT7012 - DT7013 as a 32bit time value that gets parsed as a timespan (TIME)
|
//corresponds to a DT7012 - DT7013 as a 32bit time value that gets parsed as a timespan (TIME)
|
||||||
//the smallest value to communicate to the PLC is 10ms
|
//the smallest value to communicate to the PLC is 10ms
|
||||||
[Register(7012)]
|
[Register(7012)]
|
||||||
public TimeSpan TestTime { get; private set; }
|
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; }
|
||||||
|
|
||||||
|
[Register(100)]
|
||||||
|
public TimeSpan TsTest2 { get; private set; }
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,28 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace MewtocolNet.Registers {
|
namespace MewtocolNet.Registers {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains information about the plc and its cpu
|
||||||
|
/// </summary>
|
||||||
public partial class CpuInfo {
|
public partial class CpuInfo {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The cpu type of the plc
|
||||||
|
/// </summary>
|
||||||
public CpuType Cputype { get; set; }
|
public CpuType Cputype { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Program capacity in 1K steps
|
||||||
|
/// </summary>
|
||||||
public int ProgramCapacity { get; set; }
|
public int ProgramCapacity { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Version of the cpu
|
||||||
|
/// </summary>
|
||||||
public string CpuVersion { get; set; }
|
public string CpuVersion { get; set; }
|
||||||
|
|
||||||
|
internal static CpuInfo BuildFromHexString (string _cpuType, string _cpuVersion, string _progCapacity) {
|
||||||
public static CpuInfo BuildFromHexString (string _cpuType, string _cpuVersion, string _progCapacity) {
|
|
||||||
|
|
||||||
CpuInfo retInf = new CpuInfo();
|
CpuInfo retInf = new CpuInfo();
|
||||||
|
|
||||||
@@ -47,8 +61,7 @@ namespace MewtocolNet.Registers {
|
|||||||
return retInf;
|
return retInf;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -14,17 +14,61 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public partial class MewtocolInterface {
|
public partial class MewtocolInterface {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True if the auto poller is currently paused
|
||||||
|
/// </summary>
|
||||||
|
public bool PollingPaused => pollerIsPaused;
|
||||||
|
|
||||||
internal event Action PolledCycle;
|
internal event Action PolledCycle;
|
||||||
internal CancellationTokenSource cTokenAutoUpdater;
|
|
||||||
internal bool ContinousReaderRunning;
|
internal volatile bool pollerTaskRunning;
|
||||||
|
internal volatile bool pollerTaskStopped;
|
||||||
|
internal volatile bool pollerIsPaused;
|
||||||
|
|
||||||
internal bool usePoller = false;
|
internal bool usePoller = false;
|
||||||
|
|
||||||
#region Register Polling
|
#region Register Polling
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Kills the poller completely
|
||||||
|
/// </summary>
|
||||||
internal void KillPoller () {
|
internal void KillPoller () {
|
||||||
|
|
||||||
ContinousReaderRunning = false;
|
pollerTaskRunning = false;
|
||||||
cTokenAutoUpdater?.Cancel();
|
pollerTaskStopped = true;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pauses the polling and waits for the last message to be sent
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task PausePollingAsync () {
|
||||||
|
|
||||||
|
if (!pollerTaskRunning)
|
||||||
|
return;
|
||||||
|
|
||||||
|
pollerTaskRunning = false;
|
||||||
|
|
||||||
|
while (!pollerIsPaused) {
|
||||||
|
|
||||||
|
if (pollerIsPaused)
|
||||||
|
break;
|
||||||
|
|
||||||
|
await Task.Delay(10);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
pollerTaskRunning = false;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resumes the polling
|
||||||
|
/// </summary>
|
||||||
|
public void ResumePolling () {
|
||||||
|
|
||||||
|
pollerTaskRunning = true;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,140 +77,108 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal void AttachPoller () {
|
internal void AttachPoller () {
|
||||||
|
|
||||||
if (ContinousReaderRunning) return;
|
if (pollerTaskRunning)
|
||||||
|
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 iteration = 0;
|
||||||
|
|
||||||
Task.Factory.StartNew(async () => {
|
pollerTaskStopped = false;
|
||||||
|
pollerTaskRunning = true;
|
||||||
|
pollerIsPaused = false;
|
||||||
|
|
||||||
var plcinf = await GetPLCInfoAsync();
|
while (!pollerTaskStopped) {
|
||||||
if (plcinf == null) {
|
|
||||||
Logger.Log("PLC not reachable, stopping logger", LogLevel.Info, this);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
PolledCycle += MewtocolInterface_PolledCycle;
|
while (pollerTaskRunning) {
|
||||||
void MewtocolInterface_PolledCycle () {
|
|
||||||
|
|
||||||
StringBuilder stringBuilder = new StringBuilder();
|
if (iteration >= Registers.Count + 1) {
|
||||||
foreach (var reg in GetAllRegisters()) {
|
iteration = 0;
|
||||||
string address = $"{reg.GetRegisterString()}{reg.GetStartingMemoryArea()}".PadRight(8, (char)32);
|
//invoke cycle polled event
|
||||||
stringBuilder.AppendLine($"{address}{(reg.Name != null ? $" ({reg.Name})" : "")}: {reg.GetValueString()}");
|
InvokePolledCycleDone();
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
Logger.Log($"Registers loaded are: \n" +
|
if (iteration >= Registers.Count) {
|
||||||
$"--------------------\n" +
|
await GetPLCInfoAsync();
|
||||||
$"{stringBuilder.ToString()}" +
|
iteration++;
|
||||||
$"--------------------",
|
continue;
|
||||||
LogLevel.Verbose, this);
|
|
||||||
|
|
||||||
Logger.Log("Logger did its first cycle successfully", LogLevel.Info, this);
|
|
||||||
|
|
||||||
PolledCycle -= MewtocolInterface_PolledCycle;
|
|
||||||
}
|
|
||||||
|
|
||||||
ContinousReaderRunning = true;
|
|
||||||
|
|
||||||
while (ContinousReaderRunning) {
|
|
||||||
|
|
||||||
//do priority tasks first
|
|
||||||
if (PriorityTasks.Count > 0) {
|
|
||||||
|
|
||||||
await PriorityTasks.FirstOrDefault(x => !x.IsCompleted);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var registerPair in Registers) {
|
var reg = Registers[iteration];
|
||||||
|
|
||||||
var reg = registerPair.Value;
|
if (reg is NRegister<short> shortReg) {
|
||||||
|
var lastVal = shortReg.Value;
|
||||||
if (reg is NRegister<short> shortReg) {
|
var readout = (await ReadNumRegister(shortReg)).Register.Value;
|
||||||
var lastVal = shortReg.Value;
|
if (lastVal != readout) {
|
||||||
var readout = (await ReadNumRegister(shortReg)).Register.Value;
|
InvokeRegisterChanged(shortReg);
|
||||||
if (lastVal != readout) {
|
|
||||||
shortReg.LastValue = readout;
|
|
||||||
InvokeRegisterChanged(shortReg);
|
|
||||||
shortReg.TriggerNotifyChange();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (reg is NRegister<ushort> ushortReg) {
|
}
|
||||||
var lastVal = ushortReg.Value;
|
if (reg is NRegister<ushort> ushortReg) {
|
||||||
var readout = (await ReadNumRegister(ushortReg)).Register.Value;
|
var lastVal = ushortReg.Value;
|
||||||
if (lastVal != readout) {
|
var readout = (await ReadNumRegister(ushortReg)).Register.Value;
|
||||||
ushortReg.LastValue = readout;
|
if (lastVal != readout) {
|
||||||
InvokeRegisterChanged(ushortReg);
|
InvokeRegisterChanged(ushortReg);
|
||||||
ushortReg.TriggerNotifyChange();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (reg is NRegister<int> intReg) {
|
}
|
||||||
var lastVal = intReg.Value;
|
if (reg is NRegister<int> intReg) {
|
||||||
var readout = (await ReadNumRegister(intReg)).Register.Value;
|
var lastVal = intReg.Value;
|
||||||
if (lastVal != readout) {
|
var readout = (await ReadNumRegister(intReg)).Register.Value;
|
||||||
intReg.LastValue = readout;
|
if (lastVal != readout) {
|
||||||
InvokeRegisterChanged(intReg);
|
InvokeRegisterChanged(intReg);
|
||||||
intReg.TriggerNotifyChange();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (reg is NRegister<uint> uintReg) {
|
}
|
||||||
var lastVal = uintReg.Value;
|
if (reg is NRegister<uint> uintReg) {
|
||||||
var readout = (await ReadNumRegister(uintReg)).Register.Value;
|
var lastVal = uintReg.Value;
|
||||||
if (lastVal != readout) {
|
var readout = (await ReadNumRegister(uintReg)).Register.Value;
|
||||||
uintReg.LastValue = readout;
|
if (lastVal != readout) {
|
||||||
InvokeRegisterChanged(uintReg);
|
InvokeRegisterChanged(uintReg);
|
||||||
uintReg.TriggerNotifyChange();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (reg is NRegister<float> floatReg) {
|
}
|
||||||
var lastVal = floatReg.Value;
|
if (reg is NRegister<float> floatReg) {
|
||||||
var readout = (await ReadNumRegister(floatReg)).Register.Value;
|
var lastVal = floatReg.Value;
|
||||||
if (lastVal != readout) {
|
var readout = (await ReadNumRegister(floatReg)).Register.Value;
|
||||||
floatReg.LastValue = readout;
|
if (lastVal != readout) {
|
||||||
InvokeRegisterChanged(floatReg);
|
InvokeRegisterChanged(floatReg);
|
||||||
floatReg.TriggerNotifyChange();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (reg is NRegister<TimeSpan> tsReg) {
|
}
|
||||||
var lastVal = tsReg.Value;
|
if (reg is NRegister<TimeSpan> tsReg) {
|
||||||
var readout = (await ReadNumRegister(tsReg)).Register.Value;
|
var lastVal = tsReg.Value;
|
||||||
if (lastVal != readout) {
|
var readout = (await ReadNumRegister(tsReg)).Register.Value;
|
||||||
tsReg.LastValue = readout;
|
if (lastVal != readout) {
|
||||||
InvokeRegisterChanged(tsReg);
|
InvokeRegisterChanged(tsReg);
|
||||||
tsReg.TriggerNotifyChange();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (reg is BRegister boolReg) {
|
}
|
||||||
var lastVal = boolReg.Value;
|
if (reg is BRegister boolReg) {
|
||||||
var readout = (await ReadBoolRegister(boolReg)).Register.Value;
|
var lastVal = boolReg.Value;
|
||||||
if (lastVal != readout) {
|
var readout = (await ReadBoolRegister(boolReg)).Register.Value;
|
||||||
boolReg.LastValue = readout;
|
if (lastVal != readout) {
|
||||||
InvokeRegisterChanged(boolReg);
|
InvokeRegisterChanged(boolReg);
|
||||||
boolReg.TriggerNotifyChange();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (reg is SRegister stringReg) {
|
}
|
||||||
var lastVal = stringReg.Value;
|
if (reg is SRegister stringReg) {
|
||||||
var readout = (await ReadStringRegister(stringReg)).Register.Value;
|
var lastVal = stringReg.Value;
|
||||||
if (lastVal != readout) {
|
var readout = (await ReadStringRegister(stringReg)).Register.Value;
|
||||||
InvokeRegisterChanged(stringReg);
|
if (lastVal != readout) {
|
||||||
stringReg.TriggerNotifyChange();
|
InvokeRegisterChanged(stringReg);
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//invoke cycle polled event
|
iteration++;
|
||||||
InvokePolledCycleDone();
|
|
||||||
|
await Task.Delay(pollerDelayMs);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}, cTokenAutoUpdater.Token);
|
pollerIsPaused = !pollerTaskRunning;
|
||||||
|
|
||||||
} catch (TaskCanceledException) { }
|
}
|
||||||
|
|
||||||
|
pollerIsPaused = false;
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,30 +203,60 @@ namespace MewtocolNet {
|
|||||||
/// <param name="_name">A naming definition for QOL, doesn't effect PLC and is optional</param>
|
/// <param name="_name">A naming definition for QOL, doesn't effect PLC and is optional</param>
|
||||||
public void AddRegister (int _address, RegisterType _type, string _name = null) {
|
public void AddRegister (int _address, RegisterType _type, string _name = null) {
|
||||||
|
|
||||||
|
Register toAdd = null;
|
||||||
|
|
||||||
//as number registers
|
//as number registers
|
||||||
if (_type == RegisterType.DT_short) {
|
if (_type == RegisterType.DT_short) {
|
||||||
Registers.Add(_address, new NRegister<short>(_address, _name));
|
toAdd = new NRegister<short>(_address, _name);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (_type == RegisterType.DT_ushort) {
|
if (_type == RegisterType.DT_ushort) {
|
||||||
Registers.Add(_address, new NRegister<ushort>(_address, _name));
|
toAdd = new NRegister<ushort>(_address, _name);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (_type == RegisterType.DDT_int) {
|
if (_type == RegisterType.DDT_int) {
|
||||||
Registers.Add(_address, new NRegister<int>(_address, _name));
|
toAdd = new NRegister<int>(_address, _name);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (_type == RegisterType.DDT_uint) {
|
if (_type == RegisterType.DDT_uint) {
|
||||||
Registers.Add(_address, new NRegister<uint>(_address, _name));
|
toAdd = new NRegister<uint>(_address, _name);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (_type == RegisterType.DDT_float) {
|
if (_type == RegisterType.DDT_float) {
|
||||||
Registers.Add(_address, new NRegister<float>(_address, _name));
|
toAdd = new NRegister<float>(_address, _name);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//as bool registers
|
if(toAdd == null) {
|
||||||
Registers.Add(_address, new BRegister(_address, _type, _name));
|
toAdd = new BRegister(_address, _type, _name);
|
||||||
|
}
|
||||||
|
|
||||||
|
Registers.Add(toAdd);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void AddRegister (Type _colType, int _address, RegisterType _type, string _name = null) {
|
||||||
|
|
||||||
|
Register toAdd = null;
|
||||||
|
|
||||||
|
//as number registers
|
||||||
|
if (_type == RegisterType.DT_short) {
|
||||||
|
toAdd = new NRegister<short>(_address, _name);
|
||||||
|
}
|
||||||
|
if (_type == RegisterType.DT_ushort) {
|
||||||
|
toAdd = new NRegister<ushort>(_address, _name);
|
||||||
|
}
|
||||||
|
if (_type == RegisterType.DDT_int) {
|
||||||
|
toAdd = new NRegister<int>(_address, _name);
|
||||||
|
}
|
||||||
|
if (_type == RegisterType.DDT_uint) {
|
||||||
|
toAdd = new NRegister<uint>(_address, _name);
|
||||||
|
}
|
||||||
|
if (_type == RegisterType.DDT_float) {
|
||||||
|
toAdd = new NRegister<float>(_address, _name);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toAdd == null) {
|
||||||
|
toAdd = new BRegister(_address, _type, _name);
|
||||||
|
}
|
||||||
|
|
||||||
|
toAdd.collectionType = _colType;
|
||||||
|
Registers.Add(toAdd);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,7 +277,18 @@ namespace MewtocolNet {
|
|||||||
public void AddRegister (SpecialAddress _spAddress, RegisterType _type, string _name = null) {
|
public void AddRegister (SpecialAddress _spAddress, RegisterType _type, string _name = null) {
|
||||||
|
|
||||||
//as bool registers
|
//as bool registers
|
||||||
Registers.Add((int)_spAddress, new BRegister(_spAddress, _type, _name));
|
Registers.Add(new BRegister(_spAddress, _type, _name));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void AddRegister (Type _colType, SpecialAddress _spAddress, RegisterType _type, string _name = null) {
|
||||||
|
|
||||||
|
var reg = new BRegister(_spAddress, _type, _name);
|
||||||
|
|
||||||
|
reg.collectionType = _colType;
|
||||||
|
|
||||||
|
//as bool registers
|
||||||
|
Registers.Add(reg);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,7 +309,7 @@ namespace MewtocolNet {
|
|||||||
/// <param name="_name">A naming definition for QOL, doesn't effect PLC and is optional</param>
|
/// <param name="_name">A naming definition for QOL, doesn't effect PLC and is optional</param>
|
||||||
/// <param name="_address">The address of the register in the PLCs memory</param>
|
/// <param name="_address">The address of the register in the PLCs memory</param>
|
||||||
/// <param name="_length">The length of the string (Can be ignored for other types)</param>
|
/// <param name="_length">The length of the string (Can be ignored for other types)</param>
|
||||||
public void AddRegister<T>(int _address, int _length = 1, string _name = null, bool _isBitwise = false) {
|
public void AddRegister<T>(int _address, int _length = 1, string _name = null) {
|
||||||
|
|
||||||
Type regType = typeof(T);
|
Type regType = typeof(T);
|
||||||
|
|
||||||
@@ -264,34 +317,84 @@ namespace MewtocolNet {
|
|||||||
throw new NotSupportedException($"_lenght parameter only allowed for register of type string");
|
throw new NotSupportedException($"_lenght parameter only allowed for register of type string");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Registers.Any(x => x.Key == _address)) {
|
Register toAdd;
|
||||||
|
|
||||||
throw new NotSupportedException($"Cannot add a register multiple times, " +
|
|
||||||
$"make sure that all register attributes or AddRegister assignments have different adresses.");
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if (regType == typeof(short)) {
|
if (regType == typeof(short)) {
|
||||||
Registers.Add(_address, new NRegister<short>(_address, _name, _isBitwise));
|
toAdd = new NRegister<short>(_address, _name);
|
||||||
} else if (regType == typeof(ushort)) {
|
} else if (regType == typeof(ushort)) {
|
||||||
Registers.Add(_address, new NRegister<ushort>(_address, _name));
|
toAdd = new NRegister<ushort>(_address, _name);
|
||||||
} else if (regType == typeof(int)) {
|
} else if (regType == typeof(int)) {
|
||||||
Registers.Add(_address, new NRegister<int>(_address, _name, _isBitwise));
|
toAdd = new NRegister<int>(_address, _name);
|
||||||
} else if (regType == typeof(uint)) {
|
} else if (regType == typeof(uint)) {
|
||||||
Registers.Add(_address, new NRegister<uint>(_address, _name));
|
toAdd = new NRegister<uint>(_address, _name);
|
||||||
} else if (regType == typeof(float)) {
|
} else if (regType == typeof(float)) {
|
||||||
Registers.Add(_address, new NRegister<float>(_address, _name));
|
toAdd = new NRegister<float>(_address, _name);
|
||||||
} else if (regType == typeof(string)) {
|
} else if (regType == typeof(string)) {
|
||||||
Registers.Add(_address, new SRegister(_address, _length, _name));
|
toAdd = new SRegister(_address, _length, _name);
|
||||||
} else if (regType == typeof(TimeSpan)) {
|
} else if (regType == typeof(TimeSpan)) {
|
||||||
Registers.Add(_address, new NRegister<TimeSpan>(_address, _name));
|
toAdd = new NRegister<TimeSpan>(_address, _name);
|
||||||
} else if (regType == typeof(bool)) {
|
} else if (regType == typeof(bool)) {
|
||||||
Registers.Add(_address, new BRegister(_address, RegisterType.R, _name));
|
toAdd = new BRegister(_address, RegisterType.R, _name);
|
||||||
} else {
|
} else {
|
||||||
throw new NotSupportedException($"The type {regType} is not allowed for Registers \n" +
|
throw new NotSupportedException($"The type {regType} is not allowed for Registers \n" +
|
||||||
$"Allowed are: short, ushort, int, uint, float and string");
|
$"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, Type _enumType = null) {
|
||||||
|
|
||||||
|
Type regType = typeof(T);
|
||||||
|
|
||||||
|
if (regType != typeof(string) && _length != 1) {
|
||||||
|
throw new NotSupportedException($"_lenght parameter only allowed for register of type string");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Registers.Any(x => x.MemoryAdress == _address) && _isBitwise) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Register reg = null;
|
||||||
|
|
||||||
|
if (regType == typeof(short)) {
|
||||||
|
reg = new NRegister<short>(_address, _name, _isBitwise);
|
||||||
|
} else if (regType == typeof(ushort)) {
|
||||||
|
reg = new NRegister<ushort>(_address, _name);
|
||||||
|
} else if (regType == typeof(int)) {
|
||||||
|
reg = new NRegister<int>(_address, _name, _isBitwise, _enumType);
|
||||||
|
} else if (regType == typeof(uint)) {
|
||||||
|
reg = new NRegister<uint>(_address, _name);
|
||||||
|
} else if (regType == typeof(float)) {
|
||||||
|
reg = new NRegister<float>(_address, _name);
|
||||||
|
} else if (regType == typeof(string)) {
|
||||||
|
reg = new SRegister(_address, _length, _name);
|
||||||
|
} else if (regType == typeof(TimeSpan)) {
|
||||||
|
reg = new NRegister<TimeSpan>(_address, _name);
|
||||||
|
} else if (regType == typeof(bool)) {
|
||||||
|
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 {
|
||||||
|
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -304,7 +407,7 @@ namespace MewtocolNet {
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public Register GetRegister (string name) {
|
public Register GetRegister (string name) {
|
||||||
|
|
||||||
return Registers.FirstOrDefault(x => x.Value.Name == name).Value;
|
return Registers.FirstOrDefault(x => x.Name == name);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,8 +418,8 @@ namespace MewtocolNet {
|
|||||||
/// <returns>A casted register or the <code>default</code> value</returns>
|
/// <returns>A casted register or the <code>default</code> value</returns>
|
||||||
public T GetRegister<T> (string name) where T : Register {
|
public T GetRegister<T> (string name) where T : Register {
|
||||||
try {
|
try {
|
||||||
var reg = Registers.FirstOrDefault(x => x.Value.Name == name);
|
var reg = Registers.FirstOrDefault(x => x.Name == name);
|
||||||
return reg.Value as T;
|
return reg as T;
|
||||||
} catch (InvalidCastException) {
|
} catch (InvalidCastException) {
|
||||||
return default(T);
|
return default(T);
|
||||||
}
|
}
|
||||||
@@ -331,7 +434,7 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public List<Register> GetAllRegisters () {
|
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);
|
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))
|
||||||
|
|||||||
@@ -11,42 +11,118 @@ using MewtocolNet.RegisterAttributes;
|
|||||||
using MewtocolNet.Logging;
|
using MewtocolNet.Logging;
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Net;
|
||||||
|
using System.Threading;
|
||||||
|
using MewtocolNet.Queue;
|
||||||
|
|
||||||
namespace MewtocolNet {
|
namespace MewtocolNet {
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The PLC com interface class
|
/// The PLC com interface class
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public partial class MewtocolInterface {
|
public partial class MewtocolInterface : INotifyPropertyChanged, IDisposable {
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets triggered when the PLC connection was established
|
/// Gets triggered when the PLC connection was established
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public event Action<PLCInfo> Connected;
|
public event Action<PLCInfo> Connected;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets triggered when the PLC connection was closed or lost
|
||||||
|
/// </summary>
|
||||||
|
public event Action Disconnected;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets triggered when a registered data register changes its value
|
/// Gets triggered when a registered data register changes its value
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public event Action<Register> RegisterChanged;
|
public event Action<Register> RegisterChanged;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets triggered when a property of the interface changes
|
||||||
|
/// </summary>
|
||||||
|
public event PropertyChangedEventHandler PropertyChanged;
|
||||||
|
|
||||||
|
private int connectTimeout = 3000;
|
||||||
|
/// <summary>
|
||||||
|
/// The initial connection timeout in milliseconds
|
||||||
|
/// </summary>
|
||||||
|
public int ConnectTimeout {
|
||||||
|
get { return connectTimeout; }
|
||||||
|
set { connectTimeout = value; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private volatile int pollerDelayMs = 0;
|
||||||
|
/// <summary>
|
||||||
|
/// Delay for each poller cycle in milliseconds, default = 0
|
||||||
|
/// </summary>
|
||||||
|
public int PollerDelayMs {
|
||||||
|
get => pollerDelayMs;
|
||||||
|
set {
|
||||||
|
pollerDelayMs = value;
|
||||||
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PollerDelayMs)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private volatile int queuedMessages;
|
||||||
|
/// <summary>
|
||||||
|
/// Currently queued Messages
|
||||||
|
/// </summary>
|
||||||
|
public int QueuedMessages {
|
||||||
|
get => queuedMessages;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The host ip endpoint, leave it null to use an automatic interface
|
||||||
|
/// </summary>
|
||||||
|
public IPEndPoint HostEndpoint { get; set; }
|
||||||
|
|
||||||
|
private bool isConnected;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The current connection state of the interface
|
/// The current connection state of the interface
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsConnected { get; private set; }
|
public bool IsConnected {
|
||||||
|
get => isConnected;
|
||||||
|
private set {
|
||||||
|
isConnected = value;
|
||||||
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnected)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
/// <summary>
|
||||||
/// Generic information about the connected PLC
|
/// Generic information about the connected PLC
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public PLCInfo PlcInfo { get; private set; }
|
public PLCInfo PlcInfo {
|
||||||
|
get => plcInfo;
|
||||||
|
private set {
|
||||||
|
plcInfo = value;
|
||||||
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PlcInfo)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The registered data registers of the PLC
|
/// The registered data registers of the PLC
|
||||||
/// </summary>
|
/// </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 string ip;
|
||||||
private int port;
|
private int port;
|
||||||
private int stationNumber;
|
private int stationNumber;
|
||||||
|
private int cycleTimeMs = 25;
|
||||||
|
|
||||||
|
private int bytesTotalCountedUpstream = 0;
|
||||||
|
private int bytesTotalCountedDownstream = 0;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The current IP of the PLC connection
|
/// The current IP of the PLC connection
|
||||||
@@ -61,7 +137,50 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public int StationNumber => stationNumber;
|
public int StationNumber => stationNumber;
|
||||||
|
|
||||||
internal List<Task> PriorityTasks { get; set; } = new List<Task>();
|
/// <summary>
|
||||||
|
/// The duration of the last message cycle
|
||||||
|
/// </summary>
|
||||||
|
public int CycleTimeMs {
|
||||||
|
get { return cycleTimeMs; }
|
||||||
|
private set {
|
||||||
|
cycleTimeMs = value;
|
||||||
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CycleTimeMs)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int bytesPerSecondUpstream = 0;
|
||||||
|
/// <summary>
|
||||||
|
/// The current transmission speed in bytes per second
|
||||||
|
/// </summary>
|
||||||
|
public int BytesPerSecondUpstream {
|
||||||
|
get { return bytesPerSecondUpstream; }
|
||||||
|
private set {
|
||||||
|
bytesPerSecondUpstream = value;
|
||||||
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BytesPerSecondUpstream)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int bytesPerSecondDownstream = 0;
|
||||||
|
/// <summary>
|
||||||
|
/// The current transmission speed in bytes per second
|
||||||
|
/// </summary>
|
||||||
|
public int BytesPerSecondDownstream {
|
||||||
|
get { return bytesPerSecondDownstream; }
|
||||||
|
private set {
|
||||||
|
bytesPerSecondDownstream = value;
|
||||||
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BytesPerSecondDownstream)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal NetworkStream stream;
|
||||||
|
internal TcpClient client;
|
||||||
|
internal readonly SerialQueue queue = new SerialQueue();
|
||||||
|
private int RecBufferSize = 128;
|
||||||
|
internal int SendExceptionsInRow = 0;
|
||||||
|
internal bool ImportantTaskRunning = false;
|
||||||
|
|
||||||
|
private Stopwatch speedStopwatchUpstr;
|
||||||
|
private Stopwatch speedStopwatchDownstr;
|
||||||
|
|
||||||
#region Initialization
|
#region Initialization
|
||||||
|
|
||||||
@@ -72,10 +191,10 @@ namespace MewtocolNet {
|
|||||||
/// <param name="_port">Port of the PLC</param>
|
/// <param name="_port">Port of the PLC</param>
|
||||||
/// <param name="_station">Station Number of the PLC</param>
|
/// <param name="_station">Station Number of the PLC</param>
|
||||||
public MewtocolInterface (string _ip, int _port = 9094, int _station = 1) {
|
public MewtocolInterface (string _ip, int _port = 9094, int _station = 1) {
|
||||||
|
|
||||||
ip = _ip;
|
ip = _ip;
|
||||||
port = _port;
|
port = _port;
|
||||||
stationNumber = _station;
|
stationNumber = _station;
|
||||||
|
|
||||||
Connected += MewtocolInterface_Connected;
|
Connected += MewtocolInterface_Connected;
|
||||||
|
|
||||||
@@ -90,7 +209,7 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
RegisterChanged += (o) => {
|
RegisterChanged += (o) => {
|
||||||
|
|
||||||
string address = $"{o.GetRegisterString()}{o.MemoryAdress}".PadRight(5, (char)32); ;
|
string address = $"{o.GetRegisterString()}{o.MemoryAdress}".PadRight(5, (char)32);
|
||||||
|
|
||||||
Logger.Log($"{address} " +
|
Logger.Log($"{address} " +
|
||||||
$"{(o.Name != null ? $"({o.Name}) " : "")}" +
|
$"{(o.Name != null ? $"({o.Name}) " : "")}" +
|
||||||
@@ -144,6 +263,7 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
if (OnFailed != null) {
|
if (OnFailed != null) {
|
||||||
OnFailed();
|
OnFailed();
|
||||||
|
Disconnected?.Invoke();
|
||||||
Logger.Log("Initial connection failed", LogLevel.Info, this);
|
Logger.Log("Initial connection failed", LogLevel.Info, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,6 +273,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>
|
/// <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
|
||||||
@@ -167,6 +316,87 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
#endregion
|
#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 {
|
||||||
|
|
||||||
|
if(HostEndpoint != null) {
|
||||||
|
|
||||||
|
client = new TcpClient(HostEndpoint) {
|
||||||
|
ReceiveBufferSize = RecBufferSize,
|
||||||
|
NoDelay = false,
|
||||||
|
};
|
||||||
|
var ep = (IPEndPoint)client.Client.LocalEndPoint;
|
||||||
|
Logger.Log($"Connecting [MAN] endpoint: {ep.Address}:{ep.Port}", LogLevel.Verbose, this);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
|
||||||
|
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 || !client.Connected) {
|
||||||
|
OnMajorSocketExceptionWhileConnecting();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(HostEndpoint == null) {
|
||||||
|
var ep = (IPEndPoint)client.Client.LocalEndPoint;
|
||||||
|
Logger.Log($"Connecting [AUTO] endpoint: {ep.Address.MapToIPv4()}:{ep.Port}", LogLevel.Verbose, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
stream = client.GetStream();
|
||||||
|
stream.ReadTimeout = 1000;
|
||||||
|
|
||||||
|
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
|
#region Register Collection
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -190,47 +420,51 @@ namespace MewtocolNet {
|
|||||||
string propName = prop.Name;
|
string propName = prop.Name;
|
||||||
foreach (var attr in attributes) {
|
foreach (var attr in attributes) {
|
||||||
|
|
||||||
if(attr is RegisterAttribute cAttribute) {
|
if (attr is RegisterAttribute cAttribute) {
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(bool) && cAttribute.AssignedBitIndex == -1) {
|
if (prop.PropertyType == typeof(bool) && cAttribute.AssignedBitIndex == -1) {
|
||||||
if (cAttribute.SpecialAddress == SpecialAddress.None) {
|
if (cAttribute.SpecialAddress == SpecialAddress.None) {
|
||||||
AddRegister(cAttribute.MemoryArea, cAttribute.RegisterType, _name: propName);
|
AddRegister(collection.GetType(), cAttribute.MemoryArea, cAttribute.RegisterType, _name: propName);
|
||||||
} else {
|
} else {
|
||||||
AddRegister(cAttribute.SpecialAddress, cAttribute.RegisterType, _name: propName);
|
AddRegister(collection.GetType(), cAttribute.SpecialAddress, cAttribute.RegisterType, _name: propName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(short)) {
|
if (prop.PropertyType == typeof(short)) {
|
||||||
AddRegister<short>(cAttribute.MemoryArea, _name: propName);
|
AddRegister<short>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(ushort)) {
|
if (prop.PropertyType == typeof(ushort)) {
|
||||||
AddRegister<ushort>(cAttribute.MemoryArea, _name: propName);
|
AddRegister<ushort>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(int)) {
|
if (prop.PropertyType == typeof(int)) {
|
||||||
AddRegister<int>(cAttribute.MemoryArea, _name: propName);
|
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(uint)) {
|
if (prop.PropertyType == typeof(uint)) {
|
||||||
AddRegister<uint>(cAttribute.MemoryArea, _name: propName);
|
AddRegister<uint>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(float)) {
|
if (prop.PropertyType == typeof(float)) {
|
||||||
AddRegister<float>(cAttribute.MemoryArea, _name: propName);
|
AddRegister<float>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(string)) {
|
if (prop.PropertyType == typeof(string)) {
|
||||||
AddRegister<string>(cAttribute.MemoryArea, cAttribute.StringLength, _name: propName);
|
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
|
//read number as bit array
|
||||||
if (prop.PropertyType == typeof(BitArray)) {
|
if (prop.PropertyType == typeof(BitArray)) {
|
||||||
|
|
||||||
if(cAttribute.BitCount == BitCount.B16) {
|
if (cAttribute.BitCount == BitCount.B16) {
|
||||||
AddRegister<short>(cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
AddRegister<short>(collection.GetType(), cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||||
} else {
|
} else {
|
||||||
AddRegister<int>(cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -238,16 +472,18 @@ namespace MewtocolNet {
|
|||||||
//read number as bit array by invdividual properties
|
//read number as bit array by invdividual properties
|
||||||
if (prop.PropertyType == typeof(bool) && cAttribute.AssignedBitIndex != -1) {
|
if (prop.PropertyType == typeof(bool) && cAttribute.AssignedBitIndex != -1) {
|
||||||
|
|
||||||
|
//var bitwiseCount = Registers.Count(x => x.Value.isUsedBitwise);
|
||||||
|
|
||||||
if (cAttribute.BitCount == BitCount.B16) {
|
if (cAttribute.BitCount == BitCount.B16) {
|
||||||
AddRegister<short>(cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
AddRegister<short>(collection.GetType(), cAttribute.MemoryArea, _name: $"Auto_Bitwise_DT{cAttribute.MemoryArea}", _isBitwise: true);
|
||||||
} else {
|
} else {
|
||||||
AddRegister<int>(cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: $"Auto_Bitwise_DDT{cAttribute.MemoryArea}", _isBitwise: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prop.PropertyType == typeof(TimeSpan)) {
|
if (prop.PropertyType == typeof(TimeSpan)) {
|
||||||
AddRegister<TimeSpan>(cAttribute.MemoryArea, _name: propName);
|
AddRegister<TimeSpan>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -258,8 +494,45 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
RegisterChanged += (reg) => {
|
RegisterChanged += (reg) => {
|
||||||
|
|
||||||
|
//if the register is also used bitwise assign the boolean bit value to the according prop
|
||||||
|
if(reg.isUsedBitwise) {
|
||||||
|
|
||||||
|
for (int i = 0; i < props.Length; i++) {
|
||||||
|
|
||||||
|
var prop = props[i];
|
||||||
|
var bitWiseFound = prop.GetCustomAttributes(true)
|
||||||
|
.FirstOrDefault(y => y.GetType() == typeof(RegisterAttribute) && ((RegisterAttribute)y).MemoryArea == reg.MemoryAdress);
|
||||||
|
|
||||||
|
if(bitWiseFound != null && reg is NRegister<short> reg16) {
|
||||||
|
var casted = (RegisterAttribute)bitWiseFound;
|
||||||
|
var bitIndex = casted.AssignedBitIndex;
|
||||||
|
|
||||||
|
var bytes = BitConverter.GetBytes(reg16.Value);
|
||||||
|
BitArray bitAr = new BitArray(bytes);
|
||||||
|
|
||||||
|
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;
|
||||||
|
var bitIndex = casted.AssignedBitIndex;
|
||||||
|
|
||||||
|
var bytes = BitConverter.GetBytes(reg32.Value);
|
||||||
|
BitArray bitAr = new BitArray(bytes);
|
||||||
|
prop.SetValue(collection, bitAr[bitIndex]);
|
||||||
|
collection.TriggerPropertyChanged(prop.Name);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
var foundToUpdate = props.FirstOrDefault(x => x.Name == reg.Name);
|
var foundToUpdate = props.FirstOrDefault(x => x.Name == reg.Name);
|
||||||
|
|
||||||
if (foundToUpdate != null) {
|
if (foundToUpdate != null) {
|
||||||
|
|
||||||
var foundAttributes = foundToUpdate.GetCustomAttributes(true);
|
var foundAttributes = foundToUpdate.GetCustomAttributes(true);
|
||||||
@@ -300,6 +573,14 @@ namespace MewtocolNet {
|
|||||||
foundToUpdate.SetValue(collection, ((NRegister<float>)reg).Value);
|
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
|
//setting back strings
|
||||||
|
|
||||||
if (foundToUpdate.PropertyType == typeof(string)) {
|
if (foundToUpdate.PropertyType == typeof(string)) {
|
||||||
@@ -309,27 +590,7 @@ namespace MewtocolNet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (foundToUpdate.PropertyType == typeof(bool) && registerAttr.AssignedBitIndex >= 0) {
|
if (foundToUpdate.PropertyType == typeof(BitArray)) {
|
||||||
|
|
||||||
//setting back bit registers to individual properties
|
|
||||||
if (reg is NRegister<short> shortReg) {
|
|
||||||
|
|
||||||
var bytes = BitConverter.GetBytes(shortReg.Value);
|
|
||||||
BitArray bitAr = new BitArray(bytes);
|
|
||||||
foundToUpdate.SetValue(collection, bitAr[registerAttr.AssignedBitIndex]);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if (reg is NRegister<int> intReg) {
|
|
||||||
|
|
||||||
var bytes = BitConverter.GetBytes(intReg.Value);
|
|
||||||
BitArray bitAr = new BitArray(bytes);
|
|
||||||
foundToUpdate.SetValue(collection, bitAr[registerAttr.AssignedBitIndex]);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
} else if(foundToUpdate.PropertyType == typeof(BitArray)) {
|
|
||||||
|
|
||||||
//setting back bit registers
|
//setting back bit registers
|
||||||
if (reg is NRegister<short> shortReg) {
|
if (reg is NRegister<short> shortReg) {
|
||||||
@@ -356,6 +617,14 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (collection != null)
|
||||||
|
collection.OnInterfaceLinked(this);
|
||||||
|
|
||||||
|
Connected += (i) => {
|
||||||
|
if (collection != null)
|
||||||
|
collection.OnInterfaceLinkedAndOnline(this);
|
||||||
|
};
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -454,7 +723,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) {
|
||||||
|
|
||||||
@@ -462,29 +730,44 @@ namespace MewtocolNet {
|
|||||||
_msg += "\r";
|
_msg += "\r";
|
||||||
|
|
||||||
//send request
|
//send request
|
||||||
|
try {
|
||||||
|
|
||||||
string response = null;
|
queuedMessages++;
|
||||||
|
var response = await queue.Enqueue(() => SendSingleBlock(_msg));
|
||||||
|
queuedMessages--;
|
||||||
|
|
||||||
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);
|
return new CommandResult {
|
||||||
PriorityTasks.Add(awaittask);
|
Success = true,
|
||||||
awaittask.Wait();
|
Error = "0000",
|
||||||
|
Response = response.ToString()
|
||||||
|
};
|
||||||
|
|
||||||
PriorityTasks.Remove(awaittask);
|
} catch {
|
||||||
response = awaittask.Result;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
|
|
||||||
//poller not active let the user manage message timing
|
|
||||||
|
|
||||||
response = await SendSingleBlock(_msg);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if(response == null) {
|
|
||||||
return new CommandResult {
|
return new CommandResult {
|
||||||
Success = false,
|
Success = false,
|
||||||
Error = "0000",
|
Error = "0000",
|
||||||
@@ -492,78 +775,124 @@ 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) {
|
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 == null || !client.Connected)
|
||||||
|
return null;
|
||||||
|
|
||||||
try {
|
var message = _blockString.ToHexASCIIBytes();
|
||||||
|
|
||||||
await client.ConnectAsync(ip, port);
|
//time measuring
|
||||||
|
if(speedStopwatchUpstr == null) {
|
||||||
|
speedStopwatchUpstr = Stopwatch.StartNew();
|
||||||
|
}
|
||||||
|
|
||||||
using (NetworkStream stream = client.GetStream()) {
|
if(speedStopwatchUpstr.Elapsed.TotalSeconds >= 1) {
|
||||||
var message = _blockString.ToHexASCIIBytes();
|
speedStopwatchUpstr.Restart();
|
||||||
var messageAscii = BitConverter.ToString(message).Replace("-", " ");
|
bytesTotalCountedUpstream = 0;
|
||||||
//send request
|
}
|
||||||
using (var sendStream = new MemoryStream(message)) {
|
|
||||||
await sendStream.CopyToAsync(stream);
|
//send request
|
||||||
Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this);
|
using (var sendStream = new MemoryStream(message)) {
|
||||||
//log message sent
|
await sendStream.CopyToAsync(stream);
|
||||||
ASCIIEncoding enc = new ASCIIEncoding();
|
Logger.Log($"[--------------------------------]", LogLevel.Critical, this);
|
||||||
string characters = enc.GetString(message);
|
Logger.Log($"--> OUT MSG: {_blockString}", LogLevel.Critical, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
//calc upstream speed
|
||||||
|
bytesTotalCountedUpstream += message.Length;
|
||||||
|
|
||||||
|
var perSecUpstream = (double)((bytesTotalCountedUpstream / speedStopwatchUpstr.Elapsed.TotalMilliseconds) * 1000);
|
||||||
|
if (perSecUpstream <= 10000)
|
||||||
|
BytesPerSecondUpstream = (int)Math.Round(perSecUpstream, MidpointRounding.AwayFromZero);
|
||||||
|
|
||||||
|
//await result
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
try {
|
||||||
|
|
||||||
|
byte[] responseBuffer = new byte[128 * 16];
|
||||||
|
|
||||||
|
bool endLineCode = false;
|
||||||
|
bool startMsgCode = false;
|
||||||
|
|
||||||
|
while (!endLineCode && !startMsgCode) {
|
||||||
|
|
||||||
|
do {
|
||||||
|
|
||||||
|
//time measuring
|
||||||
|
if (speedStopwatchDownstr == null) {
|
||||||
|
speedStopwatchDownstr = Stopwatch.StartNew();
|
||||||
}
|
}
|
||||||
//await result
|
|
||||||
StringBuilder response = new StringBuilder();
|
if (speedStopwatchDownstr.Elapsed.TotalSeconds >= 1) {
|
||||||
byte[] responseBuffer = new byte[256];
|
speedStopwatchDownstr.Restart();
|
||||||
do {
|
bytesTotalCountedDownstream = 0;
|
||||||
int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length);
|
|
||||||
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
|
|
||||||
}
|
}
|
||||||
while (stream.DataAvailable);
|
|
||||||
sw.Stop();
|
int bytes = await stream.ReadAsync(responseBuffer, 0, responseBuffer.Length);
|
||||||
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {_blockString}", LogLevel.Critical, this);
|
|
||||||
return response.ToString();
|
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(Exception) {
|
|
||||||
|
|
||||||
IsConnected = false;
|
|
||||||
KillPoller();
|
|
||||||
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
|
|
||||||
return null;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} catch (IOException) {
|
||||||
|
OnMajorSocketExceptionWhileConnected();
|
||||||
|
return null;
|
||||||
|
} catch (SocketException) {
|
||||||
|
OnMajorSocketExceptionWhileConnected();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!string.IsNullOrEmpty(response.ToString())) {
|
||||||
|
|
||||||
|
Logger.Log($"<-- IN MSG: {response}", LogLevel.Critical, this);
|
||||||
|
|
||||||
|
bytesTotalCountedDownstream += Encoding.ASCII.GetByteCount(response.ToString());
|
||||||
|
|
||||||
|
var perSecDownstream = (double)((bytesTotalCountedDownstream / speedStopwatchDownstr.Elapsed.TotalMilliseconds) * 1000);
|
||||||
|
|
||||||
|
if(perSecUpstream <= 10000)
|
||||||
|
BytesPerSecondDownstream = (int)Math.Round(perSecUpstream, MidpointRounding.AwayFromZero);
|
||||||
|
|
||||||
|
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
|
#endregion
|
||||||
|
|
||||||
@@ -582,4 +911,5 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -44,6 +44,8 @@ namespace MewtocolNet {
|
|||||||
ErrorCode = error,
|
ErrorCode = error,
|
||||||
StationNumber = int.Parse(station ?? "0"),
|
StationNumber = int.Parse(station ?? "0"),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
PlcInfo = retInfo;
|
||||||
return retInfo;
|
return retInfo;
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -110,29 +112,47 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="start">Start adress</param>
|
/// <param name="start">Start adress</param>
|
||||||
/// <param name="count">Number of bytes to get</param>
|
/// <param name="count">Number of bytes to get</param>
|
||||||
|
/// <param name="onProgress">Gets invoked when the progress changes, contains the progress as a double</param>
|
||||||
/// <returns>A byte array or null of there was an error</returns>
|
/// <returns>A byte array or null of there was an error</returns>
|
||||||
public async Task<byte[]> ReadByteRange (int start, int count) {
|
public async Task<byte[]> ReadByteRange (int start, int count, Action<double> onProgress = null) {
|
||||||
|
|
||||||
string startStr = start.ToString().PadLeft(5, '0');
|
var byteList = new List<byte>();
|
||||||
|
|
||||||
var wordLength = count / 2;
|
var wordLength = count / 2;
|
||||||
bool wasOdd = false;
|
|
||||||
if (count % 2 != 0)
|
if (count % 2 != 0)
|
||||||
wordLength++;
|
wordLength++;
|
||||||
|
|
||||||
string endStr = (start + wordLength - 1).ToString().PadLeft(5, '0');
|
|
||||||
|
|
||||||
string requeststring = $"%{GetStationNumber()}#RDD{startStr}{endStr}";
|
//read blocks of max 4 words per msg
|
||||||
var result = await SendCommandAsync(requeststring);
|
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());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if(onProgress != null)
|
||||||
|
onProgress((double)i / wordLength);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return byteList.ToArray();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,7 +178,7 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
var resultBool = result.Response.ParseRCSingleBit();
|
var resultBool = result.Response.ParseRCSingleBit();
|
||||||
if(resultBool != null) {
|
if(resultBool != null) {
|
||||||
_toRead.LastValue = resultBool.Value;
|
_toRead.SetValueFromPLC(resultBool.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
var finalRes = new BRegisterResult {
|
var finalRes = new BRegisterResult {
|
||||||
@@ -174,6 +194,7 @@ namespace MewtocolNet {
|
|||||||
/// Writes to the given bool register on the PLC
|
/// Writes to the given bool register on the PLC
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="_toWrite">The register to write to</param>
|
/// <param name="_toWrite">The register to write to</param>
|
||||||
|
/// <param name="value">The value to write</param>
|
||||||
/// <returns>The success state of the write operation</returns>
|
/// <returns>The success state of the write operation</returns>
|
||||||
public async Task<bool> WriteBoolRegister (BRegister _toWrite, bool value) {
|
public async Task<bool> WriteBoolRegister (BRegister _toWrite, bool value) {
|
||||||
|
|
||||||
@@ -181,7 +202,7 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
var result = await SendCommandAsync(requeststring);
|
var result = await SendCommandAsync(requeststring);
|
||||||
|
|
||||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}#WC");
|
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WC");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,7 +215,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) {
|
||||||
|
|
||||||
@@ -203,58 +223,66 @@ 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 as NRegister<short>).LastValue = 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 as NRegister<ushort>).LastValue = 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 as NRegister<int>).LastValue = 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 as NRegister<uint>).LastValue = 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);
|
||||||
|
|
||||||
byte[] floatVals = BitConverter.GetBytes(val);
|
byte[] floatVals = BitConverter.GetBytes(val);
|
||||||
float finalFloat = BitConverter.ToSingle(floatVals, 0);
|
float finalFloat = BitConverter.ToSingle(floatVals, 0);
|
||||||
|
|
||||||
(_toRead as NRegister<float>).LastValue = finalFloat;
|
_toRead.SetValueFromPLC(finalFloat);
|
||||||
|
|
||||||
} 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;
|
||||||
var ts = TimeSpan.FromMilliseconds(valMillis);
|
var ts = TimeSpan.FromMilliseconds(valMillis);
|
||||||
|
|
||||||
//minmax writable / readable value is 10ms
|
//minmax writable / readable value is 10ms
|
||||||
(_toRead as NRegister<TimeSpan>).LastValue = ts;
|
_toRead.SetValueFromPLC(ts);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,7 +299,7 @@ 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="_toWrite">The register to write</param>
|
/// <param name="_toWrite">The register to write</param>
|
||||||
/// <param name="_stationNumber">Station number to access</param>
|
/// <param name="_value">The value to write</param>
|
||||||
/// <returns>The success state of the write operation</returns>
|
/// <returns>The success state of the write operation</returns>
|
||||||
public async Task<bool> WriteNumRegister<T> (NRegister<T> _toWrite, T _value) {
|
public async Task<bool> WriteNumRegister<T> (NRegister<T> _toWrite, T _value) {
|
||||||
|
|
||||||
@@ -311,7 +339,7 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
var result = await SendCommandAsync(requeststring);
|
var result = await SendCommandAsync(requeststring);
|
||||||
|
|
||||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}#WD");
|
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -367,7 +395,7 @@ namespace MewtocolNet {
|
|||||||
var result = await SendCommandAsync(requeststring);
|
var result = await SendCommandAsync(requeststring);
|
||||||
|
|
||||||
|
|
||||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}#WD");
|
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD");
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -6,13 +6,38 @@ namespace MewtocolNet.Registers {
|
|||||||
/// All modes
|
/// All modes
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class PLCMode {
|
public class PLCMode {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// PLC is running
|
||||||
|
/// </summary>
|
||||||
public bool RunMode { get; set; }
|
public bool RunMode { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// PLC is in test
|
||||||
|
/// </summary>
|
||||||
public bool TestRunMode { get; set; }
|
public bool TestRunMode { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// BreakExcecuting
|
||||||
|
/// </summary>
|
||||||
public bool BreakExcecuting { get; set; }
|
public bool BreakExcecuting { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// BreakValid
|
||||||
|
/// </summary>
|
||||||
public bool BreakValid { get; set; }
|
public bool BreakValid { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// PLC output is enabled
|
||||||
|
/// </summary>
|
||||||
public bool OutputEnabled { get; set; }
|
public bool OutputEnabled { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// PLC runs step per step
|
||||||
|
/// </summary>
|
||||||
public bool StepRunMode { get; set; }
|
public bool StepRunMode { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Message executing
|
||||||
|
/// </summary>
|
||||||
public bool MessageExecuting { get; set; }
|
public bool MessageExecuting { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// PLC is in remote mode
|
||||||
|
/// </summary>
|
||||||
public bool RemoteMode { get; set; }
|
public bool RemoteMode { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -6,22 +6,39 @@ using System.Threading.Tasks;
|
|||||||
|
|
||||||
namespace MewtocolNet.RegisterAttributes {
|
namespace MewtocolNet.RegisterAttributes {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The size of the bitwise register
|
||||||
|
/// </summary>
|
||||||
public enum BitCount {
|
public enum BitCount {
|
||||||
|
/// <summary>
|
||||||
|
/// 16 bit
|
||||||
|
/// </summary>
|
||||||
B16,
|
B16,
|
||||||
|
/// <summary>
|
||||||
|
/// 32 bit
|
||||||
|
/// </summary>
|
||||||
B32
|
B32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Defines the behavior of a register property
|
||||||
|
/// </summary>
|
||||||
[AttributeUsage(AttributeTargets.Property)]
|
[AttributeUsage(AttributeTargets.Property)]
|
||||||
public class RegisterAttribute : Attribute {
|
public class RegisterAttribute : Attribute {
|
||||||
|
|
||||||
public int MemoryArea;
|
internal int MemoryArea;
|
||||||
public int StringLength;
|
internal int StringLength;
|
||||||
public RegisterType RegisterType;
|
internal RegisterType RegisterType;
|
||||||
public SpecialAddress SpecialAddress = SpecialAddress.None;
|
internal SpecialAddress SpecialAddress = SpecialAddress.None;
|
||||||
public BitCount BitCount;
|
internal BitCount BitCount;
|
||||||
public int AssignedBitIndex = -1;
|
internal int AssignedBitIndex = -1;
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attribute for string type or numeric registers
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="memoryArea">The area in the plcs memory</param>
|
||||||
|
/// <param name="stringLength">The max string length in the plc</param>
|
||||||
public RegisterAttribute (int memoryArea, int stringLength = 1) {
|
public RegisterAttribute (int memoryArea, int stringLength = 1) {
|
||||||
|
|
||||||
MemoryArea = memoryArea;
|
MemoryArea = memoryArea;
|
||||||
@@ -29,6 +46,11 @@ namespace MewtocolNet.RegisterAttributes {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attribute for boolean registers
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="memoryArea">The area in the plcs memory</param>
|
||||||
|
/// <param name="type">The type of boolean register</param>
|
||||||
public RegisterAttribute (int memoryArea, RegisterType type) {
|
public RegisterAttribute (int memoryArea, RegisterType type) {
|
||||||
|
|
||||||
if (type.ToString().StartsWith("DT"))
|
if (type.ToString().StartsWith("DT"))
|
||||||
@@ -40,6 +62,11 @@ namespace MewtocolNet.RegisterAttributes {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attribute for boolean registers
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="spAdress">The special area in the plcs memory</param>
|
||||||
|
/// <param name="type">The type of boolean register</param>
|
||||||
public RegisterAttribute (RegisterType type, SpecialAddress spAdress) {
|
public RegisterAttribute (RegisterType type, SpecialAddress spAdress) {
|
||||||
|
|
||||||
if (type.ToString().StartsWith("DT"))
|
if (type.ToString().StartsWith("DT"))
|
||||||
@@ -50,7 +77,11 @@ namespace MewtocolNet.RegisterAttributes {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attribute to read numeric registers as bitwise
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="memoryArea">The area in the plcs memory</param>
|
||||||
|
/// <param name="bitcount">The number of bits to parse</param>
|
||||||
public RegisterAttribute (int memoryArea, BitCount bitcount) {
|
public RegisterAttribute (int memoryArea, BitCount bitcount) {
|
||||||
|
|
||||||
MemoryArea = memoryArea;
|
MemoryArea = memoryArea;
|
||||||
@@ -59,6 +90,12 @@ namespace MewtocolNet.RegisterAttributes {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attribute to read numeric registers as bitwise
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="memoryArea">The area in the plcs memory</param>
|
||||||
|
/// <param name="bitcount">The number of bits to parse</param>
|
||||||
|
/// <param name="assignBit">The index of the bit that gets linked to the bool</param>
|
||||||
public RegisterAttribute (int memoryArea, uint assignBit, BitCount bitcount) {
|
public RegisterAttribute (int memoryArea, uint assignBit, BitCount bitcount) {
|
||||||
|
|
||||||
if(assignBit > 15 && bitcount == BitCount.B16) {
|
if(assignBit > 15 && bitcount == BitCount.B16) {
|
||||||
|
|||||||
@@ -10,17 +10,43 @@ using System.Threading.Tasks;
|
|||||||
|
|
||||||
namespace MewtocolNet.RegisterAttributes {
|
namespace MewtocolNet.RegisterAttributes {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A register collection base with full auto read and notification support built in
|
||||||
|
/// </summary>
|
||||||
public class RegisterCollectionBase : INotifyPropertyChanged {
|
public class RegisterCollectionBase : INotifyPropertyChanged {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reference to its bound interface
|
||||||
|
/// </summary>
|
||||||
public MewtocolInterface PLCInterface { get; set; }
|
public MewtocolInterface PLCInterface { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whenever one of its props changes
|
||||||
|
/// </summary>
|
||||||
public event PropertyChangedEventHandler PropertyChanged;
|
public event PropertyChangedEventHandler PropertyChanged;
|
||||||
|
|
||||||
internal void TriggerPropertyChanged (string propertyName = null) {
|
/// <summary>
|
||||||
|
/// Triggers a property changed event
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="propertyName">Name of the property to trigger for</param>
|
||||||
|
public void TriggerPropertyChanged (string propertyName = null) {
|
||||||
var handler = PropertyChanged;
|
var handler = PropertyChanged;
|
||||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets called when the register collection base was linked to its parent mewtocol interface
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="plc">The parent interface</param>
|
||||||
|
public virtual void OnInterfaceLinked (MewtocolInterface plc) { }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets called when the register collection base was linked to its parent mewtocol interface
|
||||||
|
/// and the plc connection is established
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="plc">The parent interface</param>
|
||||||
|
public virtual void OnInterfaceLinkedAndOnline (MewtocolInterface plc) { }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,22 +9,15 @@ namespace MewtocolNet.Registers {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class BRegister : Register {
|
public class BRegister : Register {
|
||||||
|
|
||||||
internal RegisterType RegType { get; set; }
|
internal RegisterType RegType { get; private set; }
|
||||||
internal SpecialAddress SpecialAddress { get; set; }
|
internal SpecialAddress SpecialAddress { get; private set; }
|
||||||
|
|
||||||
public bool NeedValue;
|
internal bool LastValue;
|
||||||
public bool LastValue;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The value of the register
|
/// The value of the register
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool Value {
|
public bool Value => LastValue;
|
||||||
get => LastValue;
|
|
||||||
set {
|
|
||||||
NeedValue = value;
|
|
||||||
TriggerChangedEvnt(this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Defines a register containing a number
|
/// Defines a register containing a number
|
||||||
@@ -35,8 +28,8 @@ namespace MewtocolNet.Registers {
|
|||||||
public BRegister (int _address, RegisterType _type = RegisterType.R, string _name = null) {
|
public BRegister (int _address, RegisterType _type = RegisterType.R, string _name = null) {
|
||||||
|
|
||||||
if (_address > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
if (_address > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||||
MemoryAdress = _address;
|
memoryAdress = _address;
|
||||||
Name = _name;
|
name = _name;
|
||||||
|
|
||||||
RegType = _type;
|
RegType = _type;
|
||||||
|
|
||||||
@@ -54,12 +47,15 @@ namespace MewtocolNet.Registers {
|
|||||||
throw new NotSupportedException("Special adress cant be none");
|
throw new NotSupportedException("Special adress cant be none");
|
||||||
|
|
||||||
SpecialAddress = _address;
|
SpecialAddress = _address;
|
||||||
Name = _name;
|
name = _name;
|
||||||
|
|
||||||
RegType = _type;
|
RegType = _type;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the register area name
|
||||||
|
/// </summary>
|
||||||
public override string BuildMewtocolIdent () {
|
public override string BuildMewtocolIdent () {
|
||||||
|
|
||||||
//build area code from register type
|
//build area code from register type
|
||||||
@@ -74,9 +70,12 @@ namespace MewtocolNet.Registers {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() {
|
internal void SetValueFromPLC (bool val) {
|
||||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
LastValue = val;
|
||||||
|
TriggerChangedEvnt(this);
|
||||||
|
TriggerNotifyChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
namespace MewtocolNet.Registers {
|
namespace MewtocolNet.Registers {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Result for a boolean register
|
||||||
|
/// </summary>
|
||||||
public class BRegisterResult {
|
public class BRegisterResult {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The command result
|
||||||
|
/// </summary>
|
||||||
public CommandResult Result { get; set; }
|
public CommandResult Result { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The used register
|
||||||
|
/// </summary>
|
||||||
public BRegister Register { get; set; }
|
public BRegister Register { get; set; }
|
||||||
|
|
||||||
public override string ToString() {
|
|
||||||
string errmsg = Result.Success ? "" : $", Error [{Result.ErrorDescription}]";
|
|
||||||
return $"Result [{Result.Success}], Register [{Register.ToString()}]{errmsg}";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,54 +7,76 @@ namespace MewtocolNet.Registers {
|
|||||||
/// <typeparam name="T">The type of the numeric value</typeparam>
|
/// <typeparam name="T">The type of the numeric value</typeparam>
|
||||||
public class NRegister<T> : Register {
|
public class NRegister<T> : Register {
|
||||||
|
|
||||||
public T NeedValue;
|
internal T LastValue;
|
||||||
public T LastValue;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The value of the register
|
/// The value of the register
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public T Value {
|
public T Value => LastValue;
|
||||||
get => LastValue;
|
|
||||||
set {
|
|
||||||
NeedValue = value;
|
|
||||||
TriggerChangedEvnt(this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Defines a register containing a number
|
/// Defines a register containing a number
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="_adress">Memory start adress max 99999</param>
|
/// <param name="_adress">Memory start adress max 99999</param>
|
||||||
/// <param name="_format">The format in which the variable is stored</param>
|
/// <param name="_name">Name of the register</param>
|
||||||
public NRegister(int _adress, string _name = null, bool isBitwise = false) {
|
public NRegister (int _adress, string _name = null) {
|
||||||
|
|
||||||
if (_adress > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
if (_adress > 99999)
|
||||||
MemoryAdress = _adress;
|
throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||||
Name = _name;
|
memoryAdress = _adress;
|
||||||
|
name = _name;
|
||||||
Type numType = typeof(T);
|
Type numType = typeof(T);
|
||||||
if (numType == typeof(short)) {
|
if (numType == typeof(short)) {
|
||||||
MemoryLength = 0;
|
memoryLength = 0;
|
||||||
} else if (numType == typeof(ushort)) {
|
} else if (numType == typeof(ushort)) {
|
||||||
MemoryLength = 0;
|
memoryLength = 0;
|
||||||
} else if (numType == typeof(int)) {
|
} else if (numType == typeof(int)) {
|
||||||
MemoryLength = 1;
|
memoryLength = 1;
|
||||||
} else if (numType == typeof(uint)) {
|
} else if (numType == typeof(uint)) {
|
||||||
MemoryLength = 1;
|
memoryLength = 1;
|
||||||
} else if (numType == typeof(float)) {
|
} else if (numType == typeof(float)) {
|
||||||
MemoryLength = 1;
|
memoryLength = 1;
|
||||||
} else if (numType == typeof(TimeSpan)) {
|
} else if (numType == typeof(TimeSpan)) {
|
||||||
MemoryLength = 1;
|
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;
|
||||||
|
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 {
|
} else {
|
||||||
throw new NotSupportedException($"The type {numType} is not allowed for Number Registers");
|
throw new NotSupportedException($"The type {numType} is not allowed for Number Registers");
|
||||||
}
|
}
|
||||||
|
|
||||||
isUsedBitwise = isBitwise;
|
isUsedBitwise = isBitwise;
|
||||||
|
enumType = _enumType;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() {
|
internal void SetValueFromPLC (object val) {
|
||||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
LastValue = (T)val;
|
||||||
|
TriggerChangedEvnt(this);
|
||||||
|
TriggerNotifyChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,34 @@
|
|||||||
namespace MewtocolNet.Registers {
|
using System;
|
||||||
|
|
||||||
|
namespace MewtocolNet.Registers {
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Result for a read/write operation
|
/// Result for a read/write operation
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T">The type of the numeric value</typeparam>
|
/// <typeparam name="T">The type of the numeric value</typeparam>
|
||||||
public class NRegisterResult<T> {
|
public class NRegisterResult<T> {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Command result
|
||||||
|
/// </summary>
|
||||||
public CommandResult Result { get; set; }
|
public CommandResult Result { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The used register
|
||||||
|
/// </summary>
|
||||||
public NRegister<T> Register { get; set; }
|
public NRegister<T> Register { get; set; }
|
||||||
|
|
||||||
public override string ToString() {
|
/// <summary>
|
||||||
string errmsg = Result.Success ? "" : $", Error [{Result.ErrorDescription}]";
|
/// Trys to get the value of there is one
|
||||||
return $"Result [{Result.Success}], Register [{Register.ToString()}]{errmsg}";
|
/// </summary>
|
||||||
|
public bool TryGetValue (out T value) {
|
||||||
|
if(Result.Success) {
|
||||||
|
value = Register.Value;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
value = default(T);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -17,13 +17,67 @@ namespace MewtocolNet.Registers {
|
|||||||
/// Gets called whenever the value was changed
|
/// Gets called whenever the value was changed
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public event Action<object> ValueChanged;
|
public event Action<object> ValueChanged;
|
||||||
|
/// <summary>
|
||||||
|
/// Triggers when a property on the register changes
|
||||||
|
/// </summary>
|
||||||
public event PropertyChangedEventHandler PropertyChanged;
|
public event PropertyChangedEventHandler PropertyChanged;
|
||||||
|
|
||||||
public string Name { get; set; }
|
internal Type collectionType;
|
||||||
public int MemoryAdress { get; set; }
|
/// <summary>
|
||||||
public int MemoryLength { get; set; }
|
/// The type of collection the register is in or null of added manually
|
||||||
internal bool isUsedBitwise { get; set; }
|
/// </summary>
|
||||||
|
public Type CollectionType => collectionType;
|
||||||
|
|
||||||
|
internal string name;
|
||||||
|
/// <summary>
|
||||||
|
/// The register name or null of not defined
|
||||||
|
/// </summary>
|
||||||
|
public string Name => name;
|
||||||
|
|
||||||
|
internal int memoryAdress;
|
||||||
|
/// <summary>
|
||||||
|
/// The registers memory adress if not a special register
|
||||||
|
/// </summary>
|
||||||
|
public int MemoryAdress => memoryAdress;
|
||||||
|
|
||||||
|
internal int memoryLength;
|
||||||
|
/// <summary>
|
||||||
|
/// The rgisters memory length
|
||||||
|
/// </summary>
|
||||||
|
public int MemoryLength => memoryLength;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The value of the register auto converted to a string
|
||||||
|
/// </summary>
|
||||||
|
public string StringValue => GetValueString();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The name the register would have in the PLC
|
||||||
|
/// </summary>
|
||||||
|
public string RegisterPLCName => GetRegisterPLCName();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The combined name with the holding register class type infront
|
||||||
|
/// </summary>
|
||||||
|
public string CombinedName => GetCombinedName();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The name of the class that contains this register or empty if it was added manually
|
||||||
|
/// </summary>
|
||||||
|
public string ContainerName => GetContainerName();
|
||||||
|
|
||||||
|
internal bool isUsedBitwise { get; set; }
|
||||||
|
internal Type enumType { get; set; }
|
||||||
|
|
||||||
|
internal Register () {
|
||||||
|
ValueChanged += (obj) => {
|
||||||
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(StringValue)));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the register area name
|
||||||
|
/// </summary>
|
||||||
public virtual string BuildMewtocolIdent() {
|
public virtual string BuildMewtocolIdent() {
|
||||||
|
|
||||||
StringBuilder asciistring = new StringBuilder("D");
|
StringBuilder asciistring = new StringBuilder("D");
|
||||||
@@ -60,6 +114,24 @@ namespace MewtocolNet.Registers {
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string GetValueString () {
|
public string GetValueString () {
|
||||||
|
|
||||||
|
if (enumType != null && this is NRegister<int> intEnumReg) {
|
||||||
|
|
||||||
|
var dict = new Dictionary<int, string>();
|
||||||
|
|
||||||
|
foreach (var name in Enum.GetNames(enumType)) {
|
||||||
|
int enumKey = (int)Enum.Parse(enumType, name);
|
||||||
|
if(!dict.ContainsKey(enumKey)) {
|
||||||
|
dict.Add(enumKey, name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(dict.ContainsKey(intEnumReg.Value)) {
|
||||||
|
return $"{intEnumReg.Value} ({dict[intEnumReg.Value]})";
|
||||||
|
} else {
|
||||||
|
return $"{intEnumReg.Value} (Missing Enum)";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
if (this is NRegister<short> shortReg) {
|
if (this is NRegister<short> shortReg) {
|
||||||
return $"{shortReg.Value}{(isUsedBitwise ? $" [{shortReg.GetBitwise().ToBitString()}]" : "")}";
|
return $"{shortReg.Value}{(isUsedBitwise ? $" [{shortReg.GetBitwise().ToBitString()}]" : "")}";
|
||||||
}
|
}
|
||||||
@@ -82,8 +154,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.";
|
||||||
@@ -116,6 +187,9 @@ namespace MewtocolNet.Registers {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the register dataarea string DT for 16bit and DDT for 32 bit types
|
||||||
|
/// </summary>
|
||||||
public string GetRegisterString () {
|
public string GetRegisterString () {
|
||||||
|
|
||||||
if (this is NRegister<short> shortReg) {
|
if (this is NRegister<short> shortReg) {
|
||||||
@@ -148,7 +222,23 @@ namespace MewtocolNet.Registers {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public string GetRegisterPLCName () {
|
internal string GetCombinedName () {
|
||||||
|
|
||||||
|
return $"{(CollectionType != null ? $"{CollectionType.Name}." : "")}{Name ?? "Unnamed"}";
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
internal string GetContainerName () {
|
||||||
|
|
||||||
|
return $"{(CollectionType != null ? $"{CollectionType.Name}" : "")}";
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
internal string GetRegisterPLCName () {
|
||||||
|
|
||||||
|
if (this is BRegister bReg && bReg.SpecialAddress != SpecialAddress.None) {
|
||||||
|
return $"{GetRegisterString()}{bReg.SpecialAddress}";
|
||||||
|
}
|
||||||
|
|
||||||
return $"{GetRegisterString()}{MemoryAdress}";
|
return $"{GetRegisterString()}{MemoryAdress}";
|
||||||
|
|
||||||
|
|||||||
@@ -8,13 +8,13 @@ namespace MewtocolNet.Registers {
|
|||||||
public class SRegister : Register {
|
public class SRegister : Register {
|
||||||
|
|
||||||
private string lastVal = "";
|
private string lastVal = "";
|
||||||
public string Value {
|
|
||||||
|
|
||||||
get => lastVal;
|
/// <summary>
|
||||||
|
/// The current value of the register
|
||||||
}
|
/// </summary>
|
||||||
|
public string Value => lastVal;
|
||||||
|
|
||||||
public short ReservedSize { get; set; }
|
internal short ReservedSize { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Defines a register containing a string
|
/// Defines a register containing a string
|
||||||
@@ -22,8 +22,8 @@ namespace MewtocolNet.Registers {
|
|||||||
public SRegister(int _adress, int _reservedStringSize, string _name = null) {
|
public SRegister(int _adress, int _reservedStringSize, string _name = null) {
|
||||||
|
|
||||||
if (_adress > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
if (_adress > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||||
Name = _name;
|
name = _name;
|
||||||
MemoryAdress = _adress;
|
memoryAdress = _adress;
|
||||||
ReservedSize = (short)_reservedStringSize;
|
ReservedSize = (short)_reservedStringSize;
|
||||||
|
|
||||||
//calc mem length
|
//calc mem length
|
||||||
@@ -32,13 +32,12 @@ namespace MewtocolNet.Registers {
|
|||||||
wordsize++;
|
wordsize++;
|
||||||
}
|
}
|
||||||
|
|
||||||
MemoryLength = (int)Math.Round(wordsize + 1);
|
memoryLength = (int)Math.Round(wordsize + 1);
|
||||||
}
|
|
||||||
|
|
||||||
public override string ToString() {
|
|
||||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the register identifier for the mewotocol protocol
|
||||||
|
/// </summary>
|
||||||
public override string BuildMewtocolIdent() {
|
public override string BuildMewtocolIdent() {
|
||||||
|
|
||||||
StringBuilder asciistring = new StringBuilder("D");
|
StringBuilder asciistring = new StringBuilder("D");
|
||||||
@@ -62,13 +61,12 @@ namespace MewtocolNet.Registers {
|
|||||||
return asciistring.ToString();
|
return asciistring.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SetValueFromPLC (string val) {
|
internal void SetValueFromPLC (string val) {
|
||||||
lastVal = val;
|
lastVal = val;
|
||||||
TriggerChangedEvnt(this);
|
TriggerChangedEvnt(this);
|
||||||
TriggerNotifyChange();
|
TriggerNotifyChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
namespace MewtocolNet.Registers {
|
namespace MewtocolNet.Registers {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The results of a string register operation
|
||||||
|
/// </summary>
|
||||||
public class SRegisterResult {
|
public class SRegisterResult {
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The command result
|
||||||
|
/// </summary>
|
||||||
public CommandResult Result { get; set; }
|
public CommandResult Result { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// The register definition used
|
||||||
|
/// </summary>
|
||||||
public SRegister Register { get; set; }
|
public SRegister Register { get; set; }
|
||||||
|
|
||||||
public override string ToString() {
|
|
||||||
string errmsg = Result.Success ? "" : $", Error [{Result.ErrorDescription}]";
|
|
||||||
return $"Result [{Result.Success}], Register [{Register.ToString()}]{errmsg}";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>netstandard2.0</TargetFramework>
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
<PackageId>MewtocolNet</PackageId>
|
<PackageId>MewtocolNet</PackageId>
|
||||||
<Version>0.3.0</Version>
|
<Version>0.5.8</Version>
|
||||||
<Authors>Felix Weiss</Authors>
|
<Authors>Felix Weiss</Authors>
|
||||||
<Company>Womed</Company>
|
<Company>Womed</Company>
|
||||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
<UserSecretsId>2ccdcc9b-94a3-4e76-8827-453ab889ea33</UserSecretsId>
|
<UserSecretsId>2ccdcc9b-94a3-4e76-8827-453ab889ea33</UserSecretsId>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
<DocumentationFile>C:\Users\Felix Weiß\source\repos\WOmed\MewtocolNet\Builds\MewtocolNet.xml</DocumentationFile>
|
<DocumentationFile>..\Builds\MewtocolNet.xml</DocumentationFile>
|
||||||
<OutputPath>C:\Users\Felix Weiß\source\repos\WOmed\MewtocolNet\Builds</OutputPath>
|
<OutputPath>..\Builds</OutputPath>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
30
MewtocolNet/Queue/SerialQueue.cs
Normal file
30
MewtocolNet/Queue/SerialQueue.cs
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
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<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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
13
README.md
13
README.md
@@ -18,18 +18,17 @@ This software was written by WOLF Medizintechnik GmbH (@WOmed/dev).
|
|||||||
|
|
||||||
- [x] Read out stats from your PLC
|
- [x] Read out stats from your PLC
|
||||||
- [x] Read and write registers in real time
|
- [x] Read and write registers in real time
|
||||||
- [X] Dynamic register type casting from properties
|
- [x] Dynamic register type casting from properties
|
||||||
- [ ] Change run / prog modes
|
- [x] Change run / prog modes
|
||||||
- [ ] Write byte blocks in a whole chain
|
- [x] Write / read byte blocks in a whole chain
|
||||||
- [ ] Upload programs to the PLC
|
- [ ] Upload / Download programs to the PLC
|
||||||
- [ ] Download programs from the PLC
|
|
||||||
- [ ] Reading / writing PLC system registers
|
- [ ] Reading / writing PLC system registers
|
||||||
|
|
||||||
# Support
|
# Support
|
||||||
|
|
||||||
## .NET Support
|
## .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)
|
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)
|
||||||
|
|
||||||
@@ -54,7 +53,7 @@ Where is the RS232/Serial support?
|
|||||||
|
|
||||||
Install this package by using [Nuget](https://www.nuget.org/packages/MewtocolNet/) or reference
|
Install this package by using [Nuget](https://www.nuget.org/packages/MewtocolNet/) or reference
|
||||||
```XML
|
```XML
|
||||||
<PackageReference Include="MewtocolNet" Version="0.2.5" />
|
<PackageReference Include="MewtocolNet" Version="0.5.2" />
|
||||||
```
|
```
|
||||||
in your dependencies.
|
in your dependencies.
|
||||||
Alternatively use the dotnet CLI and run
|
Alternatively use the dotnet CLI and run
|
||||||
|
|||||||
Reference in New Issue
Block a user