mirror of
https://github.com/OpenLogics/MewtocolNet.git
synced 2025-12-06 11:11:23 +00:00
Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43c7f72ac4 | ||
|
|
2e35ed87af | ||
|
|
a7f97a72ea | ||
|
|
51870166e4 | ||
|
|
b43e9bd201 | ||
|
|
e313dbc3ec | ||
|
|
bdf9f93f97 | ||
|
|
fe816ab78e | ||
|
|
48a5977185 | ||
|
|
c69f63c191 | ||
|
|
6a2f278dd1 | ||
|
|
19159ed183 | ||
|
|
635823a66f | ||
|
|
c7a6559f97 | ||
|
|
88a453355c | ||
|
|
6f8f891760 | ||
|
|
8fb8d4989d | ||
|
|
45a9fa0520 | ||
|
|
772f8b89a4 | ||
|
|
6c7c368b55 | ||
|
|
38f0f9f523 | ||
|
|
c2aecb387a | ||
|
|
0e1f5cd12b | ||
|
|
f15d565029 | ||
|
|
0ac0198223 | ||
|
|
3c450eea97 | ||
|
|
fe2d2b9fb9 | ||
|
|
6c411d7318 |
57
.github/workflows/publish.yml
vendored
Normal file
57
.github/workflows/publish.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
name: publish to nuget
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master # Default release branch, may also be named 'master' or 'develop'
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
name: build, pack & publish
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
# - name: Setup dotnet
|
||||||
|
# uses: actions/setup-dotnet@v1
|
||||||
|
# with:
|
||||||
|
# dotnet-version: 3.1.200
|
||||||
|
|
||||||
|
# Publish
|
||||||
|
- name: publish on version change
|
||||||
|
id: publish_nuget
|
||||||
|
uses: brandedoutcast/publish-nuget@v2
|
||||||
|
with:
|
||||||
|
# Filepath of the project to be packaged, relative to root of repository
|
||||||
|
PROJECT_FILE_PATH: MewtocolNet/MewtocolNet.csproj
|
||||||
|
|
||||||
|
# Configuration to build and package
|
||||||
|
# BUILD_CONFIGURATION: Release
|
||||||
|
|
||||||
|
# Platform target to compile (default is empty/AnyCPU)
|
||||||
|
# BUILD_PLATFORM: x64
|
||||||
|
|
||||||
|
# NuGet package id, used for version detection & defaults to project name
|
||||||
|
PACKAGE_NAME: Mewtocol.NET
|
||||||
|
|
||||||
|
# Filepath with version info, relative to root of repository & defaults to PROJECT_FILE_PATH
|
||||||
|
# VERSION_FILE_PATH: Directory.Build.props
|
||||||
|
|
||||||
|
# Regex pattern to extract version info in a capturing group
|
||||||
|
# VERSION_REGEX: ^\s*<Version>(.*)<\/Version>\s*$
|
||||||
|
|
||||||
|
# Useful with external providers like Nerdbank.GitVersioning, ignores VERSION_FILE_PATH & VERSION_REGEX
|
||||||
|
# VERSION_STATIC: 1.0.0
|
||||||
|
|
||||||
|
# Flag to toggle git tagging, enabled by default
|
||||||
|
# TAG_COMMIT: true
|
||||||
|
|
||||||
|
# Format of the git tag, [*] gets replaced with actual version
|
||||||
|
# TAG_FORMAT: v*
|
||||||
|
|
||||||
|
# API key to authenticate with NuGet server
|
||||||
|
NUGET_KEY: ${{secrets.NUGET_KEY}}
|
||||||
|
|
||||||
|
# NuGet server uri hosting the packages, defaults to https://api.nuget.org
|
||||||
|
# NUGET_SOURCE: https://api.nuget.org
|
||||||
|
|
||||||
|
# Flag to toggle pushing symbols along with nuget package to the server, disabled by default
|
||||||
|
# INCLUDE_SYMBOLS: false
|
||||||
@@ -4,12 +4,33 @@ using MewtocolNet;
|
|||||||
using MewtocolNet.Logging;
|
using MewtocolNet.Logging;
|
||||||
using MewtocolNet.Registers;
|
using MewtocolNet.Registers;
|
||||||
|
|
||||||
namespace Examples {
|
namespace Examples;
|
||||||
|
|
||||||
class Program {
|
class Program {
|
||||||
|
|
||||||
static void Main(string[] args) {
|
static void Main(string[] args) {
|
||||||
|
|
||||||
|
Console.WriteLine("Enter your scenario number:\n" +
|
||||||
|
"1 = Permanent connection\n" +
|
||||||
|
"2 = Dispose connection");
|
||||||
|
|
||||||
|
var line = Console.ReadLine();
|
||||||
|
|
||||||
|
if(line == "1") {
|
||||||
|
Scenario1();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line == "2") {
|
||||||
|
Scenario2();
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.ReadLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool isProgressReadout = false;
|
||||||
|
|
||||||
|
static void Scenario1 () {
|
||||||
|
|
||||||
Task.Factory.StartNew(async () => {
|
Task.Factory.StartNew(async () => {
|
||||||
|
|
||||||
//attaching the logger
|
//attaching the logger
|
||||||
@@ -25,22 +46,94 @@ namespace Examples {
|
|||||||
//attaching the register collection and an automatic poller
|
//attaching the register collection and an automatic poller
|
||||||
interf.WithRegisterCollection(registers).WithPoller();
|
interf.WithRegisterCollection(registers).WithPoller();
|
||||||
|
|
||||||
await interf.ConnectAsync(
|
_ = Task.Factory.StartNew(async () => {
|
||||||
(plcinf) => {
|
while (true) {
|
||||||
|
if (isProgressReadout) continue;
|
||||||
|
Console.Title = $"Polling Paused: {interf.PollingPaused}, " +
|
||||||
|
$"Poller active: {interf.PollerActive}, " +
|
||||||
|
$"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));
|
||||||
|
|
||||||
|
bool flip = false;
|
||||||
|
while(true) {
|
||||||
|
|
||||||
|
if(!flip) {
|
||||||
|
await interf.ConnectAsync();
|
||||||
|
} else {
|
||||||
|
interf.Disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
flip = !flip;
|
||||||
|
await Task.Delay(5000);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
static void AfterConnect (MewtocolInterface interf, TestRegisters registers) {
|
||||||
|
|
||||||
//reading a value from the register collection
|
//reading a value from the register collection
|
||||||
Console.WriteLine($"BitValue is: {registers.BitValue}");
|
Console.WriteLine($"BitValue is: {registers.BitValue}");
|
||||||
Console.WriteLine($"TestEnum is: {registers.TestEnum}");
|
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
|
//writing a value to the registers
|
||||||
Task.Factory.StartNew(async () => {
|
_ = Task.Factory.StartNew(async () => {
|
||||||
|
|
||||||
//set plc to run mode if not already
|
//set plc to run mode if not already
|
||||||
await interf.SetOperationMode(OPMode.Run);
|
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 Task.Delay(2000);
|
||||||
|
|
||||||
Console.WriteLine("Testregister was toggled");
|
await interf.SetRegisterAsync(nameof(registers.TestInt32), 100);
|
||||||
|
|
||||||
//adds 10 each time the plc connects to the PLCs INT regíster
|
//adds 10 each time the plc connects to the PLCs INT regíster
|
||||||
interf.SetRegister(nameof(registers.TestInt16), (short)(registers.TestInt16 + 10));
|
interf.SetRegister(nameof(registers.TestInt16), (short)(registers.TestInt16 + 10));
|
||||||
@@ -53,14 +146,77 @@ namespace Examples {
|
|||||||
//set the current second to the PLCs TIME register
|
//set the current second to the PLCs TIME register
|
||||||
interf.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second));
|
interf.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second));
|
||||||
|
|
||||||
});
|
//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");
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Console.ReadLine();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,11 @@ namespace Examples {
|
|||||||
public bool TestBoolInputXD { get; private set; }
|
public bool TestBoolInputXD { get; private set; }
|
||||||
|
|
||||||
//corresponds to a DT1101 - DT1104 string register in the PLC with (STRING[4])
|
//corresponds to a DT1101 - DT1104 string register in the PLC with (STRING[4])
|
||||||
[Register(1101, 4)]
|
//[Register(1101, 4)]
|
||||||
public string TestString1 { get; private set; }
|
//public string TestString1 { get; private set; }
|
||||||
|
|
||||||
//corresponds to a DT7000 16 bit int register in the PLC
|
//corresponds to a DT7000 16 bit int register in the PLC
|
||||||
[Register(7000)]
|
[Register(899)]
|
||||||
public short TestInt16 { get; private set; }
|
public short TestInt16 { get; private set; }
|
||||||
|
|
||||||
//corresponds to a DTD7001 - DTD7002 32 bit int register in the PLC
|
//corresponds to a DTD7001 - DTD7002 32 bit int register in the PLC
|
||||||
@@ -68,6 +68,8 @@ namespace Examples {
|
|||||||
[Register(50)]
|
[Register(50)]
|
||||||
public CurrentState TestEnum { get; private set; }
|
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,69 @@ 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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True if the poller is actvice (can be paused)
|
||||||
|
/// </summary>
|
||||||
|
public bool PollerActive => !pollerTaskStopped;
|
||||||
|
|
||||||
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 volatile bool pollerFirstCycle = false;
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
|
ClearRegisterVals();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <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,63 +85,39 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal void AttachPoller () {
|
internal void AttachPoller () {
|
||||||
|
|
||||||
if (ContinousReaderRunning) return;
|
if (pollerTaskRunning)
|
||||||
|
return;
|
||||||
|
|
||||||
cTokenAutoUpdater = new CancellationTokenSource();
|
pollerFirstCycle = true;
|
||||||
|
|
||||||
Logger.Log("Poller is attaching", LogLevel.Info, this);
|
|
||||||
|
|
||||||
try {
|
|
||||||
|
|
||||||
Task.Factory.StartNew(async () => {
|
Task.Factory.StartNew(async () => {
|
||||||
|
|
||||||
var plcinf = await GetPLCInfoAsync();
|
Logger.Log("Poller is attaching", LogLevel.Info, this);
|
||||||
if (plcinf == null) {
|
|
||||||
Logger.Log("PLC not reachable, stopping logger", LogLevel.Info, this);
|
int iteration = 0;
|
||||||
return;
|
|
||||||
|
pollerTaskStopped = false;
|
||||||
|
pollerTaskRunning = true;
|
||||||
|
pollerIsPaused = false;
|
||||||
|
|
||||||
|
while (!pollerTaskStopped) {
|
||||||
|
|
||||||
|
while (pollerTaskRunning) {
|
||||||
|
|
||||||
|
if (iteration >= Registers.Count + 1) {
|
||||||
|
iteration = 0;
|
||||||
|
//invoke cycle polled event
|
||||||
|
InvokePolledCycleDone();
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
PolledCycle += MewtocolInterface_PolledCycle;
|
if (iteration >= Registers.Count) {
|
||||||
void MewtocolInterface_PolledCycle () {
|
|
||||||
|
|
||||||
StringBuilder stringBuilder = new StringBuilder();
|
|
||||||
foreach (var reg in GetAllRegisters()) {
|
|
||||||
string address = $"{reg.GetRegisterString()}{reg.GetStartingMemoryArea()}".PadRight(8, (char)32);
|
|
||||||
stringBuilder.AppendLine($"{address}{(reg.Name != null ? $" ({reg.Name})" : "")}: {reg.GetValueString()}");
|
|
||||||
}
|
|
||||||
|
|
||||||
Logger.Log($"Registers loaded are: \n" +
|
|
||||||
$"--------------------\n" +
|
|
||||||
$"{stringBuilder.ToString()}" +
|
|
||||||
$"--------------------",
|
|
||||||
LogLevel.Verbose, this);
|
|
||||||
|
|
||||||
Logger.Log("Logger did its first cycle successfully", LogLevel.Info, this);
|
|
||||||
|
|
||||||
PolledCycle -= MewtocolInterface_PolledCycle;
|
|
||||||
}
|
|
||||||
|
|
||||||
ContinousReaderRunning = true;
|
|
||||||
|
|
||||||
int getPLCinfoCycleCount = 0;
|
|
||||||
|
|
||||||
while (ContinousReaderRunning) {
|
|
||||||
|
|
||||||
//do priority tasks first
|
|
||||||
if (PriorityTasks != null && PriorityTasks.Count > 0) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
await PriorityTasks?.FirstOrDefault(x => !x.IsCompleted);
|
|
||||||
} catch (NullReferenceException) { }
|
|
||||||
|
|
||||||
} else if (getPLCinfoCycleCount > 25) {
|
|
||||||
|
|
||||||
await GetPLCInfoAsync();
|
await GetPLCInfoAsync();
|
||||||
getPLCinfoCycleCount = 0;
|
iteration++;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var reg in Registers) {
|
var reg = Registers[iteration];
|
||||||
|
|
||||||
if (reg is NRegister<short> shortReg) {
|
if (reg is NRegister<short> shortReg) {
|
||||||
var lastVal = shortReg.Value;
|
var lastVal = shortReg.Value;
|
||||||
@@ -146,21 +174,22 @@ namespace MewtocolNet {
|
|||||||
if (lastVal != readout) {
|
if (lastVal != readout) {
|
||||||
InvokeRegisterChanged(stringReg);
|
InvokeRegisterChanged(stringReg);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
iteration++;
|
||||||
|
pollerFirstCycle = false;
|
||||||
|
|
||||||
|
await Task.Delay(pollerDelayMs);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
pollerIsPaused = !pollerTaskRunning;
|
||||||
|
|
||||||
getPLCinfoCycleCount++;
|
|
||||||
|
|
||||||
//invoke cycle polled event
|
|
||||||
InvokePolledCycleDone();
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}, cTokenAutoUpdater.Token);
|
pollerIsPaused = false;
|
||||||
|
|
||||||
} catch (TaskCanceledException) { }
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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))
|
||||||
|
|||||||
@@ -12,13 +12,16 @@ using MewtocolNet.Logging;
|
|||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.ComponentModel;
|
using System.ComponentModel;
|
||||||
|
using System.Net;
|
||||||
|
using System.Threading;
|
||||||
|
using MewtocolNet.Queue;
|
||||||
|
|
||||||
namespace MewtocolNet {
|
namespace MewtocolNet {
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The PLC com interface class
|
/// The PLC com interface class
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public partial class MewtocolInterface : INotifyPropertyChanged {
|
public partial class MewtocolInterface : INotifyPropertyChanged, IDisposable {
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets triggered when the PLC connection was established
|
/// Gets triggered when the PLC connection was established
|
||||||
@@ -40,6 +43,40 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public event PropertyChangedEventHandler PropertyChanged;
|
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;
|
private bool isConnected;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The current connection state of the interface
|
/// The current connection state of the interface
|
||||||
@@ -52,6 +89,16 @@ namespace MewtocolNet {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool disposed;
|
||||||
|
/// <summary>
|
||||||
|
/// True if the current interface was disposed
|
||||||
|
/// </summary>
|
||||||
|
public bool Disposed {
|
||||||
|
get { return disposed; }
|
||||||
|
private set { disposed = value; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private PLCInfo plcInfo;
|
private PLCInfo plcInfo;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Generic information about the connected PLC
|
/// Generic information about the connected PLC
|
||||||
@@ -72,6 +119,10 @@ namespace MewtocolNet {
|
|||||||
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
|
||||||
@@ -86,7 +137,6 @@ namespace MewtocolNet {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public int StationNumber => stationNumber;
|
public int StationNumber => stationNumber;
|
||||||
|
|
||||||
private int cycleTimeMs;
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The duration of the last message cycle
|
/// The duration of the last message cycle
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -98,10 +148,39 @@ namespace MewtocolNet {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal List<Task> PriorityTasks { get; set; } = new List<Task>();
|
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 int SendExceptionsInRow = 0;
|
||||||
|
internal bool ImportantTaskRunning = false;
|
||||||
|
|
||||||
|
private Stopwatch speedStopwatchUpstr;
|
||||||
|
private Stopwatch speedStopwatchDownstr;
|
||||||
|
|
||||||
#region Initialization
|
#region Initialization
|
||||||
|
|
||||||
@@ -131,7 +210,6 @@ 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}) " : "")}" +
|
||||||
@@ -196,16 +274,31 @@ namespace MewtocolNet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Closes all permanent polling
|
/// 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>
|
/// </summary>
|
||||||
public void Disconnect () {
|
public void Disconnect () {
|
||||||
|
|
||||||
if (!IsConnected)
|
if (!IsConnected)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
OnMajorSocketException();
|
OnMajorSocketExceptionWhileConnected();
|
||||||
|
|
||||||
PriorityTasks.Clear();
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,6 +316,98 @@ 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();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ClearRegisterVals () {
|
||||||
|
|
||||||
|
for (int i = 0; i < Registers.Count; i++) {
|
||||||
|
|
||||||
|
var reg = Registers[i];
|
||||||
|
reg.ClearValue();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region Register Collection
|
#region Register Collection
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -335,8 +520,11 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
var bytes = BitConverter.GetBytes(reg16.Value);
|
var bytes = BitConverter.GetBytes(reg16.Value);
|
||||||
BitArray bitAr = new BitArray(bytes);
|
BitArray bitAr = new BitArray(bytes);
|
||||||
|
|
||||||
|
if (bitIndex < bitAr.Length && bitIndex >= 0) {
|
||||||
prop.SetValue(collection, bitAr[bitIndex]);
|
prop.SetValue(collection, bitAr[bitIndex]);
|
||||||
collection.TriggerPropertyChanged(prop.Name);
|
collection.TriggerPropertyChanged(prop.Name);
|
||||||
|
}
|
||||||
|
|
||||||
} else if (bitWiseFound != null && reg is NRegister<int> reg32) {
|
} else if (bitWiseFound != null && reg is NRegister<int> reg32) {
|
||||||
var casted = (RegisterAttribute)bitWiseFound;
|
var casted = (RegisterAttribute)bitWiseFound;
|
||||||
@@ -553,27 +741,14 @@ namespace MewtocolNet {
|
|||||||
_msg += "\r";
|
_msg += "\r";
|
||||||
|
|
||||||
//send request
|
//send request
|
||||||
|
try {
|
||||||
|
|
||||||
string response = null;
|
queuedMessages++;
|
||||||
|
|
||||||
if (ContinousReaderRunning) {
|
var response = await queue.Enqueue(() => SendSingleBlock(_msg));
|
||||||
|
|
||||||
//if the poller is active then add all messages to a qeueue
|
if (queuedMessages > 0)
|
||||||
|
queuedMessages--;
|
||||||
var awaittask = SendSingleBlock(_msg);
|
|
||||||
PriorityTasks.Add(awaittask);
|
|
||||||
await awaittask;
|
|
||||||
|
|
||||||
PriorityTasks.Remove(awaittask);
|
|
||||||
response = awaittask.Result;
|
|
||||||
|
|
||||||
} else {
|
|
||||||
|
|
||||||
//poller not active let the user manage message timing
|
|
||||||
|
|
||||||
response = await SendSingleBlock(_msg);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response == null) {
|
if (response == null) {
|
||||||
return new CommandResult {
|
return new CommandResult {
|
||||||
@@ -591,7 +766,7 @@ namespace MewtocolNet {
|
|||||||
string eDes = Links.LinkedData.ErrorCodes[Convert.ToInt32(eCode)];
|
string eDes = Links.LinkedData.ErrorCodes[Convert.ToInt32(eCode)];
|
||||||
Console.ForegroundColor = ConsoleColor.Red;
|
Console.ForegroundColor = ConsoleColor.Red;
|
||||||
Console.WriteLine($"Response is: {response}");
|
Console.WriteLine($"Response is: {response}");
|
||||||
Console.WriteLine($"Error on command {_msg.Replace("\r", "")} the PLC returned error code: {eCode}, {eDes}");
|
Logger.Log($"Error on command {_msg.Replace("\r", "")} the PLC returned error code: {eCode}, {eDes}", LogLevel.Error);
|
||||||
Console.ResetColor();
|
Console.ResetColor();
|
||||||
return new CommandResult {
|
return new CommandResult {
|
||||||
Success = false,
|
Success = false,
|
||||||
@@ -606,89 +781,130 @@ namespace MewtocolNet {
|
|||||||
Response = response.ToString()
|
Response = response.ToString()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
} catch {
|
||||||
|
return new CommandResult {
|
||||||
|
Success = false,
|
||||||
|
Error = "0000",
|
||||||
|
ErrorDescription = "null result"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<string> SendSingleBlock (string _blockString) {
|
private async Task<string> SendSingleBlock (string _blockString) {
|
||||||
|
|
||||||
Stopwatch sw = Stopwatch.StartNew();
|
if (client == null || !client.Connected ) {
|
||||||
|
await ConnectTCP();
|
||||||
|
}
|
||||||
|
|
||||||
using (TcpClient client = new TcpClient() { ReceiveBufferSize = 64, NoDelay = true, ExclusiveAddressUse = true }) {
|
if (client == null || !client.Connected)
|
||||||
|
return null;
|
||||||
try {
|
|
||||||
|
|
||||||
await client.ConnectAsync(ip, port);
|
|
||||||
|
|
||||||
using (NetworkStream stream = client.GetStream()) {
|
|
||||||
|
|
||||||
var message = _blockString.ToHexASCIIBytes();
|
var message = _blockString.ToHexASCIIBytes();
|
||||||
var messageAscii = BitConverter.ToString(message).Replace("-", " ");
|
|
||||||
|
//time measuring
|
||||||
|
if(speedStopwatchUpstr == null) {
|
||||||
|
speedStopwatchUpstr = Stopwatch.StartNew();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(speedStopwatchUpstr.Elapsed.TotalSeconds >= 1) {
|
||||||
|
speedStopwatchUpstr.Restart();
|
||||||
|
bytesTotalCountedUpstream = 0;
|
||||||
|
}
|
||||||
|
|
||||||
//send request
|
//send request
|
||||||
try {
|
|
||||||
using (var sendStream = new MemoryStream(message)) {
|
using (var sendStream = new MemoryStream(message)) {
|
||||||
await sendStream.CopyToAsync(stream);
|
await sendStream.CopyToAsync(stream);
|
||||||
Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this);
|
Logger.Log($"[--------------------------------]", LogLevel.Critical, this);
|
||||||
//log message sent
|
Logger.Log($"--> OUT MSG: {_blockString}", LogLevel.Critical, this);
|
||||||
ASCIIEncoding enc = new ASCIIEncoding();
|
|
||||||
string characters = enc.GetString(message);
|
|
||||||
}
|
|
||||||
} catch (IOException) {
|
|
||||||
Logger.Log($"Critical IO exception on send", LogLevel.Critical, this);
|
|
||||||
return null;
|
|
||||||
} catch (SocketException) {
|
|
||||||
OnMajorSocketException();
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//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
|
//await result
|
||||||
StringBuilder response = new StringBuilder();
|
StringBuilder response = new StringBuilder();
|
||||||
try {
|
try {
|
||||||
byte[] responseBuffer = new byte[256];
|
|
||||||
|
byte[] responseBuffer = new byte[128 * 16];
|
||||||
|
|
||||||
|
bool endLineCode = false;
|
||||||
|
bool startMsgCode = false;
|
||||||
|
|
||||||
|
while (!endLineCode && !startMsgCode) {
|
||||||
|
|
||||||
do {
|
do {
|
||||||
int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length);
|
|
||||||
|
//time measuring
|
||||||
|
if (speedStopwatchDownstr == null) {
|
||||||
|
speedStopwatchDownstr = Stopwatch.StartNew();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (speedStopwatchDownstr.Elapsed.TotalSeconds >= 1) {
|
||||||
|
speedStopwatchDownstr.Restart();
|
||||||
|
bytesTotalCountedDownstream = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int bytes = await stream.ReadAsync(responseBuffer, 0, responseBuffer.Length);
|
||||||
|
|
||||||
|
endLineCode = responseBuffer.Any(x => x == 0x0D);
|
||||||
|
startMsgCode = responseBuffer.Count(x => x == 0x25) > 1;
|
||||||
|
|
||||||
|
if (!endLineCode && !startMsgCode) break;
|
||||||
|
|
||||||
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
|
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
|
||||||
}
|
}
|
||||||
while (stream.DataAvailable);
|
while (stream.DataAvailable);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
} catch (IOException) {
|
} catch (IOException) {
|
||||||
Logger.Log($"Critical IO exception on receive", LogLevel.Critical, this);
|
OnMajorSocketExceptionWhileConnected();
|
||||||
return null;
|
return null;
|
||||||
} catch (SocketException) {
|
} catch (SocketException) {
|
||||||
OnMajorSocketException();
|
OnMajorSocketExceptionWhileConnected();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
sw.Stop();
|
if(!string.IsNullOrEmpty(response.ToString())) {
|
||||||
var curCycle = (int)sw.ElapsedMilliseconds;
|
|
||||||
if (Math.Abs(CycleTimeMs - curCycle) > 2) {
|
Logger.Log($"<-- IN MSG: {response}", LogLevel.Critical, this);
|
||||||
CycleTimeMs = curCycle;
|
|
||||||
}
|
bytesTotalCountedDownstream += Encoding.ASCII.GetByteCount(response.ToString());
|
||||||
|
|
||||||
|
var perSecDownstream = (double)((bytesTotalCountedDownstream / speedStopwatchDownstr.Elapsed.TotalMilliseconds) * 1000);
|
||||||
|
|
||||||
|
if(perSecUpstream <= 10000)
|
||||||
|
BytesPerSecondDownstream = (int)Math.Round(perSecUpstream, MidpointRounding.AwayFromZero);
|
||||||
|
|
||||||
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {response}", LogLevel.Critical, this);
|
|
||||||
return response.ToString();
|
return response.ToString();
|
||||||
}
|
|
||||||
|
|
||||||
} catch (SocketException) {
|
} else {
|
||||||
|
|
||||||
OnMajorSocketException();
|
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
#endregion
|
||||||
|
|
||||||
private void OnMajorSocketException () {
|
#region Disposing
|
||||||
|
|
||||||
if (IsConnected) {
|
/// <summary>
|
||||||
|
/// Disposes the current interface and clears all its members
|
||||||
|
/// </summary>
|
||||||
|
public void Dispose () {
|
||||||
|
|
||||||
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
|
if (Disposed) return;
|
||||||
CycleTimeMs = 0;
|
|
||||||
IsConnected = false;
|
|
||||||
Disconnected?.Invoke();
|
|
||||||
KillPoller();
|
|
||||||
|
|
||||||
}
|
Disconnect();
|
||||||
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
|
||||||
|
Disposed = true;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -709,4 +925,5 @@ namespace MewtocolNet {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -112,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) {
|
||||||
|
|
||||||
|
var byteList = new List<byte>();
|
||||||
|
|
||||||
string startStr = start.ToString().PadLeft(5, '0');
|
|
||||||
var wordLength = count / 2;
|
var wordLength = count / 2;
|
||||||
bool wasOdd = false;
|
|
||||||
if (count % 2 != 0)
|
if (count % 2 != 0)
|
||||||
wordLength++;
|
wordLength++;
|
||||||
|
|
||||||
string endStr = (start + wordLength - 1).ToString().PadLeft(5, '0');
|
|
||||||
|
//read blocks of max 4 words per msg
|
||||||
|
for (int i = 0; i < wordLength; i+=8) {
|
||||||
|
|
||||||
|
int curWordStart = start + i;
|
||||||
|
int curWordEnd = curWordStart + 7;
|
||||||
|
|
||||||
|
string startStr = curWordStart.ToString().PadLeft(5, '0');
|
||||||
|
string endStr = (curWordEnd).ToString().PadLeft(5, '0');
|
||||||
|
|
||||||
string requeststring = $"%{GetStationNumber()}#RDD{startStr}{endStr}";
|
string requeststring = $"%{GetStationNumber()}#RDD{startStr}{endStr}";
|
||||||
var result = await SendCommandAsync(requeststring);
|
var result = await SendCommandAsync(requeststring);
|
||||||
|
|
||||||
if(result.Success && !string.IsNullOrEmpty(result.Response)) {
|
if (result.Success && !string.IsNullOrEmpty(result.Response)) {
|
||||||
|
|
||||||
var bytes = result.Response.ParseDTByteString(wordLength * 4).HexStringToByteArray();
|
var bytes = result.Response.ParseDTByteString(8 * 4).HexStringToByteArray();
|
||||||
|
|
||||||
return bytes.BigToMixedEndian().Take(count).ToArray();
|
if (bytes == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
byteList.AddRange(bytes.BigToMixedEndian().Take(count).ToArray());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
if(onProgress != null)
|
||||||
|
onProgress((double)i / wordLength);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return byteList.ToArray();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,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) {
|
||||||
|
|
||||||
@@ -196,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) {
|
||||||
|
|
||||||
@@ -205,40 +223,47 @@ namespace MewtocolNet {
|
|||||||
string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolIdent()}";
|
string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolIdent()}";
|
||||||
var result = await SendCommandAsync(requeststring);
|
var result = await SendCommandAsync(requeststring);
|
||||||
|
|
||||||
if(!result.Success || string.IsNullOrEmpty(result.Response)) {
|
var failedResult = new NRegisterResult<T> {
|
||||||
return new NRegisterResult<T> {
|
|
||||||
Result = result,
|
Result = result,
|
||||||
Register = _toRead
|
Register = _toRead
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (!result.Success || string.IsNullOrEmpty(result.Response)) {
|
||||||
|
return failedResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (numType == typeof(short)) {
|
if (numType == typeof(short)) {
|
||||||
|
|
||||||
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
||||||
|
if (resultBytes == null) return failedResult;
|
||||||
var val = short.Parse(resultBytes, NumberStyles.HexNumber);
|
var val = short.Parse(resultBytes, NumberStyles.HexNumber);
|
||||||
_toRead.SetValueFromPLC(val);
|
_toRead.SetValueFromPLC(val);
|
||||||
|
|
||||||
} else if (numType == typeof(ushort)) {
|
} else if (numType == typeof(ushort)) {
|
||||||
|
|
||||||
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
||||||
|
if (resultBytes == null) return failedResult;
|
||||||
var val = ushort.Parse(resultBytes, NumberStyles.HexNumber);
|
var val = ushort.Parse(resultBytes, NumberStyles.HexNumber);
|
||||||
_toRead.SetValueFromPLC(val);
|
_toRead.SetValueFromPLC(val);
|
||||||
|
|
||||||
} else if (numType == typeof(int)) {
|
} else if (numType == typeof(int)) {
|
||||||
|
|
||||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||||
|
if (resultBytes == null) return failedResult;
|
||||||
var val = int.Parse(resultBytes, NumberStyles.HexNumber);
|
var val = int.Parse(resultBytes, NumberStyles.HexNumber);
|
||||||
_toRead.SetValueFromPLC(val);
|
_toRead.SetValueFromPLC(val);
|
||||||
|
|
||||||
} else if (numType == typeof(uint)) {
|
} else if (numType == typeof(uint)) {
|
||||||
|
|
||||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||||
|
if (resultBytes == null) return failedResult;
|
||||||
var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
|
var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
|
||||||
_toRead.SetValueFromPLC(val);
|
_toRead.SetValueFromPLC(val);
|
||||||
|
|
||||||
} else if (numType == typeof(float)) {
|
} else if (numType == typeof(float)) {
|
||||||
|
|
||||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||||
|
if (resultBytes == null) return failedResult;
|
||||||
//convert to unsigned int first
|
//convert to unsigned int first
|
||||||
var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
|
var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
|
||||||
|
|
||||||
@@ -250,6 +275,7 @@ namespace MewtocolNet {
|
|||||||
} else if (numType == typeof(TimeSpan)) {
|
} else if (numType == typeof(TimeSpan)) {
|
||||||
|
|
||||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||||
|
if (resultBytes == null) return failedResult;
|
||||||
//convert to unsigned int first
|
//convert to unsigned int first
|
||||||
var vallong = long.Parse(resultBytes, NumberStyles.HexNumber);
|
var vallong = long.Parse(resultBytes, NumberStyles.HexNumber);
|
||||||
var valMillis = vallong * 10;
|
var valMillis = vallong * 10;
|
||||||
@@ -273,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) {
|
||||||
|
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
@@ -34,8 +34,17 @@ namespace MewtocolNet.RegisterAttributes {
|
|||||||
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) { }
|
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) { }
|
public virtual void OnInterfaceLinkedAndOnline (MewtocolInterface plc) { }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,7 @@ namespace MewtocolNet.Registers {
|
|||||||
internal RegisterType RegType { get; private set; }
|
internal RegisterType RegType { get; private set; }
|
||||||
internal SpecialAddress SpecialAddress { get; private 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
|
||||||
@@ -54,6 +53,9 @@ namespace MewtocolNet.Registers {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <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
|
||||||
@@ -73,9 +75,7 @@ namespace MewtocolNet.Registers {
|
|||||||
TriggerChangedEvnt(this);
|
TriggerChangedEvnt(this);
|
||||||
TriggerNotifyChange();
|
TriggerNotifyChange();
|
||||||
}
|
}
|
||||||
public override string ToString() {
|
|
||||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,8 +7,7 @@ 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
|
||||||
@@ -78,10 +77,6 @@ namespace MewtocolNet.Registers {
|
|||||||
TriggerNotifyChange();
|
TriggerNotifyChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() {
|
|
||||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,13 +6,16 @@ namespace MewtocolNet.Registers {
|
|||||||
/// </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> {
|
||||||
public CommandResult Result { get; set; }
|
|
||||||
public NRegister<T> Register { get; set; }
|
|
||||||
|
|
||||||
public override string ToString() {
|
/// <summary>
|
||||||
string errmsg = Result.Success ? "" : $", Error [{Result.ErrorDescription}]";
|
/// Command result
|
||||||
return $"Result [{Result.Success}], Register [{Register.ToString()}]{errmsg}";
|
/// </summary>
|
||||||
}
|
public CommandResult Result { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The used register
|
||||||
|
/// </summary>
|
||||||
|
public NRegister<T> Register { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Trys to get the value of there is one
|
/// Trys to get the value of there is one
|
||||||
|
|||||||
@@ -75,6 +75,9 @@ namespace MewtocolNet.Registers {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <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");
|
||||||
@@ -91,6 +94,38 @@ namespace MewtocolNet.Registers {
|
|||||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal void ClearValue () {
|
||||||
|
|
||||||
|
if (enumType != null && this is NRegister<int> intEnumReg) {
|
||||||
|
intEnumReg.SetValueFromPLC((int)0);
|
||||||
|
}
|
||||||
|
if (this is NRegister<short> shortReg) {
|
||||||
|
shortReg.SetValueFromPLC((short)0);
|
||||||
|
}
|
||||||
|
if (this is NRegister<ushort> ushortReg) {
|
||||||
|
ushortReg.SetValueFromPLC((ushort)0);
|
||||||
|
}
|
||||||
|
if (this is NRegister<int> intReg) {
|
||||||
|
intReg.SetValueFromPLC((int)0);
|
||||||
|
}
|
||||||
|
if (this is NRegister<uint> uintReg) {
|
||||||
|
uintReg.SetValueFromPLC((uint)0);
|
||||||
|
}
|
||||||
|
if (this is NRegister<float> floatReg) {
|
||||||
|
floatReg.SetValueFromPLC((float)0);
|
||||||
|
}
|
||||||
|
if (this is NRegister<TimeSpan> tsReg) {
|
||||||
|
tsReg.SetValueFromPLC(TimeSpan.Zero);
|
||||||
|
}
|
||||||
|
if (this is BRegister boolReg) {
|
||||||
|
boolReg.SetValueFromPLC(false);
|
||||||
|
}
|
||||||
|
if (this is SRegister stringReg) {
|
||||||
|
stringReg.SetValueFromPLC(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the starting memory are either numeric or A,B,C,D etc for special areas like inputs
|
/// Gets the starting memory are either numeric or A,B,C,D etc for special areas like inputs
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -112,9 +147,14 @@ namespace MewtocolNet.Registers {
|
|||||||
public string GetValueString () {
|
public string GetValueString () {
|
||||||
|
|
||||||
if (enumType != null && this is NRegister<int> intEnumReg) {
|
if (enumType != null && this is NRegister<int> intEnumReg) {
|
||||||
|
|
||||||
var dict = new Dictionary<int, string>();
|
var dict = new Dictionary<int, string>();
|
||||||
|
|
||||||
foreach (var name in Enum.GetNames(enumType)) {
|
foreach (var name in Enum.GetNames(enumType)) {
|
||||||
dict.Add((int)Enum.Parse(enumType, name), name);
|
int enumKey = (int)Enum.Parse(enumType, name);
|
||||||
|
if(!dict.ContainsKey(enumKey)) {
|
||||||
|
dict.Add(enumKey, name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(dict.ContainsKey(intEnumReg.Value)) {
|
if(dict.ContainsKey(intEnumReg.Value)) {
|
||||||
@@ -122,6 +162,7 @@ namespace MewtocolNet.Registers {
|
|||||||
} else {
|
} else {
|
||||||
return $"{intEnumReg.Value} (Missing Enum)";
|
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()}]" : "")}";
|
||||||
@@ -145,7 +186,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.";
|
||||||
@@ -178,6 +219,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) {
|
||||||
|
|||||||
@@ -9,9 +9,12 @@ namespace MewtocolNet.Registers {
|
|||||||
|
|
||||||
private string lastVal = "";
|
private string lastVal = "";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The current value of the register
|
||||||
|
/// </summary>
|
||||||
public string Value => lastVal;
|
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
|
||||||
@@ -32,10 +35,9 @@ namespace MewtocolNet.Registers {
|
|||||||
memoryLength = (int)Math.Round(wordsize + 1);
|
memoryLength = (int)Math.Round(wordsize + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() {
|
/// <summary>
|
||||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
/// 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");
|
||||||
@@ -65,7 +67,6 @@ namespace MewtocolNet.Registers {
|
|||||||
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}";
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>netstandard2.0</TargetFramework>
|
<TargetFramework>netstandard2.0</TargetFramework>
|
||||||
<PackageId>MewtocolNet</PackageId>
|
<PackageId>Mewtocol.NET</PackageId>
|
||||||
<Version>0.4.3</Version>
|
<Version>0.6.2</Version>
|
||||||
<Authors>Felix Weiss</Authors>
|
<Authors>Felix Weiss</Authors>
|
||||||
<Company>Womed</Company>
|
<Company>Womed</Company>
|
||||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
|
|||||||
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
@@ -1,7 +1,6 @@
|
|||||||
[](https://github.com/WOmed/MewtocolNet/actions/workflows/dotnet-windows.yml)
|
[](https://github.com/WOmed/MewtocolNet/actions/workflows/publish.yml)
|
||||||

|
[](https://www.nuget.org/packages/Mewtocol.NET)
|
||||||

|

|
||||||

|
|
||||||

|

|
||||||

|

|
||||||
|
|
||||||
@@ -28,7 +27,7 @@ This software was written by WOLF Medizintechnik GmbH (@WOmed/dev).
|
|||||||
|
|
||||||
## .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)
|
||||||
|
|
||||||
@@ -51,14 +50,14 @@ Where is the RS232/Serial support?
|
|||||||
|
|
||||||
# Installing
|
# Installing
|
||||||
|
|
||||||
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/Mewtocol.NET) or reference
|
||||||
```XML
|
```XML
|
||||||
<PackageReference Include="MewtocolNet" Version="0.4.2" />
|
<PackageReference Include="Mewtocol.NET" Version="0.6.1"/>
|
||||||
```
|
```
|
||||||
in your dependencies.
|
in your dependencies.
|
||||||
Alternatively use the dotnet CLI and run
|
Alternatively use the dotnet CLI and run
|
||||||
```Shell
|
```Shell
|
||||||
dotnet add package MewtocolNet
|
dotnet add package Mewtocol.NET
|
||||||
```
|
```
|
||||||
|
|
||||||
# Protocol description
|
# Protocol description
|
||||||
|
|||||||
Reference in New Issue
Block a user