diff --git a/MewtocolNet/Mewtocol/CodeDescriptions.cs b/MewtocolNet/CodeDescriptions.cs similarity index 96% rename from MewtocolNet/Mewtocol/CodeDescriptions.cs rename to MewtocolNet/CodeDescriptions.cs index cbe90ef..9407856 100644 --- a/MewtocolNet/Mewtocol/CodeDescriptions.cs +++ b/MewtocolNet/CodeDescriptions.cs @@ -1,7 +1,6 @@ -using System; using System.Collections.Generic; -namespace MewtocolNet.Links { +namespace MewtocolNet { internal class CodeDescriptions { @@ -40,7 +39,6 @@ namespace MewtocolNet.Links { }; - } } \ No newline at end of file diff --git a/MewtocolNet/Mewtocol/CpuInfo.cs b/MewtocolNet/CpuInfo.cs similarity index 90% rename from MewtocolNet/Mewtocol/CpuInfo.cs rename to MewtocolNet/CpuInfo.cs index 3fa008b..4f21723 100644 --- a/MewtocolNet/Mewtocol/CpuInfo.cs +++ b/MewtocolNet/CpuInfo.cs @@ -1,6 +1,7 @@ -using System; +using MewtocolNet.PLCEnums; +using System; -namespace MewtocolNet.Registers { +namespace MewtocolNet { /// /// Contains information about the plc and its cpu @@ -22,7 +23,7 @@ namespace MewtocolNet.Registers { /// public string CpuVersion { get; set; } - internal static CpuInfo BuildFromHexString (string _cpuType, string _cpuVersion, string _progCapacity) { + internal static CpuInfo BuildFromHexString(string _cpuType, string _cpuVersion, string _progCapacity) { CpuInfo retInf = new CpuInfo(); @@ -61,7 +62,7 @@ namespace MewtocolNet.Registers { return retInf; } - + } } \ No newline at end of file diff --git a/MewtocolNet/Mewtocol/DynamicInterface.cs b/MewtocolNet/DynamicInterface.cs similarity index 88% rename from MewtocolNet/Mewtocol/DynamicInterface.cs rename to MewtocolNet/DynamicInterface.cs index 8bee8e6..f8726b0 100644 --- a/MewtocolNet/Mewtocol/DynamicInterface.cs +++ b/MewtocolNet/DynamicInterface.cs @@ -1,14 +1,10 @@ -using System; +using MewtocolNet.Logging; +using MewtocolNet.Subregisters; +using System; using System.Collections.Generic; -using System.Data; using System.Linq; using System.Reflection; -using System.Text; -using System.Threading; using System.Threading.Tasks; -using MewtocolNet.Logging; -using MewtocolNet.RegisterAttributes; -using MewtocolNet.Registers; namespace MewtocolNet { @@ -41,7 +37,7 @@ namespace MewtocolNet { /// /// Kills the poller completely /// - internal void KillPoller () { + internal void KillPoller() { pollerTaskRunning = false; pollerTaskStopped = true; @@ -54,7 +50,7 @@ namespace MewtocolNet { /// Pauses the polling and waits for the last message to be sent /// /// - public async Task PausePollingAsync () { + public async Task PausePollingAsync() { if (!pollerTaskRunning) return; @@ -65,9 +61,9 @@ namespace MewtocolNet { if (pollerIsPaused) break; - + await Task.Delay(10); - + } pollerTaskRunning = false; @@ -77,7 +73,7 @@ namespace MewtocolNet { /// /// Resumes the polling /// - public void ResumePolling () { + public void ResumePolling() { pollerTaskRunning = true; @@ -86,7 +82,7 @@ namespace MewtocolNet { /// /// Attaches a continous reader that reads back the Registers and Contacts /// - internal void AttachPoller () { + internal void AttachPoller() { if (pollerTaskRunning) return; @@ -196,9 +192,9 @@ namespace MewtocolNet { } - internal void PropertyRegisterWasSet (string propName, object value) { + internal void PropertyRegisterWasSet(string propName, object value) { - SetRegister(propName, value); + SetRegister(propName, value); } @@ -207,7 +203,7 @@ namespace MewtocolNet { #region Register Adding //Internal register adding for auto register collection building - internal void AddRegister (Type _colType, int _address, PropertyInfo boundProp, int _length = 1, bool _isBitwise = false, Type _enumType = null) { + internal void AddRegister(Type _colType, int _address, PropertyInfo boundProp, int _length = 1, bool _isBitwise = false, Type _enumType = null) { Type regType = typeof(T); @@ -224,7 +220,7 @@ namespace MewtocolNet { string propName = boundProp.Name; //rename the property name to prevent duplicate names in case of a bitwise prop - if(_isBitwise && regType == typeof(short)) + if (_isBitwise && regType == typeof(short)) propName = $"Auto_Bitwise_DT{_address}"; if (_isBitwise && regType == typeof(int)) @@ -245,7 +241,7 @@ namespace MewtocolNet { } else if (regType == typeof(TimeSpan)) { reg = new NRegister(_address, propName).WithCollectionType(_colType); } else if (regType == typeof(bool)) { - reg = new BRegister(IOType.R, 0x0, _address,propName).WithCollectionType(_colType); + reg = new BRegister(IOType.R, 0x0, _address, propName).WithCollectionType(_colType); } if (reg == null) { @@ -270,7 +266,7 @@ namespace MewtocolNet { /// Gets a register that was added by its name /// /// - public IRegister GetRegister (string name) { + public IRegister GetRegister(string name) { return Registers.FirstOrDefault(x => x.Name == name); @@ -281,16 +277,16 @@ namespace MewtocolNet { /// /// The type of register /// A casted register or the default value - public T GetRegister (string name) where T : IRegister { + public T GetRegister(string name) where T : IRegister { try { - + var reg = Registers.FirstOrDefault(x => x.Name == name); return (T)reg; } catch (InvalidCastException) { - + return default(T); - + } } @@ -302,7 +298,7 @@ namespace MewtocolNet { /// /// Gets a list of all added registers /// - public List GetAllRegisters () { + public List GetAllRegisters() { return Registers; @@ -312,19 +308,20 @@ namespace MewtocolNet { #region Event Invoking - internal void InvokeRegisterChanged (IRegister reg) { + internal void InvokeRegisterChanged(IRegister reg) { - RegisterChanged?.Invoke(reg); + RegisterChanged?.Invoke(reg); } - internal void InvokePolledCycleDone () { + internal void InvokePolledCycleDone() { - PolledCycle?.Invoke(); + PolledCycle?.Invoke(); } #endregion } + } diff --git a/MewtocolNet/Mewtocol/IRegister.cs b/MewtocolNet/IRegister.cs similarity index 97% rename from MewtocolNet/Mewtocol/IRegister.cs rename to MewtocolNet/IRegister.cs index 524bf15..c771084 100644 --- a/MewtocolNet/Mewtocol/IRegister.cs +++ b/MewtocolNet/IRegister.cs @@ -1,7 +1,4 @@ using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; namespace MewtocolNet { diff --git a/MewtocolNet/Mewtocol/Logging/Logger.cs b/MewtocolNet/Logging/Logger.cs similarity index 74% rename from MewtocolNet/Mewtocol/Logging/Logger.cs rename to MewtocolNet/Logging/Logger.cs index ee4d311..d9d68ae 100644 --- a/MewtocolNet/Mewtocol/Logging/Logger.cs +++ b/MewtocolNet/Logging/Logger.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace MewtocolNet.Logging { @@ -12,14 +10,14 @@ namespace MewtocolNet.Logging { /// /// Sets the loglevel for the logger module /// - public static LogLevel LogLevel { get; set; } + public static LogLevel LogLevel { get; set; } internal static Action LogInvoked; /// /// Gets invoked whenever a new log message is ready /// - public static void OnNewLogMessage (Action onMsg) { + public static void OnNewLogMessage(Action onMsg) { LogInvoked += (t, m) => { onMsg(t, m); @@ -27,7 +25,7 @@ namespace MewtocolNet.Logging { } - internal static void Log (string message, LogLevel loglevel, MewtocolInterface sender = null) { + internal static void Log(string message, LogLevel loglevel, MewtocolInterface sender = null) { if ((int)loglevel <= (int)LogLevel) { if (sender == null) { diff --git a/MewtocolNet/Mewtocol/Logging/LoggerEnums.cs b/MewtocolNet/Logging/LoggerEnums.cs similarity index 86% rename from MewtocolNet/Mewtocol/Logging/LoggerEnums.cs rename to MewtocolNet/Logging/LoggerEnums.cs index 385bdae..a845218 100644 --- a/MewtocolNet/Mewtocol/Logging/LoggerEnums.cs +++ b/MewtocolNet/Logging/LoggerEnums.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace MewtocolNet.Logging { +namespace MewtocolNet.Logging { /// /// The loglevel of the logging module diff --git a/MewtocolNet/Mewtocol/MewtocolHelpers.cs b/MewtocolNet/MewtocolHelpers.cs similarity index 78% rename from MewtocolNet/Mewtocol/MewtocolHelpers.cs rename to MewtocolNet/MewtocolHelpers.cs index 715a869..e3f0d2f 100644 --- a/MewtocolNet/Mewtocol/MewtocolHelpers.cs +++ b/MewtocolNet/MewtocolHelpers.cs @@ -1,10 +1,9 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; -using System.Collections.Generic; -using MewtocolNet.Registers; -using System.Collections; namespace MewtocolNet { @@ -16,7 +15,7 @@ namespace MewtocolNet { /// /// Turns a bit array into a 0 and 1 string /// - public static string ToBitString (this BitArray arr) { + public static string ToBitString(this BitArray arr) { var bits = new bool[arr.Length]; arr.CopyTo(bits, 0); @@ -27,29 +26,29 @@ namespace MewtocolNet { /// /// Converts a string (after converting to upper case) to ascii bytes /// - internal static byte[] ToHexASCIIBytes (this string _str) { + internal static byte[] ToHexASCIIBytes(this string _str) { ASCIIEncoding ascii = new ASCIIEncoding(); - byte[] bytes = ascii.GetBytes(_str.ToUpper()); + byte[] bytes = ascii.GetBytes(_str.ToUpper()); return bytes; } - internal static string BuildBCCFrame (this string asciiArr) { + internal static string BuildBCCFrame(this string asciiArr) { Encoding ae = Encoding.ASCII; byte[] b = ae.GetBytes(asciiArr); byte xorTotalByte = 0; - for(int i = 0; i < b.Length; i++) - xorTotalByte ^= b[i]; + for (int i = 0; i < b.Length; i++) + xorTotalByte ^= b[i]; return asciiArr.Insert(asciiArr.Length, xorTotalByte.ToString("X2")); - + } /// /// Parses the byte string from a incoming RD message /// - internal static string ParseDTByteString (this string _onString, int _blockSize = 4) { + internal static string ParseDTByteString(this string _onString, int _blockSize = 4) { if (_onString == null) return null; @@ -63,7 +62,7 @@ namespace MewtocolNet { } - internal static bool? ParseRCSingleBit (this string _onString) { + internal static bool? ParseRCSingleBit(this string _onString) { var res = new Regex(@"\%([0-9]{2})\$RC(.)").Match(_onString); if (res.Success) { @@ -74,10 +73,10 @@ namespace MewtocolNet { } - internal static string ParseDTString (this string _onString) { + internal static string ParseDTString(this string _onString) { var res = new Regex(@"\%([0-9]{2})\$RD.{8}(.*)...").Match(_onString); - if(res.Success) { + if (res.Success) { string val = res.Groups[2].Value; return val.GetStringFromAsciiHex()?.Trim(); } @@ -85,9 +84,9 @@ namespace MewtocolNet { } - internal static string ReverseByteOrder (this string _onString) { + internal static string ReverseByteOrder(this string _onString) { - if(_onString == null) return null; + if (_onString == null) return null; //split into 2 chars var stringBytes = _onString.SplitInParts(2).ToList(); @@ -98,7 +97,7 @@ namespace MewtocolNet { } - internal static IEnumerable SplitInParts (this string s, int partLength) { + internal static IEnumerable SplitInParts(this string s, int partLength) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -110,7 +109,7 @@ namespace MewtocolNet { } - internal static string BuildDTString (this string _inString, short _stringReservedSize) { + internal static string BuildDTString(this string _inString, short _stringReservedSize) { StringBuilder sb = new StringBuilder(); @@ -140,7 +139,7 @@ namespace MewtocolNet { sb.Append(reservedSizeBytes); //string count actual bytes sb.Append(sizeBytes); - + sb.Append(hexstring); @@ -148,18 +147,18 @@ namespace MewtocolNet { } - internal static string GetStringFromAsciiHex (this string input) { + internal static string GetStringFromAsciiHex(this string input) { if (input.Length % 2 != 0) return null; byte[] bytes = new byte[input.Length / 2]; for (int i = 0; i < input.Length; i += 2) { String hex = input.Substring(i, 2); - bytes[i/2] = Convert.ToByte(hex, 16); + bytes[i / 2] = Convert.ToByte(hex, 16); } return Encoding.ASCII.GetString(bytes); } - internal static string GetAsciiHexFromString (this string input) { + internal static string GetAsciiHexFromString(this string input) { var bytes = new ASCIIEncoding().GetBytes(input); return bytes.ToHexString(); } @@ -173,7 +172,7 @@ namespace MewtocolNet { .ToArray(); } - internal static string ToHexString (this byte[] arr) { + internal static string ToHexString(this byte[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.Length; i++) { @@ -184,17 +183,17 @@ namespace MewtocolNet { } - internal static byte[] BigToMixedEndian (this byte[] arr) { + internal static byte[] BigToMixedEndian(this byte[] arr) { List oldBL = new List(arr); List tempL = new List(); //make the input list even - if(arr.Length % 2 != 0) + if (arr.Length % 2 != 0) oldBL.Add((byte)0); - for (int i = 0; i < oldBL.Count; i+=2) { + for (int i = 0; i < oldBL.Count; i += 2) { byte firstByte = oldBL[i]; byte lastByte = oldBL[i + 1]; tempL.Add(lastByte); @@ -206,7 +205,7 @@ namespace MewtocolNet { } - internal static bool IsDoubleNumericRegisterType (this Type type) { + internal static bool IsDoubleNumericRegisterType(this Type type) { //Type[] singles = new Type[] { // typeof(short), @@ -224,7 +223,7 @@ namespace MewtocolNet { } - internal static bool IsNumericSupportedType (this Type type) { + internal static bool IsNumericSupportedType(this Type type) { Type[] supported = new Type[] { typeof(short), @@ -242,7 +241,7 @@ namespace MewtocolNet { /// /// Checks if the register type is non numeric /// - internal static bool IsBoolean (this RegisterType type) { + internal static bool IsBoolean(this RegisterType type) { return type == RegisterType.X || type == RegisterType.Y || type == RegisterType.R; @@ -251,7 +250,7 @@ namespace MewtocolNet { /// /// Checks if the register type is an physical in or output of the plc /// - internal static bool IsPhysicalInOutType (this RegisterType type) { + internal static bool IsPhysicalInOutType(this RegisterType type) { return type == RegisterType.X || type == RegisterType.Y; diff --git a/MewtocolNet/Mewtocol/MewtocolInterface.cs b/MewtocolNet/MewtocolInterface.cs similarity index 91% rename from MewtocolNet/Mewtocol/MewtocolInterface.cs rename to MewtocolNet/MewtocolInterface.cs index 009f7fe..b5f28a6 100644 --- a/MewtocolNet/Mewtocol/MewtocolInterface.cs +++ b/MewtocolNet/MewtocolInterface.cs @@ -1,27 +1,21 @@ +using MewtocolNet.Logging; +using MewtocolNet.Queue; +using MewtocolNet.RegisterAttributes; +using MewtocolNet.Subregisters; using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; using System.IO; +using System.Linq; +using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; -using System.Collections.Generic; using System.Threading.Tasks; -using System.Linq; -using MewtocolNet.Registers; -using MewtocolNet.RegisterAttributes; -using MewtocolNet.Logging; -using System.Collections; -using System.Diagnostics; -using System.ComponentModel; -using System.Net; -using System.Threading; -using MewtocolNet.Queue; -using System.Reflection; -using System.Timers; -using System.Data; -using System.Xml.Linq; -namespace MewtocolNet -{ +namespace MewtocolNet { /// /// The PLC com interface class @@ -63,7 +57,7 @@ namespace MewtocolNet /// public int PollerDelayMs { get => pollerDelayMs; - set { + set { pollerDelayMs = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PollerDelayMs))); } @@ -108,8 +102,8 @@ namespace MewtocolNet /// /// Generic information about the connected PLC /// - public PLCInfo PlcInfo { - get => plcInfo; + public PLCInfo PlcInfo { + get => plcInfo; private set { plcInfo = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PlcInfo))); @@ -158,7 +152,7 @@ namespace MewtocolNet /// The current transmission speed in bytes per second /// public int BytesPerSecondUpstream { - get { return bytesPerSecondUpstream; } + get { return bytesPerSecondUpstream; } private set { bytesPerSecondUpstream = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BytesPerSecondUpstream))); @@ -195,7 +189,7 @@ namespace MewtocolNet /// IP adress of the PLC /// Port of the PLC /// Station Number of the PLC - public MewtocolInterface (string _ip, int _port = 9094, int _station = 1) { + public MewtocolInterface(string _ip, int _port = 9094, int _station = 1) { ip = _ip; port = _port; @@ -203,7 +197,7 @@ namespace MewtocolNet Connected += MewtocolInterface_Connected; - void MewtocolInterface_Connected (PLCInfo obj) { + void MewtocolInterface_Connected(PLCInfo obj) { if (usePoller) AttachPoller(); @@ -237,7 +231,7 @@ namespace MewtocolNet /// /// Gets called when an error or timeout during connection occurs /// - public async Task ConnectAsync (Action OnConnected = null, Action OnFailed = null) { + public async Task ConnectAsync(Action OnConnected = null, Action OnFailed = null) { Logger.Log("Connecting to PLC...", LogLevel.Info, this); @@ -258,7 +252,7 @@ namespace MewtocolNet } PolledCycle += OnPollCycleDone; - void OnPollCycleDone () { + void OnPollCycleDone() { OnConnected(plcinf); PolledCycle -= OnPollCycleDone; } @@ -284,7 +278,7 @@ namespace MewtocolNet /// Ip adress /// Port number /// Station number - public void ChangeConnectionSettings (string _ip, int _port, int _station = 1) { + 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"); @@ -298,7 +292,7 @@ namespace MewtocolNet /// /// Closes the connection all cyclic polling /// - public void Disconnect () { + public void Disconnect() { if (!IsConnected) return; @@ -311,7 +305,7 @@ namespace MewtocolNet /// Attaches a poller to the interface that continously /// polls the registered data registers and writes the values to them /// - public MewtocolInterface WithPoller () { + public MewtocolInterface WithPoller() { usePoller = true; @@ -323,7 +317,7 @@ namespace MewtocolNet #region TCP connection state handling - private async Task ConnectTCP () { + private async Task ConnectTCP() { if (!IPAddress.TryParse(ip, out var targetIP)) { throw new ArgumentException("The IP adress of the PLC was no valid format"); @@ -331,8 +325,8 @@ namespace MewtocolNet try { - if(HostEndpoint != null) { - + if (HostEndpoint != null) { + client = new TcpClient(HostEndpoint) { ReceiveBufferSize = RecBufferSize, NoDelay = false, @@ -353,12 +347,12 @@ namespace MewtocolNet var result = client.BeginConnect(targetIP, port, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(ConnectTimeout)); - if(!success || !client.Connected) { + if (!success || !client.Connected) { OnMajorSocketExceptionWhileConnecting(); return; } - if(HostEndpoint == null) { + if (HostEndpoint == null) { var ep = (IPEndPoint)client.Client.LocalEndPoint; Logger.Log($"Connecting [AUTO] endpoint: {ep.Address.MapToIPv4()}:{ep.Port}", LogLevel.Verbose, this); } @@ -376,7 +370,7 @@ namespace MewtocolNet } - private void OnMajorSocketExceptionWhileConnecting () { + private void OnMajorSocketExceptionWhileConnecting() { Logger.Log("The PLC connection timed out", LogLevel.Error, this); CycleTimeMs = 0; @@ -385,7 +379,7 @@ namespace MewtocolNet } - private void OnMajorSocketExceptionWhileConnected () { + private void OnMajorSocketExceptionWhileConnected() { if (IsConnected) { @@ -400,7 +394,7 @@ namespace MewtocolNet } - private void ClearRegisterVals () { + private void ClearRegisterVals() { for (int i = 0; i < Registers.Count; i++) { @@ -423,7 +417,7 @@ namespace MewtocolNet /// and assert some propertys with the custom . /// /// A collection inherting the class - public MewtocolInterface WithRegisterCollection (RegisterCollectionBase collection) { + public MewtocolInterface WithRegisterCollection(RegisterCollectionBase collection) { collection.PLCInterface = this; @@ -516,7 +510,7 @@ namespace MewtocolNet RegisterChanged += (reg) => { //register is used bitwise - if(reg.IsUsedBitwise()) { + if (reg.IsUsedBitwise()) { for (int i = 0; i < props.Length; i++) { @@ -524,7 +518,7 @@ namespace MewtocolNet var bitWiseFound = prop.GetCustomAttributes(true) .FirstOrDefault(y => y.GetType() == typeof(RegisterAttribute) && ((RegisterAttribute)y).MemoryArea == reg.MemoryAddress); - if(bitWiseFound != null) { + if (bitWiseFound != null) { var casted = (RegisterAttribute)bitWiseFound; var bitIndex = casted.AssignedBitIndex; @@ -534,13 +528,13 @@ namespace MewtocolNet if (reg is NRegister reg16) { var bytes = BitConverter.GetBytes((short)reg16.Value); bitAr = new BitArray(bytes); - } else if(reg is NRegister reg32) { + } else if (reg is NRegister reg32) { var bytes = BitConverter.GetBytes((int)reg32.Value); bitAr = new BitArray(bytes); } if (bitAr != null && bitIndex < bitAr.Length && bitIndex >= 0) { - + //set the specific bit index if needed prop.SetValue(collection, bitAr[bitIndex]); collection.TriggerPropertyChanged(prop.Name); @@ -550,7 +544,7 @@ namespace MewtocolNet //set the specific bit array if needed prop.SetValue(collection, bitAr); collection.TriggerPropertyChanged(prop.Name); - + } } @@ -558,7 +552,7 @@ namespace MewtocolNet } } - + //updating normal properties var foundToUpdate = props.FirstOrDefault(x => x.Name == reg.Name); @@ -576,13 +570,13 @@ namespace MewtocolNet if (registerAttr.AssignedBitIndex == -1) { HashSet NumericTypes = new HashSet { - typeof(bool), - typeof(short), + typeof(bool), + typeof(short), typeof(ushort), - typeof(int), - typeof(uint), - typeof(float), - typeof(TimeSpan), + typeof(int), + typeof(uint), + typeof(float), + typeof(TimeSpan), typeof(string) }; @@ -625,7 +619,7 @@ namespace MewtocolNet /// /// The name the register was given to or a property name from the RegisterCollection class /// The value to write to the register - public void SetRegister (string registerName, object value) { + public void SetRegister(string registerName, object value) { var foundRegister = GetAllRegisters().FirstOrDefault(x => x.Name == registerName); @@ -642,7 +636,7 @@ namespace MewtocolNet /// /// The name the register was given to or a property name from the RegisterCollection class /// The value to write to the register - public async Task SetRegisterAsync (string registerName, object value) { + public async Task SetRegisterAsync(string registerName, object value) { var foundRegister = GetAllRegisters().FirstOrDefault(x => x.Name == registerName); @@ -711,7 +705,7 @@ namespace MewtocolNet /// /// MEWTOCOL Formatted request string ex: %01#RT /// Returns the result - public async Task SendCommandAsync (string _msg) { + public async Task SendCommandAsync(string _msg) { _msg = _msg.BuildBCCFrame(); _msg += "\r"; @@ -720,10 +714,10 @@ namespace MewtocolNet try { queuedMessages++; - + var response = await queue.Enqueue(() => SendSingleBlock(_msg)); - if (queuedMessages > 0) + if (queuedMessages > 0) queuedMessages--; if (response == null) { @@ -739,7 +733,7 @@ namespace MewtocolNet Match m = errorcheck.Match(response.ToString()); if (m.Success) { string eCode = m.Groups[1].Value; - string eDes = Links.CodeDescriptions.Error[Convert.ToInt32(eCode)]; + string eDes = CodeDescriptions.Error[Convert.ToInt32(eCode)]; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Response is: {response}"); Logger.Log($"Error on command {_msg.Replace("\r", "")} the PLC returned error code: {eCode}, {eDes}", LogLevel.Error); @@ -767,9 +761,9 @@ namespace MewtocolNet } - private async Task SendSingleBlock (string _blockString) { + private async Task SendSingleBlock(string _blockString) { - if (client == null || !client.Connected ) { + if (client == null || !client.Connected) { await ConnectTCP(); } @@ -779,11 +773,11 @@ namespace MewtocolNet var message = _blockString.ToHexASCIIBytes(); //time measuring - if(speedStopwatchUpstr == null) { + if (speedStopwatchUpstr == null) { speedStopwatchUpstr = Stopwatch.StartNew(); } - if(speedStopwatchUpstr.Elapsed.TotalSeconds >= 1) { + if (speedStopwatchUpstr.Elapsed.TotalSeconds >= 1) { speedStopwatchUpstr.Restart(); bytesTotalCountedUpstream = 0; } @@ -846,15 +840,15 @@ namespace MewtocolNet return null; } - if(!string.IsNullOrEmpty(response.ToString())) { - + if (!string.IsNullOrEmpty(response.ToString())) { + Logger.Log($"<-- IN MSG: {response}", LogLevel.Critical, this); bytesTotalCountedDownstream += Encoding.ASCII.GetByteCount(response.ToString()); var perSecDownstream = (double)((bytesTotalCountedDownstream / speedStopwatchDownstr.Elapsed.TotalMilliseconds) * 1000); - if(perSecUpstream <= 10000) + if (perSecUpstream <= 10000) BytesPerSecondDownstream = (int)Math.Round(perSecUpstream, MidpointRounding.AwayFromZero); return response.ToString(); @@ -872,7 +866,7 @@ namespace MewtocolNet /// /// Disposes the current interface and clears all its members /// - public void Dispose () { + public void Dispose() { if (Disposed) return; @@ -891,7 +885,7 @@ namespace MewtocolNet /// /// Gets the connection info string /// - public string GetConnectionPortInfo () { + public string GetConnectionPortInfo() { return $"{IpAddress}:{Port}"; @@ -901,5 +895,4 @@ namespace MewtocolNet } - } \ No newline at end of file diff --git a/MewtocolNet/Mewtocol/MewtocolInterfaceRequests.cs b/MewtocolNet/MewtocolInterfaceRequests.cs similarity index 90% rename from MewtocolNet/Mewtocol/MewtocolInterfaceRequests.cs rename to MewtocolNet/MewtocolInterfaceRequests.cs index 375fb73..94917db 100644 --- a/MewtocolNet/Mewtocol/MewtocolInterfaceRequests.cs +++ b/MewtocolNet/MewtocolInterfaceRequests.cs @@ -1,17 +1,15 @@ +using MewtocolNet.Logging; +using MewtocolNet.PLCEnums; +using MewtocolNet.Subregisters; using System; -using System.IO; -using System.Net.Sockets; -using System.Text; using System.Collections.Generic; +using System.Globalization; +using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; -using MewtocolNet.Registers; -using System.Linq; -using System.Globalization; -using MewtocolNet.Logging; namespace MewtocolNet { - + public partial class MewtocolInterface { #region PLC info getters @@ -20,14 +18,14 @@ namespace MewtocolNet { /// Gets generic information about the PLC /// /// A PLCInfo class - public async Task GetPLCInfoAsync () { + public async Task GetPLCInfoAsync() { var resu = await SendCommandAsync("%01#RT"); - if(!resu.Success) return null; + if (!resu.Success) return null; var reg = new Regex(@"\%([0-9]{2})\$RT([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{4})..", RegexOptions.IgnoreCase); Match m = reg.Match(resu.Response); - - if(m.Success) { + + if (m.Success) { string station = m.Groups[1].Value; string cpu = m.Groups[2].Value; @@ -48,7 +46,7 @@ namespace MewtocolNet { PlcInfo = retInfo; return retInfo; - } + } return null; } @@ -61,7 +59,7 @@ namespace MewtocolNet { /// /// The mode to change to /// The success state of the write operation - public async Task SetOperationMode (OPMode mode) { + public async Task SetOperationMode(OPMode mode) { string modeChar = mode == OPMode.Prog ? "P" : "R"; @@ -90,7 +88,7 @@ namespace MewtocolNet { /// /// start address of the array /// /// - public async Task WriteByteRange (int start, byte[] byteArr) { + public async Task WriteByteRange(int start, byte[] byteArr) { string byteString = byteArr.BigToMixedEndian().ToHexString(); var wordLength = byteArr.Length / 2; @@ -114,17 +112,17 @@ namespace MewtocolNet { /// Number of bytes to get /// Gets invoked when the progress changes, contains the progress as a double /// A byte array or null of there was an error - public async Task ReadByteRange (int start, int count, Action onProgress = null) { + public async Task ReadByteRange(int start, int count, Action onProgress = null) { var byteList = new List(); - + var wordLength = count / 2; - if (count % 2 != 0) + if (count % 2 != 0) wordLength++; //read blocks of max 4 words per msg - for (int i = 0; i < wordLength; i+=8) { + for (int i = 0; i < wordLength; i += 8) { int curWordStart = start + i; int curWordEnd = curWordStart + 7; @@ -147,12 +145,12 @@ namespace MewtocolNet { } - if(onProgress != null) + if (onProgress != null) onProgress((double)i / wordLength); } - return byteList.ToArray(); + return byteList.ToArray(); } @@ -164,12 +162,12 @@ namespace MewtocolNet { /// Reads the given boolean register from the PLC /// /// The register to read - public async Task ReadBoolRegister (BRegister _toRead) { + public async Task ReadBoolRegister(BRegister _toRead) { string requeststring = $"%{GetStationNumber()}#RCS{_toRead.BuildMewtocolQuery()}"; var result = await SendCommandAsync(requeststring); - if(!result.Success) { + if (!result.Success) { return new BRegisterResult { Result = result, Register = _toRead @@ -177,9 +175,9 @@ namespace MewtocolNet { } var resultBool = result.Response.ParseRCSingleBit(); - if(resultBool != null) { + if (resultBool != null) { _toRead.SetValueFromPLC(resultBool.Value); - } + } var finalRes = new BRegisterResult { Result = result, @@ -196,13 +194,13 @@ namespace MewtocolNet { /// The register to write to /// The value to write /// The success state of the write operation - public async Task WriteBoolRegister (BRegister _toWrite, bool value) { + public async Task WriteBoolRegister(BRegister _toWrite, bool value) { string requeststring = $"%{GetStationNumber()}#WCS{_toWrite.BuildMewtocolQuery()}{(value ? "1" : "0")}"; var result = await SendCommandAsync(requeststring); - return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WC"); + return result.Success && result.Response.StartsWith($"%{GetStationNumber()}$WC"); } @@ -216,7 +214,7 @@ namespace MewtocolNet { /// Type of number (short, ushort, int, uint, float) /// The register to read /// A result with the given NumberRegister containing the readback value and a result struct - public async Task> ReadNumRegister (NRegister _toRead) { + public async Task> ReadNumRegister(NRegister _toRead) { Type numType = typeof(T); @@ -231,7 +229,7 @@ namespace MewtocolNet { if (!result.Success || string.IsNullOrEmpty(result.Response)) { return failedResult; } - + if (numType == typeof(short)) { var resultBytes = result.Response.ParseDTByteString(4).ReverseByteOrder(); @@ -301,7 +299,7 @@ namespace MewtocolNet { /// The register to write /// The value to write /// The success state of the write operation - public async Task WriteNumRegister (NRegister _toWrite, T _value) { + public async Task WriteNumRegister(NRegister _toWrite, T _value) { byte[] toWriteVal; Type numType = typeof(T); @@ -339,7 +337,7 @@ namespace MewtocolNet { var result = await SendCommandAsync(requeststring); - return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD"); + return result.Success && result.Response.StartsWith($"%{GetStationNumber()}$WD"); } @@ -360,7 +358,7 @@ namespace MewtocolNet { /// The register to read /// The station number of the PLC /// - public async Task ReadStringRegister (SRegister _toRead, int _stationNumber = 1) { + public async Task ReadStringRegister(SRegister _toRead, int _stationNumber = 1) { string requeststring = $"%{GetStationNumber()}#RD{_toRead.BuildMewtocolQuery()}"; var result = await SendCommandAsync(requeststring); @@ -382,27 +380,27 @@ namespace MewtocolNet { public async Task WriteStringRegister(SRegister _toWrite, string _value, int _stationNumber = 1) { if (_value == null) _value = ""; - if(_value.Length > _toWrite.ReservedSize) { + if (_value.Length > _toWrite.ReservedSize) { throw new ArgumentException("Write string size cannot be longer than reserved string size"); } string stationNum = GetStationNumber(); string dataString = _value.BuildDTString(_toWrite.ReservedSize); string dataArea = _toWrite.BuildCustomIdent(dataString.Length / 4); - + string requeststring = $"%{stationNum}#WD{dataArea}{dataString}"; var result = await SendCommandAsync(requeststring); - return result.Success && result.Response.StartsWith($"%{ GetStationNumber()}$WD"); + return result.Success && result.Response.StartsWith($"%{GetStationNumber()}$WD"); } #endregion #region Helpers - internal string GetStationNumber () { + internal string GetStationNumber() { return StationNumber.ToString().PadLeft(2, '0'); diff --git a/MewtocolNet/Mewtocol/PLCEnums/CpuType.cs b/MewtocolNet/PLCEnums/CpuType.cs similarity index 96% rename from MewtocolNet/Mewtocol/PLCEnums/CpuType.cs rename to MewtocolNet/PLCEnums/CpuType.cs index 9312177..cc5bcef 100644 --- a/MewtocolNet/Mewtocol/PLCEnums/CpuType.cs +++ b/MewtocolNet/PLCEnums/CpuType.cs @@ -1,4 +1,4 @@ -namespace MewtocolNet { +namespace MewtocolNet.PLCEnums { /// /// CPU type of the PLC diff --git a/MewtocolNet/Mewtocol/PLCEnums/OPMode.cs b/MewtocolNet/PLCEnums/OPMode.cs similarity index 74% rename from MewtocolNet/Mewtocol/PLCEnums/OPMode.cs rename to MewtocolNet/PLCEnums/OPMode.cs index 150338c..9ae73f1 100644 --- a/MewtocolNet/Mewtocol/PLCEnums/OPMode.cs +++ b/MewtocolNet/PLCEnums/OPMode.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace MewtocolNet { +namespace MewtocolNet.PLCEnums { /// /// CPU type of the PLC diff --git a/MewtocolNet/Mewtocol/PLCInfo.cs b/MewtocolNet/PLCInfo.cs similarity index 80% rename from MewtocolNet/Mewtocol/PLCInfo.cs rename to MewtocolNet/PLCInfo.cs index c89748e..4b1b46d 100644 --- a/MewtocolNet/Mewtocol/PLCInfo.cs +++ b/MewtocolNet/PLCInfo.cs @@ -1,4 +1,4 @@ -namespace MewtocolNet.Registers { +namespace MewtocolNet { /// /// Contains generic information about the plc /// @@ -7,26 +7,26 @@ /// /// Contains information about the PLCs cpu /// - public CpuInfo CpuInformation {get;set;} + public CpuInfo CpuInformation { get; set; } /// /// Contains information about the PLCs operation modes /// - public PLCMode OperationMode {get;set;} + public PLCMode OperationMode { get; set; } /// /// Current error code of the PLC /// - public string ErrorCode {get;set;} + public string ErrorCode { get; set; } /// /// Current station number of the PLC /// - public int StationNumber { get;set;} + public int StationNumber { get; set; } /// /// Generates a string containing some of the most important informations /// /// - public override string ToString () { + public override string ToString() { return $"Type: {CpuInformation.Cputype},\n" + $"Capacity: {CpuInformation.ProgramCapacity}k\n" + diff --git a/MewtocolNet/Mewtocol/PLCMode.cs b/MewtocolNet/PLCMode.cs similarity index 96% rename from MewtocolNet/Mewtocol/PLCMode.cs rename to MewtocolNet/PLCMode.cs index e9a10eb..9079527 100644 --- a/MewtocolNet/Mewtocol/PLCMode.cs +++ b/MewtocolNet/PLCMode.cs @@ -1,6 +1,6 @@ using System; -namespace MewtocolNet.Registers { +namespace MewtocolNet { /// /// All modes @@ -43,7 +43,7 @@ namespace MewtocolNet.Registers { /// /// Gets operation mode from 2 digit hex number /// - internal static PLCMode BuildFromHex (string _hexString) { + internal static PLCMode BuildFromHex(string _hexString) { string lower = Convert.ToString(Convert.ToInt32(_hexString.Substring(0, 1)), 2).PadLeft(4, '0'); string higher = Convert.ToString(Convert.ToInt32(_hexString.Substring(1, 1)), 2).PadLeft(4, '0'); @@ -87,6 +87,7 @@ namespace MewtocolNet.Registers { return retMode; } + } } \ No newline at end of file diff --git a/MewtocolNet/Queue/SerialQueue.cs b/MewtocolNet/Queue/SerialQueue.cs index 06001bf..efa71c6 100644 --- a/MewtocolNet/Queue/SerialQueue.cs +++ b/MewtocolNet/Queue/SerialQueue.cs @@ -8,7 +8,7 @@ namespace MewtocolNet.Queue { readonly object _locker = new object(); readonly WeakReference _lastTask = new WeakReference(null); - internal Task Enqueue (Func> asyncFunction) { + internal Task Enqueue(Func> asyncFunction) { lock (_locker) { Task lastTask; Task resultTask; diff --git a/MewtocolNet/RegisterAttributes/BitCount.cs b/MewtocolNet/RegisterAttributes/BitCount.cs new file mode 100644 index 0000000..08228b1 --- /dev/null +++ b/MewtocolNet/RegisterAttributes/BitCount.cs @@ -0,0 +1,16 @@ +namespace MewtocolNet.RegisterAttributes { + /// + /// The size of the bitwise register + /// + public enum BitCount { + /// + /// 16 bit + /// + B16, + /// + /// 32 bit + /// + B32 + } + +} diff --git a/MewtocolNet/Mewtocol/RegisterAttributes/RegisterAttribute.cs b/MewtocolNet/RegisterAttributes/RegisterAttribute.cs similarity index 75% rename from MewtocolNet/Mewtocol/RegisterAttributes/RegisterAttribute.cs rename to MewtocolNet/RegisterAttributes/RegisterAttribute.cs index 8e81f21..dd90c3c 100644 --- a/MewtocolNet/Mewtocol/RegisterAttributes/RegisterAttribute.cs +++ b/MewtocolNet/RegisterAttributes/RegisterAttribute.cs @@ -1,25 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace MewtocolNet.RegisterAttributes { - /// - /// The size of the bitwise register - /// - public enum BitCount { - /// - /// 16 bit - /// - B16, - /// - /// 32 bit - /// - B32 - } - /// /// Defines the behavior of a register property /// @@ -38,10 +20,10 @@ namespace MewtocolNet.RegisterAttributes { /// /// The area in the plcs memory /// The max string length in the plc - public RegisterAttribute (int memoryArea, int stringLength = 1) { + public RegisterAttribute(int memoryArea, int stringLength = 1) { MemoryArea = memoryArea; - StringLength = stringLength; + StringLength = stringLength; } @@ -59,11 +41,11 @@ namespace MewtocolNet.RegisterAttributes { /// /// Attribute for boolean registers /// - public RegisterAttribute (IOType type, int memoryArea, byte spAdress = 0x0) { + public RegisterAttribute(IOType type, int memoryArea, byte spAdress = 0x0) { MemoryArea = memoryArea; RegisterType = (RegisterType)(int)type; - SpecialAddress = spAdress; + SpecialAddress = spAdress; } @@ -72,7 +54,7 @@ namespace MewtocolNet.RegisterAttributes { /// /// The area in the plcs memory /// The number of bits to parse - public RegisterAttribute (int memoryArea, BitCount bitcount) { + public RegisterAttribute(int memoryArea, BitCount bitcount) { MemoryArea = memoryArea; StringLength = 0; @@ -86,9 +68,9 @@ namespace MewtocolNet.RegisterAttributes { /// The area in the plcs memory /// The number of bits to parse /// The index of the bit that gets linked to the bool - 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) { throw new NotSupportedException("The assignBit parameter cannot be greater than 15 in a 16 bit var"); } diff --git a/MewtocolNet/Mewtocol/RegisterAttributes/RegisterCollectionBase.cs b/MewtocolNet/RegisterAttributes/RegisterCollectionBase.cs similarity index 69% rename from MewtocolNet/Mewtocol/RegisterAttributes/RegisterCollectionBase.cs rename to MewtocolNet/RegisterAttributes/RegisterCollectionBase.cs index 4b5f2a5..66d38d8 100644 --- a/MewtocolNet/Mewtocol/RegisterAttributes/RegisterCollectionBase.cs +++ b/MewtocolNet/RegisterAttributes/RegisterCollectionBase.cs @@ -1,15 +1,7 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; +using System.ComponentModel; using System.Runtime.CompilerServices; -using System.Text; -using System.Threading.Tasks; -namespace MewtocolNet.RegisterAttributes -{ +namespace MewtocolNet.RegisterAttributes { /// /// A register collection base with full auto read and notification support built in @@ -19,7 +11,7 @@ namespace MewtocolNet.RegisterAttributes /// /// Reference to its bound interface /// - public MewtocolInterface PLCInterface { get; set; } + public MewtocolInterface PLCInterface { get; set; } /// /// Whenever one of its props changes @@ -30,7 +22,7 @@ namespace MewtocolNet.RegisterAttributes /// Triggers a property changed event /// /// Name of the property to trigger for - public void TriggerPropertyChanged (string propertyName = null) { + public void TriggerPropertyChanged(string propertyName = null) { var handler = PropertyChanged; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } @@ -38,11 +30,11 @@ namespace MewtocolNet.RegisterAttributes /// /// Use this on the setter method of a property to enable automatic property register writing /// - public void AutoSetter (object value, ref T privateField, [CallerMemberName] string propName = null) { + public void AutoSetter(object value, ref T privateField, [CallerMemberName] string propName = null) { PLCInterface.PropertyRegisterWasSet(propName, value); - if(value is IRegister reg) { + if (value is IRegister reg) { privateField = (T)reg.Value; return; @@ -57,14 +49,14 @@ namespace MewtocolNet.RegisterAttributes /// Gets called when the register collection base was linked to its parent mewtocol interface /// /// The parent interface - public virtual void OnInterfaceLinked (MewtocolInterface plc) { } + public virtual void OnInterfaceLinked(MewtocolInterface plc) { } /// /// Gets called when the register collection base was linked to its parent mewtocol interface /// and the plc connection is established /// /// The parent interface - public virtual void OnInterfaceLinkedAndOnline (MewtocolInterface plc) { } + public virtual void OnInterfaceLinkedAndOnline(MewtocolInterface plc) { } } diff --git a/MewtocolNet/Mewtocol/RegisterBuilder.cs b/MewtocolNet/RegisterBuilding/RegisterBuilder.cs similarity index 67% rename from MewtocolNet/Mewtocol/RegisterBuilder.cs rename to MewtocolNet/RegisterBuilding/RegisterBuilder.cs index 7278ac4..96cbf67 100644 --- a/MewtocolNet/Mewtocol/RegisterBuilder.cs +++ b/MewtocolNet/RegisterBuilding/RegisterBuilder.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace MewtocolNet.RegisterBuilding { -namespace MewtocolNet.Mewtocol { - /// /// Contains useful tools for register creation /// @@ -15,12 +11,14 @@ namespace MewtocolNet.Mewtocol { /// The name, fe. DT100 /// An or null if /// True if successfully parsed - //public static bool TryBuildFromName (string name, out IRegister reg) { + public static bool TryBuildFromName(string name, out IRegister reg) { + reg = null; + return false; + + } - //} - } } diff --git a/MewtocolNet/Mewtocol/RegisterEnums.cs b/MewtocolNet/RegisterEnums.cs similarity index 90% rename from MewtocolNet/Mewtocol/RegisterEnums.cs rename to MewtocolNet/RegisterEnums.cs index d6559c4..55c3528 100644 --- a/MewtocolNet/Mewtocol/RegisterEnums.cs +++ b/MewtocolNet/RegisterEnums.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MewtocolNet { +namespace MewtocolNet { /// /// The register prefixed type diff --git a/MewtocolNet/Mewtocol/Responses.cs b/MewtocolNet/Responses.cs similarity index 57% rename from MewtocolNet/Mewtocol/Responses.cs rename to MewtocolNet/Responses.cs index b9b2289..efc003b 100644 --- a/MewtocolNet/Mewtocol/Responses.cs +++ b/MewtocolNet/Responses.cs @@ -1,10 +1,4 @@ -using System.Collections.Generic; -using System.Text.RegularExpressions; -using System.Linq; -using System.Text; -using System.ComponentModel; - -namespace MewtocolNet.Registers { +namespace MewtocolNet { /// /// The formatted result of a ascii command @@ -14,19 +8,19 @@ namespace MewtocolNet.Registers { /// /// Success state of the message /// - public bool Success {get;set;} + public bool Success { get; set; } /// /// Response text of the message /// - public string Response {get;set;} + public string Response { get; set; } /// /// Error code of the message /// - public string Error {get;set;} + public string Error { get; set; } /// /// Error text of the message /// - public string ErrorDescription {get;set;} + public string ErrorDescription { get; set; } } diff --git a/MewtocolNet/Mewtocol/Subregisters/BRegister.cs b/MewtocolNet/Subregisters/BRegister.cs similarity index 90% rename from MewtocolNet/Mewtocol/Subregisters/BRegister.cs rename to MewtocolNet/Subregisters/BRegister.cs index c49d13e..88b8590 100644 --- a/MewtocolNet/Mewtocol/Subregisters/BRegister.cs +++ b/MewtocolNet/Subregisters/BRegister.cs @@ -1,10 +1,8 @@ using System; using System.ComponentModel; -using System.Data; using System.Text; -using MewtocolNet; -namespace MewtocolNet.Registers { +namespace MewtocolNet.Subregisters { /// /// Defines a register containing a boolean @@ -21,7 +19,7 @@ namespace MewtocolNet.Registers { /// public event PropertyChangedEventHandler PropertyChanged; - internal RegisterType RegType { get; private set; } + internal RegisterType RegType { get; private set; } internal Type collectionType; @@ -64,12 +62,12 @@ namespace MewtocolNet.Registers { /// The custom name /// /// - public BRegister (IOType _io, byte _spAddress = 0x0, int _areaAdress = 0, string _name = null) { + public BRegister(IOType _io, byte _spAddress = 0x0, int _areaAdress = 0, string _name = null) { if (_areaAdress < 0) throw new NotSupportedException("The area address cant be negative"); - if(_io == IOType.R && _areaAdress >= 512) + if (_io == IOType.R && _areaAdress >= 512) throw new NotSupportedException("R area addresses cant be greater than 511"); if ((_io == IOType.X || _io == IOType.Y) && _areaAdress >= 110) @@ -78,7 +76,7 @@ namespace MewtocolNet.Registers { if (_spAddress > 0xF) throw new NotSupportedException("Special address cant be greater 15 or 0xF"); - memoryAddress = (int)_areaAdress; + memoryAddress = _areaAdress; specialAddress = _spAddress; name = _name; @@ -96,7 +94,7 @@ namespace MewtocolNet.Registers { /// /// Builds the register area name /// - public string BuildMewtocolQuery () { + public string BuildMewtocolQuery() { //build area code from register type StringBuilder asciistring = new StringBuilder(RegType.ToString()); @@ -111,12 +109,12 @@ namespace MewtocolNet.Registers { } - internal void SetValueFromPLC (bool val) { + internal void SetValueFromPLC(bool val) { lastValue = val; TriggerChangedEvnt(this); TriggerNotifyChange(); - + } public string GetStartingMemoryArea() { @@ -149,7 +147,7 @@ namespace MewtocolNet.Registers { } - if(MemoryAddress > 0 && SpecialAddress != 0) { + if (MemoryAddress > 0 && SpecialAddress != 0) { return $"{GetRegisterString()}{MemoryAddress}{spAdressEnd}"; diff --git a/MewtocolNet/Mewtocol/Subregisters/BRegisterResult.cs b/MewtocolNet/Subregisters/BRegisterResult.cs similarity index 90% rename from MewtocolNet/Mewtocol/Subregisters/BRegisterResult.cs rename to MewtocolNet/Subregisters/BRegisterResult.cs index 8a39277..ddc4477 100644 --- a/MewtocolNet/Mewtocol/Subregisters/BRegisterResult.cs +++ b/MewtocolNet/Subregisters/BRegisterResult.cs @@ -1,4 +1,4 @@ -namespace MewtocolNet.Registers { +namespace MewtocolNet.Subregisters { /// /// Result for a boolean register diff --git a/MewtocolNet/Mewtocol/Subregisters/NRegister.cs b/MewtocolNet/Subregisters/NRegister.cs similarity index 93% rename from MewtocolNet/Mewtocol/Subregisters/NRegister.cs rename to MewtocolNet/Subregisters/NRegister.cs index 79cf631..1030cd6 100644 --- a/MewtocolNet/Mewtocol/Subregisters/NRegister.cs +++ b/MewtocolNet/Subregisters/NRegister.cs @@ -2,16 +2,15 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; -using System.Reflection; using System.Text; -namespace MewtocolNet.Registers { +namespace MewtocolNet.Subregisters { /// /// Defines a register containing a number /// /// The type of the numeric value - public class NRegister : IRegister { + public class NRegister : IRegister { /// /// Gets called whenever the value was changed @@ -64,7 +63,7 @@ namespace MewtocolNet.Registers { /// /// Memory start adress max 99999 /// Name of the register - public NRegister (int _adress, string _name = null) { + public NRegister(int _adress, string _name = null) { if (_adress > 99999) throw new NotSupportedException("Memory adresses cant be greater than 99999"); @@ -113,18 +112,18 @@ namespace MewtocolNet.Registers { } isUsedBitwise = isBitwise; - enumType = _enumType; + enumType = _enumType; } - internal NRegister WithCollectionType (Type colType) { + internal NRegister WithCollectionType(Type colType) { collectionType = colType; return this; } - internal void SetValueFromPLC (object val) { + internal void SetValueFromPLC(object val) { lastValue = (T)val; TriggerChangedEvnt(this); @@ -132,7 +131,7 @@ namespace MewtocolNet.Registers { } - public string GetStartingMemoryArea () => this.MemoryAddress.ToString(); + public string GetStartingMemoryArea() => MemoryAddress.ToString(); public Type GetCollectionType() => CollectionType; @@ -141,10 +140,10 @@ namespace MewtocolNet.Registers { public string GetValueString() { //is number or bitwise - if(enumType == null) { + if (enumType == null) { return $"{Value}{(isUsedBitwise ? $" [{GetBitwise().ToBitString()}]" : "")}"; - + } //is enum @@ -164,11 +163,11 @@ namespace MewtocolNet.Registers { if (dict.ContainsKey(shortVal)) { return $"{Value} ({dict[shortVal]})"; - + } else { - + return $"{Value} (Missing Enum)"; - + } } @@ -228,7 +227,7 @@ namespace MewtocolNet.Registers { public string GetRegisterString() { - if(Value is short) { + if (Value is short) { return "DT"; } diff --git a/MewtocolNet/Mewtocol/Subregisters/NRegisterResult.cs b/MewtocolNet/Subregisters/NRegisterResult.cs similarity index 79% rename from MewtocolNet/Mewtocol/Subregisters/NRegisterResult.cs rename to MewtocolNet/Subregisters/NRegisterResult.cs index 74f7214..fa5e29d 100644 --- a/MewtocolNet/Mewtocol/Subregisters/NRegisterResult.cs +++ b/MewtocolNet/Subregisters/NRegisterResult.cs @@ -1,6 +1,4 @@ -using System; - -namespace MewtocolNet.Registers { +namespace MewtocolNet.Subregisters { /// /// Result for a read/write operation /// @@ -20,15 +18,15 @@ namespace MewtocolNet.Registers { /// /// Trys to get the value of there is one /// - public bool TryGetValue (out T value) { + public bool TryGetValue(out T value) { - if(Result.Success) { + if (Result.Success) { value = (T)Register.Value; return true; } - value = default(T); + value = default; return false; - + } } diff --git a/MewtocolNet/Mewtocol/Subregisters/SRegister.cs b/MewtocolNet/Subregisters/SRegister.cs similarity index 92% rename from MewtocolNet/Mewtocol/Subregisters/SRegister.cs rename to MewtocolNet/Subregisters/SRegister.cs index 49c0d6e..49fa579 100644 --- a/MewtocolNet/Mewtocol/Subregisters/SRegister.cs +++ b/MewtocolNet/Subregisters/SRegister.cs @@ -2,7 +2,7 @@ using System.ComponentModel; using System.Text; -namespace MewtocolNet.Registers { +namespace MewtocolNet.Subregisters { /// /// Defines a register containing a string /// @@ -91,7 +91,7 @@ namespace MewtocolNet.Registers { return asciistring.ToString(); } - internal string BuildCustomIdent (int overwriteWordLength) { + internal string BuildCustomIdent(int overwriteWordLength) { if (overwriteWordLength <= 0) throw new Exception("overwriteWordLength cant be 0 or less"); @@ -108,16 +108,16 @@ namespace MewtocolNet.Registers { public bool IsUsedBitwise() => false; - internal void SetValueFromPLC (string val) { + internal void SetValueFromPLC(string val) { lastValue = val; TriggerChangedEvnt(this); TriggerNotifyChange(); - + } - public string GetStartingMemoryArea() => this.MemoryAddress.ToString(); + public string GetStartingMemoryArea() => MemoryAddress.ToString(); public string GetValueString() => Value?.ToString() ?? ""; @@ -135,7 +135,7 @@ namespace MewtocolNet.Registers { public void TriggerNotifyChange() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); - public override string ToString () => $"{GetRegisterPLCName()} - Value: {GetValueString()}"; + public override string ToString() => $"{GetRegisterPLCName()} - Value: {GetValueString()}"; } diff --git a/MewtocolNet/Mewtocol/Subregisters/SRegisterResult.cs b/MewtocolNet/Subregisters/SRegisterResult.cs similarity index 90% rename from MewtocolNet/Mewtocol/Subregisters/SRegisterResult.cs rename to MewtocolNet/Subregisters/SRegisterResult.cs index 45129a6..9ffed98 100644 --- a/MewtocolNet/Mewtocol/Subregisters/SRegisterResult.cs +++ b/MewtocolNet/Subregisters/SRegisterResult.cs @@ -1,4 +1,4 @@ -namespace MewtocolNet.Registers { +namespace MewtocolNet.Subregisters { /// /// The results of a string register operation diff --git a/MewtocolTests/AutomatedPropertyRegisters.cs b/MewtocolTests/AutomatedPropertyRegisters.cs index 834a39c..5ae5d3e 100644 --- a/MewtocolTests/AutomatedPropertyRegisters.cs +++ b/MewtocolTests/AutomatedPropertyRegisters.cs @@ -1,14 +1,15 @@ using Xunit; using MewtocolNet; -using MewtocolNet.Registers; using System.Diagnostics; using Xunit.Abstractions; using System.Collections; using MewtocolNet.RegisterAttributes; using Microsoft.Win32; +using MewtocolNet.Subregisters; -namespace MewtocolTests { +namespace MewtocolTests +{ public class AutomatedPropertyRegisters { diff --git a/MewtocolTests/TestLinkedLists.cs b/MewtocolTests/TestLinkedLists.cs index 4f47f03..324cdf5 100644 --- a/MewtocolTests/TestLinkedLists.cs +++ b/MewtocolTests/TestLinkedLists.cs @@ -3,9 +3,9 @@ using Xunit; using MewtocolNet; using MewtocolNet.Registers; using Xunit.Abstractions; -using MewtocolNet.Links; -namespace MewtocolTests { +namespace MewtocolTests +{ public class TestLinkedLists { diff --git a/MewtocolTests/TestLivePLC.cs b/MewtocolTests/TestLivePLC.cs index eea5f52..79f9bcf 100644 --- a/MewtocolTests/TestLivePLC.cs +++ b/MewtocolTests/TestLivePLC.cs @@ -1,5 +1,6 @@ using MewtocolNet; using MewtocolNet.Logging; +using MewtocolNet.PLCEnums; using System; using System.Collections.Generic; using System.Linq; @@ -8,7 +9,8 @@ using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; -namespace MewtocolTests { +namespace MewtocolTests +{ public class TestLivePLC { diff --git a/MewtocolTests/TestRegisterInterface.cs b/MewtocolTests/TestRegisterInterface.cs index d66daba..ec0f04f 100644 --- a/MewtocolTests/TestRegisterInterface.cs +++ b/MewtocolTests/TestRegisterInterface.cs @@ -61,6 +61,7 @@ namespace MewtocolTests { //boolean new BRegister(IOType.R, 0, 100), + new BRegister(IOType.R, 0, 0), new BRegister(IOType.X, 5), new BRegister(IOType.X, 0xA), new BRegister(IOType.X, 0xF, 109), @@ -82,6 +83,7 @@ namespace MewtocolTests { //boolean "R100", + "R0", "X5", "XA", "X109F", diff --git a/formatting_settings b/formatting_settings new file mode 100644 index 0000000..e140ae8 --- /dev/null +++ b/formatting_settings @@ -0,0 +1,229 @@ +# Entfernen Sie die folgende Zeile, wenn Sie EDITORCONFIG-Einstellungen von höheren Verzeichnissen vererben möchten. +root = true + +# C#-Dateien +[*.cs] + +#### Wichtige EditorConfig-Optionen #### + +# Einzüge und Abstände +indent_size = 4 +indent_style = space +tab_width = 4 + +# Einstellungen für neue Zeilen +end_of_line = crlf +insert_final_newline = false + +#### .NET-Codierungskonventionen #### + +# Using-Direktiven organisieren +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = false +file_header_template = unset + +# this.- und Me.-Einstellungen +dotnet_style_qualification_for_event = false +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Einstellungen für Sprachschlüsselwörter und BCL-Typen +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true + +# Einstellungen für Klammern +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity + +# Einstellungen für Modifizierer +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +# Einstellungen für Ausdrucksebene +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true +dotnet_style_explicit_tuple_names = true +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true +dotnet_style_object_initializer = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true +dotnet_style_prefer_compound_assignment = true +dotnet_style_prefer_conditional_expression_over_assignment = true +dotnet_style_prefer_conditional_expression_over_return = true +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed +dotnet_style_prefer_inferred_anonymous_type_member_names = true +dotnet_style_prefer_inferred_tuple_names = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +dotnet_style_prefer_simplified_boolean_expressions = true +dotnet_style_prefer_simplified_interpolation = true + +# Einstellungen für Felder +dotnet_style_readonly_field = true + +# Einstellungen für Parameter +dotnet_code_quality_unused_parameters = all + +# Unterdrückungseinstellungen +dotnet_remove_unnecessary_suppression_exclusions = none + +# Einstellungen für neue Zeilen +dotnet_style_allow_multiple_blank_lines_experimental = true +dotnet_style_allow_statement_immediately_after_block_experimental = true + +#### C#-Codierungskonventionen #### + +# Var-Einstellungen +csharp_style_var_elsewhere = false +csharp_style_var_for_built_in_types = false +csharp_style_var_when_type_is_apparent = false + +# Ausdruckskörpermember +csharp_style_expression_bodied_accessors = true +csharp_style_expression_bodied_constructors = false +csharp_style_expression_bodied_indexers = true +csharp_style_expression_bodied_lambdas = true +csharp_style_expression_bodied_local_functions = false +csharp_style_expression_bodied_methods = false +csharp_style_expression_bodied_operators = false +csharp_style_expression_bodied_properties = true + +# Einstellungen für den Musterabgleich +csharp_style_pattern_matching_over_as_with_null_check = true +csharp_style_pattern_matching_over_is_with_cast_check = true +csharp_style_prefer_extended_property_pattern = true +csharp_style_prefer_not_pattern = true +csharp_style_prefer_pattern_matching = true +csharp_style_prefer_switch_expression = true + +# Einstellungen für NULL-Überprüfung +csharp_style_conditional_delegate_call = true + +# Einstellungen für Modifizierer +csharp_prefer_static_local_function = true +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async +csharp_style_prefer_readonly_struct = true +csharp_style_prefer_readonly_struct_member = true + +# Einstellungen für Codeblöcke +csharp_prefer_braces = true +csharp_prefer_simple_using_statement = true +csharp_style_namespace_declarations = file_scoped +csharp_style_prefer_method_group_conversion = true +csharp_style_prefer_top_level_statements = true + +# Einstellungen für Ausdrucksebene +csharp_prefer_simple_default_expression = true +csharp_style_deconstructed_variable_declaration = true +csharp_style_implicit_object_creation_when_type_is_apparent = true +csharp_style_inlined_variable_declaration = true +csharp_style_prefer_index_operator = true +csharp_style_prefer_local_over_anonymous_function = true +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_range_operator = true +csharp_style_prefer_tuple_swap = true +csharp_style_prefer_utf8_string_literals = true +csharp_style_throw_expression = true +csharp_style_unused_value_assignment_preference = discard_variable +csharp_style_unused_value_expression_statement_preference = discard_variable + +# Einstellungen für using-Anweisungen +csharp_using_directive_placement = outside_namespace + +# Einstellungen für neue Zeilen +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true +csharp_style_allow_embedded_statements_on_same_line_experimental = true + +#### C#-Formatierungsregeln #### + +# Einstellungen für neue Zeilen +csharp_new_line_before_catch = false +csharp_new_line_before_else = false +csharp_new_line_before_finally = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = none +csharp_new_line_between_query_expression_clauses = true + +# Einstellungen für Einrückung +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = false +csharp_indent_case_contents_when_block = false +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Einstellungen für Abstände +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Umbrucheinstellungen +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Benennungsstile #### + +# Benennungsregeln + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbolspezifikationen + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Benennungsstile + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case