mirror of
https://github.com/OpenLogics/MewtocolNet.git
synced 2025-12-06 11:11:23 +00:00
Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18384ff964 | ||
|
|
e4ddad685a | ||
|
|
e953938a65 | ||
|
|
83f17a4eae | ||
|
|
4c719843f2 | ||
|
|
8f9e66d5d3 | ||
|
|
5cc222abcc | ||
|
|
14659ffaad | ||
|
|
ea106416ee | ||
|
|
0afa146712 | ||
|
|
325aa56d8a | ||
|
|
f4fad297fb | ||
|
|
664b32b92e | ||
|
|
a639a8eda8 | ||
|
|
23c2b0efb4 | ||
|
|
eed19f84d7 | ||
|
|
da90a45e15 | ||
|
|
614426207c | ||
|
|
3aa8aa227c | ||
|
|
26c0e9add0 | ||
|
|
4a63fb10bd | ||
|
|
881253130b | ||
|
|
3a5cdb11c2 |
23
.github/workflows/dotnet-windows.yml
vendored
Normal file
23
.github/workflows/dotnet-windows.yml
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
name: .NET Windows
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
matrix:
|
||||
dotnet-version: [ '3.0', '3.1.x', '5.0.x' ]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Setup dotnet ${{ matrix.dotnet-version }}
|
||||
uses: actions/setup-dotnet@v2
|
||||
with:
|
||||
dotnet-version: ${{ matrix.dotnet-version }}
|
||||
# You can test your matrix by printing the current dotnet version
|
||||
- name: Display dotnet version
|
||||
run: dotnet --version
|
||||
@@ -2,6 +2,7 @@
|
||||
using System.Threading.Tasks;
|
||||
using MewtocolNet;
|
||||
using MewtocolNet.Logging;
|
||||
using MewtocolNet.Registers;
|
||||
|
||||
namespace Examples {
|
||||
|
||||
@@ -29,14 +30,15 @@ namespace Examples {
|
||||
|
||||
//reading a value from the register collection
|
||||
Console.WriteLine($"BitValue is: {registers.BitValue}");
|
||||
Console.WriteLine($"TestEnum is: {registers.TestEnum}");
|
||||
|
||||
//writing a value to the registers
|
||||
Task.Factory.StartNew(async () => {
|
||||
|
||||
await Task.Delay(2000);
|
||||
//set plc to run mode if not already
|
||||
await interf.SetOperationMode(OPMode.Run);
|
||||
|
||||
//inverts the boolean register
|
||||
await interf.SetRegisterAsync(nameof(registers.TestBool1), !registers.TestBool1);
|
||||
await Task.Delay(2000);
|
||||
|
||||
Console.WriteLine("Testregister was toggled");
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace Examples {
|
||||
public class TestRegisters : RegisterCollectionBase {
|
||||
|
||||
//corresponds to a R100 boolean register in the PLC
|
||||
[Register(100, RegisterType.R)]
|
||||
[Register(1000, RegisterType.R)]
|
||||
public bool TestBool1 { get; private set; }
|
||||
|
||||
//corresponds to a XD input of the PLC
|
||||
@@ -42,11 +42,29 @@ namespace Examples {
|
||||
[Register(1204, 9, BitCount.B16)]
|
||||
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)
|
||||
//the smallest value to communicate to the PLC is 10ms
|
||||
[Register(7012)]
|
||||
public TimeSpan TestTime { get; private set; }
|
||||
|
||||
public enum CurrentState {
|
||||
Undefined = 0,
|
||||
State1 = 1,
|
||||
State2 = 2,
|
||||
//State3 = 3,
|
||||
State4 = 4,
|
||||
State5 = 5,
|
||||
StateBetween = 100,
|
||||
State6 = 6,
|
||||
State7 = 7,
|
||||
}
|
||||
|
||||
[Register(50)]
|
||||
public CurrentState TestEnum { get; private set; }
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,7 @@
|
||||
using System;
|
||||
|
||||
namespace MewtocolNet.Registers {
|
||||
public class CpuInfo {
|
||||
/// <summary>
|
||||
/// CPU type of the PLC
|
||||
/// </summary>
|
||||
public enum CpuType {
|
||||
/// <summary>
|
||||
/// FP 0 / FP 2.7K
|
||||
/// </summary>
|
||||
FP0_FP1_2_7K,
|
||||
/// <summary>
|
||||
/// FP0 / FP1, 5K / 10K
|
||||
/// </summary>
|
||||
FP0_FP1_5K_10K,
|
||||
/// <summary>
|
||||
/// FP1 M 0.9K
|
||||
/// </summary>
|
||||
FP1_M_0_9K,
|
||||
/// <summary>
|
||||
/// FP2 16k / 32k
|
||||
/// </summary>
|
||||
FP2_16K_32K,
|
||||
/// <summary>
|
||||
/// FP3 C 10K
|
||||
/// </summary>
|
||||
FP3_C_10K,
|
||||
/// <summary>
|
||||
/// FP3 C 16K
|
||||
/// </summary>
|
||||
FP3_C_16K,
|
||||
/// <summary>
|
||||
/// FP5 16K
|
||||
/// </summary>
|
||||
FP5_16K,
|
||||
/// <summary>
|
||||
/// FP 5 24K
|
||||
/// </summary>
|
||||
FP5_24K,
|
||||
/// <summary>
|
||||
/// Includes panasonic FPX, FPX-H, Sigma
|
||||
/// </summary>
|
||||
FP_Sigma_X_H_30K_60K_120K
|
||||
|
||||
}
|
||||
public partial class CpuInfo {
|
||||
|
||||
public CpuType Cputype { get; set; }
|
||||
public int ProgramCapacity { get; set; }
|
||||
|
||||
@@ -24,7 +24,7 @@ namespace MewtocolNet {
|
||||
internal void KillPoller () {
|
||||
|
||||
ContinousReaderRunning = false;
|
||||
cTokenAutoUpdater.Cancel();
|
||||
cTokenAutoUpdater?.Cancel();
|
||||
|
||||
}
|
||||
|
||||
@@ -71,12 +71,21 @@ namespace MewtocolNet {
|
||||
|
||||
ContinousReaderRunning = true;
|
||||
|
||||
int getPLCinfoCycleCount = 0;
|
||||
|
||||
while (ContinousReaderRunning) {
|
||||
|
||||
//do priority tasks first
|
||||
if (PriorityTasks.Count > 0) {
|
||||
if (PriorityTasks != null && PriorityTasks.Count > 0) {
|
||||
|
||||
await PriorityTasks.FirstOrDefault(x => !x.IsCompleted);
|
||||
try {
|
||||
await PriorityTasks?.FirstOrDefault(x => !x.IsCompleted);
|
||||
} catch (NullReferenceException) { }
|
||||
|
||||
} else if (getPLCinfoCycleCount > 25) {
|
||||
|
||||
await GetPLCInfoAsync();
|
||||
getPLCinfoCycleCount = 0;
|
||||
|
||||
}
|
||||
|
||||
@@ -86,79 +95,66 @@ namespace MewtocolNet {
|
||||
|
||||
if (reg is NRegister<short> shortReg) {
|
||||
var lastVal = shortReg.Value;
|
||||
var readout = (await ReadNumRegister(shortReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadNumRegister(shortReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
shortReg.LastValue = readout;
|
||||
InvokeRegisterChanged(shortReg);
|
||||
shortReg.TriggerNotifyChange();
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<ushort> ushortReg) {
|
||||
var lastVal = ushortReg.Value;
|
||||
var readout = (await ReadNumRegister(ushortReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadNumRegister(ushortReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
ushortReg.LastValue = readout;
|
||||
InvokeRegisterChanged(ushortReg);
|
||||
ushortReg.TriggerNotifyChange();
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<int> intReg) {
|
||||
var lastVal = intReg.Value;
|
||||
var readout = (await ReadNumRegister(intReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadNumRegister(intReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
intReg.LastValue = readout;
|
||||
InvokeRegisterChanged(intReg);
|
||||
intReg.TriggerNotifyChange();
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<uint> uintReg) {
|
||||
var lastVal = uintReg.Value;
|
||||
var readout = (await ReadNumRegister(uintReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadNumRegister(uintReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
uintReg.LastValue = readout;
|
||||
InvokeRegisterChanged(uintReg);
|
||||
uintReg.TriggerNotifyChange();
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<float> floatReg) {
|
||||
var lastVal = floatReg.Value;
|
||||
var readout = (await ReadNumRegister(floatReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadNumRegister(floatReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
floatReg.LastValue = readout;
|
||||
InvokeRegisterChanged(floatReg);
|
||||
floatReg.TriggerNotifyChange();
|
||||
}
|
||||
}
|
||||
if (reg is NRegister<TimeSpan> tsReg) {
|
||||
var lastVal = tsReg.Value;
|
||||
var readout = (await ReadNumRegister(tsReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadNumRegister(tsReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
tsReg.LastValue = readout;
|
||||
InvokeRegisterChanged(tsReg);
|
||||
tsReg.TriggerNotifyChange();
|
||||
}
|
||||
}
|
||||
if (reg is BRegister boolReg) {
|
||||
var lastVal = boolReg.Value;
|
||||
var readout = (await ReadBoolRegister(boolReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadBoolRegister(boolReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
boolReg.LastValue = readout;
|
||||
InvokeRegisterChanged(boolReg);
|
||||
boolReg.TriggerNotifyChange();
|
||||
}
|
||||
}
|
||||
if (reg is SRegister stringReg) {
|
||||
var lastVal = stringReg.Value;
|
||||
var readout = (await ReadStringRegister(stringReg, stationNumber)).Register.Value;
|
||||
var readout = (await ReadStringRegister(stringReg)).Register.Value;
|
||||
if (lastVal != readout) {
|
||||
InvokeRegisterChanged(stringReg);
|
||||
stringReg.TriggerNotifyChange();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
getPLCinfoCycleCount++;
|
||||
|
||||
//invoke cycle polled event
|
||||
InvokePolledCycleDone();
|
||||
|
||||
@@ -191,30 +187,60 @@ namespace MewtocolNet {
|
||||
/// <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) {
|
||||
|
||||
Register toAdd = null;
|
||||
|
||||
//as number registers
|
||||
if (_type == RegisterType.DT_short) {
|
||||
Registers.Add(_address, new NRegister<short>(_address, _name));
|
||||
return;
|
||||
toAdd = new NRegister<short>(_address, _name);
|
||||
}
|
||||
if (_type == RegisterType.DT_ushort) {
|
||||
Registers.Add(_address, new NRegister<ushort>(_address, _name));
|
||||
return;
|
||||
toAdd = new NRegister<ushort>(_address, _name);
|
||||
}
|
||||
if (_type == RegisterType.DDT_int) {
|
||||
Registers.Add(_address, new NRegister<int>(_address, _name));
|
||||
return;
|
||||
toAdd = new NRegister<int>(_address, _name);
|
||||
}
|
||||
if (_type == RegisterType.DDT_uint) {
|
||||
Registers.Add(_address, new NRegister<uint>(_address, _name));
|
||||
return;
|
||||
toAdd = new NRegister<uint>(_address, _name);
|
||||
}
|
||||
if (_type == RegisterType.DDT_float) {
|
||||
Registers.Add(_address, new NRegister<float>(_address, _name));
|
||||
return;
|
||||
toAdd = new NRegister<float>(_address, _name);
|
||||
}
|
||||
|
||||
//as bool registers
|
||||
Registers.Add(_address, new BRegister(_address, _type, _name));
|
||||
if(toAdd == null) {
|
||||
toAdd = new BRegister(_address, _type, _name);
|
||||
}
|
||||
|
||||
Registers.Add(_address, 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(_address, toAdd);
|
||||
|
||||
}
|
||||
|
||||
@@ -239,6 +265,17 @@ namespace MewtocolNet {
|
||||
|
||||
}
|
||||
|
||||
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((int)_spAddress, reg);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a PLC memory register to the watchlist <para/>
|
||||
/// The registers can be read back by attaching <see cref="WithPoller"/>
|
||||
@@ -256,7 +293,7 @@ namespace MewtocolNet {
|
||||
/// <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="_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);
|
||||
|
||||
@@ -265,18 +302,16 @@ namespace MewtocolNet {
|
||||
}
|
||||
|
||||
if (Registers.Any(x => x.Key == _address)) {
|
||||
|
||||
throw new NotSupportedException($"Cannot add a register multiple times, " +
|
||||
$"make sure that all register attributes or AddRegister assignments have different adresses.");
|
||||
|
||||
}
|
||||
|
||||
if (regType == typeof(short)) {
|
||||
Registers.Add(_address, new NRegister<short>(_address, _name, _isBitwise));
|
||||
Registers.Add(_address, new NRegister<short>(_address, _name));
|
||||
} else if (regType == typeof(ushort)) {
|
||||
Registers.Add(_address, new NRegister<ushort>(_address, _name));
|
||||
} else if (regType == typeof(int)) {
|
||||
Registers.Add(_address, new NRegister<int>(_address, _name, _isBitwise));
|
||||
Registers.Add(_address, new NRegister<int>(_address, _name));
|
||||
} else if (regType == typeof(uint)) {
|
||||
Registers.Add(_address, new NRegister<uint>(_address, _name));
|
||||
} else if (regType == typeof(float)) {
|
||||
@@ -294,6 +329,56 @@ namespace MewtocolNet {
|
||||
|
||||
}
|
||||
|
||||
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.Key == _address) && !_isBitwise) {
|
||||
throw new NotSupportedException($"Cannot add a register multiple times, " +
|
||||
$"make sure that all register attributes or AddRegister assignments have different adresses.");
|
||||
}
|
||||
|
||||
if (Registers.Any(x => x.Key == _address) && _isBitwise) {
|
||||
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 {
|
||||
|
||||
reg.collectionType = _colType;
|
||||
|
||||
Registers.Add(_address, reg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Register accessing
|
||||
|
||||
@@ -159,19 +159,42 @@ namespace MewtocolNet {
|
||||
|
||||
internal static byte[] HexStringToByteArray(this string hex) {
|
||||
return Enumerable.Range(0, hex.Length)
|
||||
.Where(x => x % 2 == 0)
|
||||
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
|
||||
.ToArray();
|
||||
.Where(x => x % 2 == 0)
|
||||
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
internal static string ToHexString (this byte[] arr) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
foreach (var b in arr) {
|
||||
for (int i = 0; i < arr.Length; i++) {
|
||||
byte b = arr[i];
|
||||
sb.Append(b.ToString("X2"));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
internal static byte[] BigToMixedEndian (this byte[] arr) {
|
||||
|
||||
List<byte> oldBL = new List<byte>(arr);
|
||||
|
||||
List<byte> tempL = new List<byte>();
|
||||
|
||||
//make the input list even
|
||||
if(arr.Length % 2 != 0)
|
||||
oldBL.Add((byte)0);
|
||||
|
||||
for (int i = 0; i < oldBL.Count; i+=2) {
|
||||
byte firstByte = oldBL[i];
|
||||
byte lastByte = oldBL[i + 1];
|
||||
tempL.Add(lastByte);
|
||||
tempL.Add(firstByte);
|
||||
|
||||
}
|
||||
|
||||
return tempL.ToArray();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -11,33 +11,58 @@ using MewtocolNet.RegisterAttributes;
|
||||
using MewtocolNet.Logging;
|
||||
using System.Collections;
|
||||
using System.Diagnostics;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace MewtocolNet {
|
||||
|
||||
/// <summary>
|
||||
/// The PLC com interface class
|
||||
/// </summary>
|
||||
public partial class MewtocolInterface {
|
||||
public partial class MewtocolInterface : INotifyPropertyChanged {
|
||||
|
||||
/// <summary>
|
||||
/// Gets triggered when the PLC connection was established
|
||||
/// </summary>
|
||||
public event Action<PLCInfo> Connected;
|
||||
|
||||
/// <summary>
|
||||
/// Gets triggered when the PLC connection was closed or lost
|
||||
/// </summary>
|
||||
public event Action Disconnected;
|
||||
|
||||
/// <summary>
|
||||
/// Gets triggered when a registered data register changes its value
|
||||
/// </summary>
|
||||
public event Action<Register> RegisterChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets triggered when a property of the interface changes
|
||||
/// </summary>
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
|
||||
private bool isConnected;
|
||||
/// <summary>
|
||||
/// The current connection state of the interface
|
||||
/// </summary>
|
||||
public bool IsConnected { get; private set; }
|
||||
public bool IsConnected {
|
||||
get => isConnected;
|
||||
private set {
|
||||
isConnected = value;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnected)));
|
||||
}
|
||||
}
|
||||
|
||||
private PLCInfo plcInfo;
|
||||
/// <summary>
|
||||
/// Generic information about the connected PLC
|
||||
/// </summary>
|
||||
public PLCInfo PlcInfo { get; private set; }
|
||||
public PLCInfo PlcInfo {
|
||||
get => plcInfo;
|
||||
private set {
|
||||
plcInfo = value;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PlcInfo)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The registered data registers of the PLC
|
||||
@@ -61,8 +86,23 @@ namespace MewtocolNet {
|
||||
/// </summary>
|
||||
public int StationNumber => stationNumber;
|
||||
|
||||
private int cycleTimeMs;
|
||||
/// <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)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal List<Task> PriorityTasks { get; set; } = new List<Task>();
|
||||
|
||||
internal int SendExceptionsInRow = 0;
|
||||
|
||||
#region Initialization
|
||||
|
||||
/// <summary>
|
||||
@@ -90,7 +130,8 @@ namespace MewtocolNet {
|
||||
|
||||
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} " +
|
||||
$"{(o.Name != null ? $"({o.Name}) " : "")}" +
|
||||
@@ -115,6 +156,8 @@ namespace MewtocolNet {
|
||||
/// <returns></returns>
|
||||
public async Task<MewtocolInterface> ConnectAsync (Action<PLCInfo> OnConnected = null, Action OnFailed = null) {
|
||||
|
||||
Logger.Log("Connecting to PLC...", LogLevel.Info, this);
|
||||
|
||||
var plcinf = await GetPLCInfoAsync();
|
||||
|
||||
if (plcinf != null) {
|
||||
@@ -142,6 +185,7 @@ namespace MewtocolNet {
|
||||
|
||||
if (OnFailed != null) {
|
||||
OnFailed();
|
||||
Disconnected?.Invoke();
|
||||
Logger.Log("Initial connection failed", LogLevel.Info, this);
|
||||
}
|
||||
|
||||
@@ -188,47 +232,51 @@ namespace MewtocolNet {
|
||||
string propName = prop.Name;
|
||||
foreach (var attr in attributes) {
|
||||
|
||||
if(attr is RegisterAttribute cAttribute) {
|
||||
if (attr is RegisterAttribute cAttribute) {
|
||||
|
||||
if (prop.PropertyType == typeof(bool) && cAttribute.AssignedBitIndex == -1) {
|
||||
if (cAttribute.SpecialAddress == SpecialAddress.None) {
|
||||
AddRegister(cAttribute.MemoryArea, cAttribute.RegisterType, _name: propName);
|
||||
AddRegister(collection.GetType(), cAttribute.MemoryArea, cAttribute.RegisterType, _name: propName);
|
||||
} else {
|
||||
AddRegister(cAttribute.SpecialAddress, cAttribute.RegisterType, _name: propName);
|
||||
AddRegister(collection.GetType(), cAttribute.SpecialAddress, cAttribute.RegisterType, _name: propName);
|
||||
}
|
||||
}
|
||||
|
||||
if (prop.PropertyType == typeof(short)) {
|
||||
AddRegister<short>(cAttribute.MemoryArea, _name: propName);
|
||||
AddRegister<short>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||
}
|
||||
|
||||
if (prop.PropertyType == typeof(ushort)) {
|
||||
AddRegister<ushort>(cAttribute.MemoryArea, _name: propName);
|
||||
AddRegister<ushort>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||
}
|
||||
|
||||
if (prop.PropertyType == typeof(int)) {
|
||||
AddRegister<int>(cAttribute.MemoryArea, _name: propName);
|
||||
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||
}
|
||||
|
||||
if (prop.PropertyType == typeof(uint)) {
|
||||
AddRegister<uint>(cAttribute.MemoryArea, _name: propName);
|
||||
AddRegister<uint>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||
}
|
||||
|
||||
if (prop.PropertyType == typeof(float)) {
|
||||
AddRegister<float>(cAttribute.MemoryArea, _name: propName);
|
||||
AddRegister<float>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||
}
|
||||
|
||||
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
|
||||
if (prop.PropertyType == typeof(BitArray)) {
|
||||
|
||||
if(cAttribute.BitCount == BitCount.B16) {
|
||||
AddRegister<short>(cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||
if (cAttribute.BitCount == BitCount.B16) {
|
||||
AddRegister<short>(collection.GetType(), cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||
} else {
|
||||
AddRegister<int>(cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||
AddRegister<int>(collection.GetType(), cAttribute.MemoryArea, _name: propName, _isBitwise: true);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -236,16 +284,18 @@ namespace MewtocolNet {
|
||||
//read number as bit array by invdividual properties
|
||||
if (prop.PropertyType == typeof(bool) && cAttribute.AssignedBitIndex != -1) {
|
||||
|
||||
//var bitwiseCount = Registers.Count(x => x.Value.isUsedBitwise);
|
||||
|
||||
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 {
|
||||
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)) {
|
||||
AddRegister<TimeSpan>(cAttribute.MemoryArea, _name: propName);
|
||||
AddRegister<TimeSpan>(collection.GetType(), cAttribute.MemoryArea, _name: propName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -256,6 +306,40 @@ namespace MewtocolNet {
|
||||
|
||||
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);
|
||||
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);
|
||||
|
||||
if (foundToUpdate != null) {
|
||||
@@ -298,6 +382,14 @@ namespace MewtocolNet {
|
||||
foundToUpdate.SetValue(collection, ((NRegister<float>)reg).Value);
|
||||
}
|
||||
|
||||
if (foundToUpdate.PropertyType.IsEnum) {
|
||||
foundToUpdate.SetValue(collection, ((NRegister<int>)reg).Value);
|
||||
}
|
||||
|
||||
if (foundToUpdate.PropertyType == typeof(TimeSpan)) {
|
||||
foundToUpdate.SetValue(collection, ((NRegister<TimeSpan>)reg).Value);
|
||||
}
|
||||
|
||||
//setting back strings
|
||||
|
||||
if (foundToUpdate.PropertyType == typeof(string)) {
|
||||
@@ -307,27 +399,7 @@ namespace MewtocolNet {
|
||||
}
|
||||
|
||||
|
||||
if (foundToUpdate.PropertyType == typeof(bool) && registerAttr.AssignedBitIndex >= 0) {
|
||||
|
||||
//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)) {
|
||||
if (foundToUpdate.PropertyType == typeof(BitArray)) {
|
||||
|
||||
//setting back bit registers
|
||||
if (reg is NRegister<short> shortReg) {
|
||||
@@ -354,6 +426,14 @@ namespace MewtocolNet {
|
||||
|
||||
};
|
||||
|
||||
if (collection != null)
|
||||
collection.OnInterfaceLinked(this);
|
||||
|
||||
Connected += (i) => {
|
||||
if (collection != null)
|
||||
collection.OnInterfaceLinkedAndOnline(this);
|
||||
};
|
||||
|
||||
return this;
|
||||
|
||||
}
|
||||
@@ -394,49 +474,49 @@ namespace MewtocolNet {
|
||||
|
||||
if (foundRegister.GetType() == typeof(BRegister)) {
|
||||
|
||||
return await WriteBoolRegister((BRegister)foundRegister, (bool)value, StationNumber);
|
||||
return await WriteBoolRegister((BRegister)foundRegister, (bool)value);
|
||||
|
||||
}
|
||||
|
||||
if (foundRegister.GetType() == typeof(NRegister<short>)) {
|
||||
|
||||
return await WriteNumRegister((NRegister<short>)foundRegister, (short)value, StationNumber);
|
||||
return await WriteNumRegister((NRegister<short>)foundRegister, (short)value);
|
||||
|
||||
}
|
||||
|
||||
if (foundRegister.GetType() == typeof(NRegister<ushort>)) {
|
||||
|
||||
return await WriteNumRegister((NRegister<ushort>)foundRegister, (ushort)value, StationNumber);
|
||||
return await WriteNumRegister((NRegister<ushort>)foundRegister, (ushort)value);
|
||||
|
||||
}
|
||||
|
||||
if (foundRegister.GetType() == typeof(NRegister<int>)) {
|
||||
|
||||
return await WriteNumRegister((NRegister<int>)foundRegister, (int)value, StationNumber);
|
||||
return await WriteNumRegister((NRegister<int>)foundRegister, (int)value);
|
||||
|
||||
}
|
||||
|
||||
if (foundRegister.GetType() == typeof(NRegister<uint>)) {
|
||||
|
||||
return await WriteNumRegister((NRegister<uint>)foundRegister, (uint)value, StationNumber);
|
||||
return await WriteNumRegister((NRegister<uint>)foundRegister, (uint)value);
|
||||
|
||||
}
|
||||
|
||||
if (foundRegister.GetType() == typeof(NRegister<float>)) {
|
||||
|
||||
return await WriteNumRegister((NRegister<float>)foundRegister, (float)value, StationNumber);
|
||||
return await WriteNumRegister((NRegister<float>)foundRegister, (float)value);
|
||||
|
||||
}
|
||||
|
||||
if (foundRegister.GetType() == typeof(NRegister<TimeSpan>)) {
|
||||
|
||||
return await WriteNumRegister((NRegister<TimeSpan>)foundRegister, (TimeSpan)value, StationNumber);
|
||||
return await WriteNumRegister((NRegister<TimeSpan>)foundRegister, (TimeSpan)value);
|
||||
|
||||
}
|
||||
|
||||
if (foundRegister.GetType() == typeof(SRegister)) {
|
||||
|
||||
return await WriteStringRegister((SRegister)foundRegister, (string)value, StationNumber);
|
||||
return await WriteStringRegister((SRegister)foundRegister, (string)value);
|
||||
|
||||
}
|
||||
|
||||
@@ -463,13 +543,13 @@ namespace MewtocolNet {
|
||||
|
||||
string response = null;
|
||||
|
||||
if(ContinousReaderRunning) {
|
||||
if (ContinousReaderRunning) {
|
||||
|
||||
//if the poller is active then add all messages to a qeueue
|
||||
|
||||
var awaittask = SendSingleBlock(_msg);
|
||||
PriorityTasks.Add(awaittask);
|
||||
awaittask.Wait();
|
||||
await awaittask;
|
||||
|
||||
PriorityTasks.Remove(awaittask);
|
||||
response = awaittask.Result;
|
||||
@@ -482,7 +562,7 @@ namespace MewtocolNet {
|
||||
|
||||
}
|
||||
|
||||
if(response == null) {
|
||||
if (response == null) {
|
||||
return new CommandResult {
|
||||
Success = false,
|
||||
Error = "0000",
|
||||
@@ -526,34 +606,60 @@ namespace MewtocolNet {
|
||||
await client.ConnectAsync(ip, port);
|
||||
|
||||
using (NetworkStream stream = client.GetStream()) {
|
||||
|
||||
var message = _blockString.ToHexASCIIBytes();
|
||||
var messageAscii = BitConverter.ToString(message).Replace("-", " ");
|
||||
|
||||
//send request
|
||||
using (var sendStream = new MemoryStream(message)) {
|
||||
await sendStream.CopyToAsync(stream);
|
||||
Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this);
|
||||
//log message sent
|
||||
ASCIIEncoding enc = new ASCIIEncoding();
|
||||
string characters = enc.GetString(message);
|
||||
try {
|
||||
using (var sendStream = new MemoryStream(message)) {
|
||||
await sendStream.CopyToAsync(stream);
|
||||
Logger.Log($"OUT MSG: {_blockString}", LogLevel.Critical, this);
|
||||
//log message sent
|
||||
ASCIIEncoding enc = new ASCIIEncoding();
|
||||
string characters = enc.GetString(message);
|
||||
}
|
||||
} catch (IOException) {
|
||||
Logger.Log($"Critical IO exception on send", LogLevel.Critical, this);
|
||||
return null;
|
||||
}
|
||||
|
||||
//await result
|
||||
StringBuilder response = new StringBuilder();
|
||||
byte[] responseBuffer = new byte[256];
|
||||
do {
|
||||
int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length);
|
||||
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
|
||||
try {
|
||||
byte[] responseBuffer = new byte[256];
|
||||
do {
|
||||
int bytes = stream.Read(responseBuffer, 0, responseBuffer.Length);
|
||||
response.Append(Encoding.UTF8.GetString(responseBuffer, 0, bytes));
|
||||
}
|
||||
while (stream.DataAvailable);
|
||||
} catch (IOException) {
|
||||
Logger.Log($"Critical IO exception on receive", LogLevel.Critical, this);
|
||||
return null;
|
||||
}
|
||||
while (stream.DataAvailable);
|
||||
|
||||
sw.Stop();
|
||||
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {_blockString}", LogLevel.Critical, this);
|
||||
var curCycle = (int)sw.ElapsedMilliseconds;
|
||||
if (Math.Abs(CycleTimeMs - curCycle) > 2) {
|
||||
CycleTimeMs = curCycle;
|
||||
}
|
||||
|
||||
Logger.Log($"IN MSG ({(int)sw.Elapsed.TotalMilliseconds}ms): {response}", LogLevel.Critical, this);
|
||||
return response.ToString();
|
||||
}
|
||||
|
||||
} catch(Exception) {
|
||||
} catch (SocketException) {
|
||||
|
||||
if (IsConnected) {
|
||||
|
||||
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
|
||||
CycleTimeMs = 0;
|
||||
IsConnected = false;
|
||||
Disconnected?.Invoke();
|
||||
KillPoller();
|
||||
|
||||
}
|
||||
|
||||
IsConnected = false;
|
||||
KillPoller();
|
||||
Logger.Log("The PLC connection was closed", LogLevel.Error, this);
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ using System.Threading.Tasks;
|
||||
using MewtocolNet.Registers;
|
||||
using System.Linq;
|
||||
using System.Globalization;
|
||||
using MewtocolNet.Logging;
|
||||
|
||||
namespace MewtocolNet {
|
||||
|
||||
@@ -43,6 +44,8 @@ namespace MewtocolNet {
|
||||
ErrorCode = error,
|
||||
StationNumber = int.Parse(station ?? "0"),
|
||||
};
|
||||
|
||||
PlcInfo = retInfo;
|
||||
return retInfo;
|
||||
|
||||
}
|
||||
@@ -51,16 +54,101 @@ namespace MewtocolNet {
|
||||
|
||||
#endregion
|
||||
|
||||
#region Operation mode changing
|
||||
|
||||
/// <summary>
|
||||
/// Changes the PLCs operation mode to the given one
|
||||
/// </summary>
|
||||
/// <param name="mode">The mode to change to</param>
|
||||
/// <returns>The success state of the write operation</returns>
|
||||
public async Task<bool> SetOperationMode (OPMode mode) {
|
||||
|
||||
string modeChar = mode == OPMode.Prog ? "P" : "R";
|
||||
|
||||
string requeststring = $"%{GetStationNumber()}#RM{modeChar}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
if (result.Success) {
|
||||
Logger.Log($"operation mode was changed to {mode}", LogLevel.Info, this);
|
||||
} else {
|
||||
Logger.Log("Operation mode change failed", LogLevel.Error, this);
|
||||
}
|
||||
|
||||
return result.Success;
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Byte range writingv / reading to registers
|
||||
|
||||
/// <summary>
|
||||
/// Writes a byte array to a span over multiple registers at once,
|
||||
/// Rembember the plc can only store word so in order to write to a word array
|
||||
/// your byte array should be double the size
|
||||
/// </summary>
|
||||
/// /// <param name="start">start address of the array</param>
|
||||
/// <param name="byteArr"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<bool> WriteByteRange (int start, byte[] byteArr) {
|
||||
|
||||
string byteString = byteArr.BigToMixedEndian().ToHexString();
|
||||
var wordLength = byteArr.Length / 2;
|
||||
if (byteArr.Length % 2 != 0)
|
||||
wordLength++;
|
||||
|
||||
string startStr = start.ToString().PadLeft(5, '0');
|
||||
string endStr = (start + wordLength - 1).ToString().PadLeft(5, '0');
|
||||
|
||||
string requeststring = $"%{GetStationNumber()}#WDD{startStr}{endStr}{byteString}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
return result.Success;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bytes from the start adress for counts byte length
|
||||
/// </summary>
|
||||
/// <param name="start">Start adress</param>
|
||||
/// <param name="count">Number of bytes to get</param>
|
||||
/// <returns>A byte array or null of there was an error</returns>
|
||||
public async Task<byte[]> ReadByteRange (int start, int count) {
|
||||
|
||||
string startStr = start.ToString().PadLeft(5, '0');
|
||||
var wordLength = count / 2;
|
||||
bool wasOdd = false;
|
||||
if (count % 2 != 0)
|
||||
wordLength++;
|
||||
|
||||
string endStr = (start + wordLength - 1).ToString().PadLeft(5, '0');
|
||||
|
||||
string requeststring = $"%{GetStationNumber()}#RDD{startStr}{endStr}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
if(result.Success && !string.IsNullOrEmpty(result.Response)) {
|
||||
|
||||
var bytes = result.Response.ParseDTByteString(wordLength * 4).HexStringToByteArray();
|
||||
|
||||
return bytes.BigToMixedEndian().Take(count).ToArray();
|
||||
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Bool register reading / writing
|
||||
|
||||
/// <summary>
|
||||
/// Reads the given boolean register from the PLC
|
||||
/// </summary>
|
||||
/// <param name="_toRead">The register to read</param>
|
||||
/// <param name="_stationNumber">Station number to access</param>
|
||||
public async Task<BRegisterResult> ReadBoolRegister (BRegister _toRead, int _stationNumber = 1) {
|
||||
public async Task<BRegisterResult> ReadBoolRegister (BRegister _toRead) {
|
||||
|
||||
string requeststring = $"%{_stationNumber.ToString().PadLeft(2, '0')}#RCS{_toRead.BuildMewtocolIdent()}";
|
||||
string requeststring = $"%{GetStationNumber()}#RCS{_toRead.BuildMewtocolIdent()}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
if(!result.Success) {
|
||||
@@ -72,7 +160,7 @@ namespace MewtocolNet {
|
||||
|
||||
var resultBool = result.Response.ParseRCSingleBit();
|
||||
if(resultBool != null) {
|
||||
_toRead.LastValue = resultBool.Value;
|
||||
_toRead.SetValueFromPLC(resultBool.Value);
|
||||
}
|
||||
|
||||
var finalRes = new BRegisterResult {
|
||||
@@ -88,15 +176,14 @@ namespace MewtocolNet {
|
||||
/// Writes to the given bool register on the PLC
|
||||
/// </summary>
|
||||
/// <param name="_toWrite">The register to write to</param>
|
||||
/// <param name="_stationNumber">Station number to access</param>
|
||||
/// <returns>The success state of the write operation</returns>
|
||||
public async Task<bool> WriteBoolRegister (BRegister _toWrite, bool value, int _stationNumber = 1) {
|
||||
public async Task<bool> WriteBoolRegister (BRegister _toWrite, bool value) {
|
||||
|
||||
string requeststring = $"%{_stationNumber.ToString().PadLeft(2, '0')}#WCS{_toWrite.BuildMewtocolIdent()}{(value ? "1" : "0")}";
|
||||
string requeststring = $"%{GetStationNumber()}#WCS{_toWrite.BuildMewtocolIdent()}{(value ? "1" : "0")}";
|
||||
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
return result.Success && result.Response.StartsWith($"%{ _stationNumber.ToString().PadLeft(2, '0')}#WC");
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WC");
|
||||
|
||||
}
|
||||
|
||||
@@ -111,11 +198,11 @@ namespace MewtocolNet {
|
||||
/// <param name="_toRead">The register to read</param>
|
||||
/// <param name="_stationNumber">Station number to access</param>
|
||||
/// <returns>A result with the given NumberRegister containing the readback value and a result struct</returns>
|
||||
public async Task<NRegisterResult<T>> ReadNumRegister<T> (NRegister<T> _toRead, int _stationNumber = 1) {
|
||||
public async Task<NRegisterResult<T>> ReadNumRegister<T> (NRegister<T> _toRead) {
|
||||
|
||||
Type numType = typeof(T);
|
||||
|
||||
string requeststring = $"%{_stationNumber.ToString().PadLeft(2, '0')}#RD{_toRead.BuildMewtocolIdent()}";
|
||||
string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolIdent()}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
if(!result.Success || string.IsNullOrEmpty(result.Response)) {
|
||||
@@ -129,25 +216,25 @@ namespace MewtocolNet {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
||||
var val = short.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
(_toRead as NRegister<short>).LastValue = val;
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(ushort)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder();
|
||||
var val = ushort.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
(_toRead as NRegister<ushort>).LastValue = val;
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(int)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||
var val = int.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
(_toRead as NRegister<int>).LastValue = val;
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(uint)) {
|
||||
|
||||
var resultBytes = result.Response.ParseDTByteString(8).ReverseByteOrder();
|
||||
var val = uint.Parse(resultBytes, NumberStyles.HexNumber);
|
||||
(_toRead as NRegister<uint>).LastValue = val;
|
||||
_toRead.SetValueFromPLC(val);
|
||||
|
||||
} else if (numType == typeof(float)) {
|
||||
|
||||
@@ -158,7 +245,7 @@ namespace MewtocolNet {
|
||||
byte[] floatVals = BitConverter.GetBytes(val);
|
||||
float finalFloat = BitConverter.ToSingle(floatVals, 0);
|
||||
|
||||
(_toRead as NRegister<float>).LastValue = finalFloat;
|
||||
_toRead.SetValueFromPLC(finalFloat);
|
||||
|
||||
} else if (numType == typeof(TimeSpan)) {
|
||||
|
||||
@@ -169,7 +256,7 @@ namespace MewtocolNet {
|
||||
var ts = TimeSpan.FromMilliseconds(valMillis);
|
||||
|
||||
//minmax writable / readable value is 10ms
|
||||
(_toRead as NRegister<TimeSpan>).LastValue = ts;
|
||||
_toRead.SetValueFromPLC(ts);
|
||||
|
||||
}
|
||||
|
||||
@@ -188,7 +275,7 @@ namespace MewtocolNet {
|
||||
/// <param name="_toWrite">The register to write</param>
|
||||
/// <param name="_stationNumber">Station number to access</param>
|
||||
/// <returns>The success state of the write operation</returns>
|
||||
public async Task<bool> WriteNumRegister<T> (NRegister<T> _toWrite, T _value, int _stationNumber = 1) {
|
||||
public async Task<bool> WriteNumRegister<T> (NRegister<T> _toWrite, T _value) {
|
||||
|
||||
byte[] toWriteVal;
|
||||
Type numType = typeof(T);
|
||||
@@ -222,11 +309,11 @@ namespace MewtocolNet {
|
||||
toWriteVal = null;
|
||||
}
|
||||
|
||||
string requeststring = $"%{_stationNumber.ToString().PadLeft(2, '0')}#WD{_toWrite.BuildMewtocolIdent()}{toWriteVal.ToHexString()}";
|
||||
string requeststring = $"%{GetStationNumber()}#WD{_toWrite.BuildMewtocolIdent()}{toWriteVal.ToHexString()}";
|
||||
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
return result.Success && result.Response.StartsWith($"%{ _stationNumber.ToString().PadLeft(2, '0')}#WD");
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD");
|
||||
|
||||
}
|
||||
|
||||
@@ -249,7 +336,7 @@ namespace MewtocolNet {
|
||||
/// <returns></returns>
|
||||
public async Task<SRegisterResult> ReadStringRegister (SRegister _toRead, int _stationNumber = 1) {
|
||||
|
||||
string requeststring = $"%{_stationNumber.ToString().PadLeft(2, '0')}#RD{_toRead.BuildMewtocolIdent()}";
|
||||
string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolIdent()}";
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
if (result.Success)
|
||||
_toRead.SetValueFromPLC(result.Response.ParseDTString());
|
||||
@@ -273,7 +360,7 @@ namespace MewtocolNet {
|
||||
throw new ArgumentException("Write string size cannot be longer than reserved string size");
|
||||
}
|
||||
|
||||
string stationNum = _stationNumber.ToString().PadLeft(2, '0');
|
||||
string stationNum = GetStationNumber();
|
||||
string dataString = _value.BuildDTString(_toWrite.ReservedSize);
|
||||
string dataArea = _toWrite.BuildCustomIdent(dataString.Length / 4);
|
||||
|
||||
@@ -282,7 +369,18 @@ namespace MewtocolNet {
|
||||
var result = await SendCommandAsync(requeststring);
|
||||
|
||||
|
||||
return result.Success && result.Response.StartsWith($"%{ _stationNumber.ToString().PadLeft(2, '0')}#WD");
|
||||
return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helpers
|
||||
|
||||
internal string GetStationNumber () {
|
||||
|
||||
return StationNumber.ToString().PadLeft(2, '0');
|
||||
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
46
MewtocolNet/Mewtocol/PLCEnums/CpuType.cs
Normal file
46
MewtocolNet/Mewtocol/PLCEnums/CpuType.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
namespace MewtocolNet {
|
||||
|
||||
/// <summary>
|
||||
/// CPU type of the PLC
|
||||
/// </summary>
|
||||
public enum CpuType {
|
||||
/// <summary>
|
||||
/// FP 0 / FP 2.7K
|
||||
/// </summary>
|
||||
FP0_FP1_2_7K,
|
||||
/// <summary>
|
||||
/// FP0 / FP1, 5K / 10K
|
||||
/// </summary>
|
||||
FP0_FP1_5K_10K,
|
||||
/// <summary>
|
||||
/// FP1 M 0.9K
|
||||
/// </summary>
|
||||
FP1_M_0_9K,
|
||||
/// <summary>
|
||||
/// FP2 16k / 32k
|
||||
/// </summary>
|
||||
FP2_16K_32K,
|
||||
/// <summary>
|
||||
/// FP3 C 10K
|
||||
/// </summary>
|
||||
FP3_C_10K,
|
||||
/// <summary>
|
||||
/// FP3 C 16K
|
||||
/// </summary>
|
||||
FP3_C_16K,
|
||||
/// <summary>
|
||||
/// FP5 16K
|
||||
/// </summary>
|
||||
FP5_16K,
|
||||
/// <summary>
|
||||
/// FP 5 24K
|
||||
/// </summary>
|
||||
FP5_24K,
|
||||
/// <summary>
|
||||
/// Includes panasonic FPX, FPX-H, Sigma
|
||||
/// </summary>
|
||||
FP_Sigma_X_H_30K_60K_120K
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
21
MewtocolNet/Mewtocol/PLCEnums/OPMode.cs
Normal file
21
MewtocolNet/Mewtocol/PLCEnums/OPMode.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace MewtocolNet {
|
||||
|
||||
/// <summary>
|
||||
/// CPU type of the PLC
|
||||
/// </summary>
|
||||
public enum OPMode {
|
||||
/// <summary>
|
||||
/// PLC run mode
|
||||
/// </summary>
|
||||
Run,
|
||||
/// <summary>
|
||||
/// PLC programming mode
|
||||
/// </summary>
|
||||
Prog,
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,17 +10,34 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace MewtocolNet.RegisterAttributes {
|
||||
|
||||
/// <summary>
|
||||
/// A register collection base with full auto read and notification support built in
|
||||
/// </summary>
|
||||
public class RegisterCollectionBase : INotifyPropertyChanged {
|
||||
|
||||
/// <summary>
|
||||
/// Reference to its bound interface
|
||||
/// </summary>
|
||||
public MewtocolInterface PLCInterface { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Whenever one of its props changes
|
||||
/// </summary>
|
||||
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;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
|
||||
public virtual void OnInterfaceLinked (MewtocolInterface plc) { }
|
||||
|
||||
public virtual void OnInterfaceLinkedAndOnline (MewtocolInterface plc) { }
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ namespace MewtocolNet.Registers {
|
||||
/// </summary>
|
||||
public class BRegister : Register {
|
||||
|
||||
internal RegisterType RegType { get; set; }
|
||||
internal SpecialAddress SpecialAddress { get; set; }
|
||||
internal RegisterType RegType { get; private set; }
|
||||
internal SpecialAddress SpecialAddress { get; private set; }
|
||||
|
||||
public bool NeedValue;
|
||||
public bool LastValue;
|
||||
@@ -18,13 +18,7 @@ namespace MewtocolNet.Registers {
|
||||
/// <summary>
|
||||
/// The value of the register
|
||||
/// </summary>
|
||||
public bool Value {
|
||||
get => LastValue;
|
||||
set {
|
||||
NeedValue = value;
|
||||
TriggerChangedEvnt(this);
|
||||
}
|
||||
}
|
||||
public bool Value => LastValue;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a register containing a number
|
||||
@@ -35,8 +29,8 @@ namespace MewtocolNet.Registers {
|
||||
public BRegister (int _address, RegisterType _type = RegisterType.R, string _name = null) {
|
||||
|
||||
if (_address > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||
MemoryAdress = _address;
|
||||
Name = _name;
|
||||
memoryAdress = _address;
|
||||
name = _name;
|
||||
|
||||
RegType = _type;
|
||||
|
||||
@@ -54,7 +48,7 @@ namespace MewtocolNet.Registers {
|
||||
throw new NotSupportedException("Special adress cant be none");
|
||||
|
||||
SpecialAddress = _address;
|
||||
Name = _name;
|
||||
name = _name;
|
||||
|
||||
RegType = _type;
|
||||
|
||||
@@ -74,6 +68,11 @@ namespace MewtocolNet.Registers {
|
||||
|
||||
}
|
||||
|
||||
internal void SetValueFromPLC (bool val) {
|
||||
LastValue = val;
|
||||
TriggerChangedEvnt(this);
|
||||
TriggerNotifyChange();
|
||||
}
|
||||
public override string ToString() {
|
||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
||||
}
|
||||
|
||||
@@ -13,48 +13,75 @@ namespace MewtocolNet.Registers {
|
||||
/// <summary>
|
||||
/// The value of the register
|
||||
/// </summary>
|
||||
public T Value {
|
||||
get => LastValue;
|
||||
set {
|
||||
NeedValue = value;
|
||||
TriggerChangedEvnt(this);
|
||||
}
|
||||
}
|
||||
public T Value => LastValue;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a register containing a number
|
||||
/// </summary>
|
||||
/// <param name="_adress">Memory start adress max 99999</param>
|
||||
/// <param name="_format">The format in which the variable is stored</param>
|
||||
public NRegister(int _adress, string _name = null, bool isBitwise = false) {
|
||||
/// <param name="_name">Name of the register</param>
|
||||
public NRegister (int _adress, string _name = null) {
|
||||
|
||||
if (_adress > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||
MemoryAdress = _adress;
|
||||
Name = _name;
|
||||
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;
|
||||
memoryLength = 0;
|
||||
} else if (numType == typeof(ushort)) {
|
||||
MemoryLength = 0;
|
||||
memoryLength = 0;
|
||||
} else if (numType == typeof(int)) {
|
||||
MemoryLength = 1;
|
||||
memoryLength = 1;
|
||||
} else if (numType == typeof(uint)) {
|
||||
MemoryLength = 1;
|
||||
memoryLength = 1;
|
||||
} else if (numType == typeof(float)) {
|
||||
MemoryLength = 1;
|
||||
memoryLength = 1;
|
||||
} 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 {
|
||||
throw new NotSupportedException($"The type {numType} is not allowed for Number Registers");
|
||||
}
|
||||
|
||||
isUsedBitwise = isBitwise;
|
||||
enumType = _enumType;
|
||||
|
||||
}
|
||||
|
||||
internal void SetValueFromPLC (object val) {
|
||||
LastValue = (T)val;
|
||||
TriggerChangedEvnt(this);
|
||||
TriggerNotifyChange();
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return $"Adress: {MemoryAdress} Val: {Value}";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace MewtocolNet.Registers {
|
||||
using System;
|
||||
|
||||
namespace MewtocolNet.Registers {
|
||||
/// <summary>
|
||||
/// Result for a read/write operation
|
||||
/// </summary>
|
||||
@@ -11,6 +13,19 @@
|
||||
string errmsg = Result.Success ? "" : $", Error [{Result.ErrorDescription}]";
|
||||
return $"Result [{Result.Success}], Register [{Register.ToString()}]{errmsg}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trys to get the value of there is one
|
||||
/// </summary>
|
||||
public bool TryGetValue (out T value) {
|
||||
if(Result.Success) {
|
||||
value = Register.Value;
|
||||
return true;
|
||||
}
|
||||
value = default(T);
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -17,12 +17,63 @@ namespace MewtocolNet.Registers {
|
||||
/// Gets called whenever the value was changed
|
||||
/// </summary>
|
||||
public event Action<object> ValueChanged;
|
||||
/// <summary>
|
||||
/// Triggers when a property on the register changes
|
||||
/// </summary>
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
|
||||
public string Name { get; set; }
|
||||
public int MemoryAdress { get; set; }
|
||||
public int MemoryLength { get; set; }
|
||||
internal Type collectionType;
|
||||
/// <summary>
|
||||
/// The type of collection the register is in or null of added manually
|
||||
/// </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)));
|
||||
};
|
||||
}
|
||||
|
||||
public virtual string BuildMewtocolIdent() {
|
||||
|
||||
@@ -60,6 +111,18 @@ namespace MewtocolNet.Registers {
|
||||
/// <returns></returns>
|
||||
public string GetValueString () {
|
||||
|
||||
if (enumType != null && this is NRegister<int> intEnumReg) {
|
||||
var dict = new Dictionary<int, string>();
|
||||
foreach (var name in Enum.GetNames(enumType)) {
|
||||
dict.Add((int)Enum.Parse(enumType, name), name);
|
||||
}
|
||||
|
||||
if(dict.ContainsKey(intEnumReg.Value)) {
|
||||
return $"{intEnumReg.Value} ({dict[intEnumReg.Value]})";
|
||||
} else {
|
||||
return $"{intEnumReg.Value} (Missing Enum)";
|
||||
}
|
||||
}
|
||||
if (this is NRegister<short> shortReg) {
|
||||
return $"{shortReg.Value}{(isUsedBitwise ? $" [{shortReg.GetBitwise().ToBitString()}]" : "")}";
|
||||
}
|
||||
@@ -83,7 +146,6 @@ namespace MewtocolNet.Registers {
|
||||
}
|
||||
if (this is SRegister stringReg) {
|
||||
return stringReg.Value.ToString();
|
||||
|
||||
}
|
||||
|
||||
return "Type of the register is not supported.";
|
||||
@@ -148,7 +210,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}";
|
||||
|
||||
|
||||
@@ -8,11 +8,8 @@ namespace MewtocolNet.Registers {
|
||||
public class SRegister : Register {
|
||||
|
||||
private string lastVal = "";
|
||||
public string Value {
|
||||
|
||||
get => lastVal;
|
||||
|
||||
}
|
||||
public string Value => lastVal;
|
||||
|
||||
public short ReservedSize { get; set; }
|
||||
|
||||
@@ -22,8 +19,8 @@ namespace MewtocolNet.Registers {
|
||||
public SRegister(int _adress, int _reservedStringSize, string _name = null) {
|
||||
|
||||
if (_adress > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999");
|
||||
Name = _name;
|
||||
MemoryAdress = _adress;
|
||||
name = _name;
|
||||
memoryAdress = _adress;
|
||||
ReservedSize = (short)_reservedStringSize;
|
||||
|
||||
//calc mem length
|
||||
@@ -32,7 +29,7 @@ namespace MewtocolNet.Registers {
|
||||
wordsize++;
|
||||
}
|
||||
|
||||
MemoryLength = (int)Math.Round(wordsize + 1);
|
||||
memoryLength = (int)Math.Round(wordsize + 1);
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
@@ -62,7 +59,7 @@ namespace MewtocolNet.Registers {
|
||||
return asciistring.ToString();
|
||||
}
|
||||
|
||||
public void SetValueFromPLC (string val) {
|
||||
internal void SetValueFromPLC (string val) {
|
||||
lastVal = val;
|
||||
TriggerChangedEvnt(this);
|
||||
TriggerNotifyChange();
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<PackageId>AppLogger</PackageId>
|
||||
<Version>0.2.5</Version>
|
||||
<PackageId>MewtocolNet</PackageId>
|
||||
<Version>0.4.1</Version>
|
||||
<Authors>Felix Weiss</Authors>
|
||||
<Company>Womed</Company>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
<Description>A Mewtocol protocol library to interface with Panasonic PLCs over TCP/Serial.</Description>
|
||||
<Copyright>Copyright (c) 2022 WOLF Medizintechnik GmbH</Copyright>
|
||||
<PackageProjectUrl>https://github.com/WOmed/MewtocolNet</PackageProjectUrl>
|
||||
<RepositoryUrl>https://github.com/WOmed/MewtocolNet</RepositoryUrl>
|
||||
<PackageTags>plc;panasonic;mewtocol;automation;</PackageTags>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<UserSecretsId>2ccdcc9b-94a3-4e76-8827-453ab889ea33</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DocumentationFile>C:\Users\Felix Weiß\source\repos\WOmed\MewtocolNet\Builds\MewtocolNet.xml</DocumentationFile>
|
||||
<OutputPath>C:\Users\Felix Weiß\source\repos\WOmed\MewtocolNet\Builds</OutputPath>
|
||||
<DocumentationFile>..\Builds\MewtocolNet.xml</DocumentationFile>
|
||||
<OutputPath>..\Builds</OutputPath>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
||||
68
README.md
68
README.md
@@ -1,3 +1,4 @@
|
||||
[](https://github.com/WOmed/MewtocolNet/actions/workflows/dotnet-windows.yml)
|
||||

|
||||

|
||||

|
||||
@@ -17,11 +18,10 @@ This software was written by WOLF Medizintechnik GmbH (@WOmed/dev).
|
||||
|
||||
- [x] Read out stats from your PLC
|
||||
- [x] Read and write registers in real time
|
||||
- [X] Dynamic register type casting from properties
|
||||
- [ ] Change run / prog modes
|
||||
- [ ] Write byte blocks in a whole chain
|
||||
- [ ] Upload programs to the PLC
|
||||
- [ ] Download programs from the PLC
|
||||
- [x] Dynamic register type casting from properties
|
||||
- [x] Change run / prog modes
|
||||
- [x] Write / read byte blocks in a whole chain
|
||||
- [ ] Upload / Download programs to the PLC
|
||||
- [ ] Reading / writing PLC system registers
|
||||
|
||||
# Support
|
||||
@@ -53,7 +53,7 @@ Where is the RS232/Serial support?
|
||||
|
||||
Install this package by using [Nuget](https://www.nuget.org/packages/MewtocolNet/) or reference
|
||||
```XML
|
||||
<PackageReference Include="MewtocolNet" Version="0.2.5" />
|
||||
<PackageReference Include="MewtocolNet" Version="0.3.0" />
|
||||
```
|
||||
in your dependencies.
|
||||
Alternatively use the dotnet CLI and run
|
||||
@@ -84,28 +84,15 @@ Logger.OnNewLogMessage((date, msg) => {
|
||||
});
|
||||
|
||||
//setting up a new PLC interface
|
||||
MewtocolInterface interf = new MewtocolInterface("192.168.115.5");
|
||||
MewtocolInterface plc = new MewtocolInterface("192.168.115.5");
|
||||
|
||||
await interf.ConnectAsync();
|
||||
await plc.ConnectAsync();
|
||||
```
|
||||
|
||||
You can also use the callbacks of the `ConnectAsync()` method to do something after the initial connection establishment.
|
||||
|
||||
```C#
|
||||
await interf.ConnectAsync(
|
||||
//PLC connected
|
||||
(plc) => {
|
||||
if(plcinf.OperationMode.RunMode)
|
||||
Console.WriteLine("PLC is in RUN");
|
||||
},
|
||||
//Connection failed
|
||||
() => {
|
||||
Console.WriteLine("PLC failed to connect");
|
||||
}
|
||||
);
|
||||
```
|
||||
## Reading data registers / contacts
|
||||
|
||||
[Detailed instructions](https://github.com/WOmed/MewtocolNet/wiki/Attribute-handled-reading)
|
||||
|
||||
- Create a new class that inherits from `RegisterCollectionBase`
|
||||
|
||||
```C#
|
||||
@@ -135,20 +122,14 @@ public class TestRegisters : RegisterCollectionBase {
|
||||
- attach an automatic poller by chaining `.WithPoller()` after the register attachment
|
||||
|
||||
```C#
|
||||
//attaching a logger
|
||||
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("192.168.115.5");
|
||||
MewtocolInterface plc = new MewtocolInterface("192.168.115.5");
|
||||
TestRegisters registers = new TestRegisters();
|
||||
|
||||
//attaching the register collection and an automatic poller
|
||||
interf.WithRegisterCollection(registers).WithPoller();
|
||||
plc.WithRegisterCollection(registers).WithPoller();
|
||||
|
||||
await interf.ConnectAsync(
|
||||
await plc.ConnectAsync(
|
||||
(plcinf) => {
|
||||
//reading a value from the register collection
|
||||
Console.WriteLine($"Time Value is: {registers.TestTime}");
|
||||
@@ -169,37 +150,28 @@ Sets the register without feedback if it was set
|
||||
|
||||
```C#
|
||||
//inverts the boolean register
|
||||
interf.SetRegister(nameof(registers.TestBool1), !registers.TestBool1);
|
||||
plc.SetRegister(nameof(registers.TestBool1), !registers.TestBool1);
|
||||
|
||||
//set the current second to the PLCs TIME register
|
||||
interf.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second));
|
||||
plc.SetRegister(nameof(registers.TestTime), TimeSpan.FromSeconds(DateTime.Now.Second));
|
||||
|
||||
//writes 'Test' to the PLCs string register
|
||||
interf.SetRegister(nameof(registers.TestString1), "Test");
|
||||
plc.SetRegister(nameof(registers.TestString1), "Test");
|
||||
```
|
||||
|
||||
You can also set a register by calling its name directly (Must be either in an attached register collection or added to the list manually)
|
||||
|
||||
Adding registers to a manual list
|
||||
```C#
|
||||
interf.AddRegister<bool>(105, _name: "ManualBoolRegister");
|
||||
plc.AddRegister<bool>(105, _name: "ManualBoolRegister");
|
||||
```
|
||||
|
||||
Reading the value of the manually added register
|
||||
```C#
|
||||
//get the value as a string
|
||||
string value = interf.GetRegister("ManualBoolRegister").GetValueString();
|
||||
string value = plc.GetRegister("ManualBoolRegister").GetValueString();
|
||||
//get the value by casting
|
||||
bool value2 = interf.GetRegister<BRegister>("ManualBoolRegister").Value;
|
||||
bool value2 = plc.GetRegister<BRegister>("ManualBoolRegister").Value;
|
||||
//for double casted ones like numbers
|
||||
var value2 = interf.GetRegister<NRegister<short>>("NumberRegister").Value;
|
||||
```
|
||||
|
||||
### Asynchronous
|
||||
|
||||
Sets the register waiting for the PLC to confirm it was set
|
||||
|
||||
```C#
|
||||
//inverts the boolean register
|
||||
await interf.SetRegisterAsync(nameof(registers.TestBool1), !registers.TestBool1);
|
||||
var value2 = plc.GetRegister<NRegister<short>>("NumberRegister").Value;
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user