From 8a30c6c07ee7b401fe0331f8bd7592c5055fcdbb Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 21 May 2026 18:07:25 +0200 Subject: [PATCH] Ancora riorganizzazione codice per separare ambiti --- IOB-UT-NEXT/BinaryFormatter.cs | 143 -------------------------- IOB-UT-NEXT/BinaryUtils.cs | 116 +++++++++++++++++++++ IOB-UT-NEXT/IOB-UT-NEXT.csproj | 2 +- IOB-UT-NEXT/IobConfiguration.cs | 175 -------------------------------- IOB-UT-NEXT/baseUtils.cs | 93 ++--------------- 5 files changed, 124 insertions(+), 405 deletions(-) delete mode 100644 IOB-UT-NEXT/BinaryFormatter.cs create mode 100644 IOB-UT-NEXT/BinaryUtils.cs delete mode 100644 IOB-UT-NEXT/IobConfiguration.cs diff --git a/IOB-UT-NEXT/BinaryFormatter.cs b/IOB-UT-NEXT/BinaryFormatter.cs deleted file mode 100644 index 0619bf95..00000000 --- a/IOB-UT-NEXT/BinaryFormatter.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.Globalization; -using System.Numerics; - -namespace IOB_UT_NEXT -{ - public class BinaryUtils : IFormatProvider, ICustomFormatter - { - #region Public Methods - - // Format number in binary (B), octal (O), or hexadecimal (H). - public string Format(string format, object arg, IFormatProvider formatProvider) - { - // Handle format string. - int baseNumber; - // Handle null or empty format string, string with precision specifier. - string thisFmt = String.Empty; - // Extract first character of format string (precision specifiers are not supported). - if (!String.IsNullOrEmpty(format)) - thisFmt = format.Length > 1 ? format.Substring(0, 1) : format; - - // Get a byte array representing the numeric value. - byte[] bytes; - if (arg is sbyte) - { - string byteString = ((sbyte)arg).ToString("X2"); - bytes = new byte[1] { Byte.Parse(byteString, System.Globalization.NumberStyles.HexNumber) }; - } - else if (arg is byte) - { - bytes = new byte[1] { (byte)arg }; - } - else if (arg is short) - { - bytes = BitConverter.GetBytes((short)arg); - } - else if (arg is int) - { - bytes = BitConverter.GetBytes((int)arg); - } - else if (arg is long) - { - bytes = BitConverter.GetBytes((long)arg); - } - else if (arg is ushort) - { - bytes = BitConverter.GetBytes((ushort)arg); - } - else if (arg is uint) - { - bytes = BitConverter.GetBytes((uint)arg); - } - else if (arg is ulong) - { - bytes = BitConverter.GetBytes((ulong)arg); - } - else if (arg is BigInteger) - { - bytes = ((BigInteger)arg).ToByteArray(); - } - else - { - try - { - return HandleOtherFormats(format, arg); - } - catch (FormatException e) - { - throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e); - } - } - - switch (thisFmt.ToUpper()) - { - // Binary formatting. - case "B": - baseNumber = 2; - break; - - case "O": - baseNumber = 8; - break; - - case "H": - baseNumber = 16; - break; - // Handle unsupported format strings. - default: - try - { - return HandleOtherFormats(format, arg); - } - catch (FormatException e) - { - throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e); - } - } - - // Return a formatted string. - string numericString = String.Empty; - for (int ctr = bytes.GetUpperBound(0); ctr >= bytes.GetLowerBound(0); ctr--) - { - string byteString = Convert.ToString(bytes[ctr], baseNumber); - if (baseNumber == 2) - byteString = new String('0', 8 - byteString.Length) + byteString; - else if (baseNumber == 8) - byteString = new String('0', 4 - byteString.Length) + byteString; - // Base is 16. - else - byteString = new String('0', 2 - byteString.Length) + byteString; - - numericString += byteString + " "; - } - return numericString.Trim(); - } - - // IFormatProvider.GetFormat implementation. - public object GetFormat(Type formatType) - { - // Determine whether custom formatting object is requested. - if (formatType == typeof(ICustomFormatter)) - return this; - else - return null; - } - - #endregion Public Methods - - #region Private Methods - - private string HandleOtherFormats(string format, object arg) - { - if (arg is IFormattable) - return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture); - else if (arg != null) - return arg.ToString(); - else - return String.Empty; - } - - #endregion Private Methods - } -} \ No newline at end of file diff --git a/IOB-UT-NEXT/BinaryUtils.cs b/IOB-UT-NEXT/BinaryUtils.cs new file mode 100644 index 00000000..d7edbc87 --- /dev/null +++ b/IOB-UT-NEXT/BinaryUtils.cs @@ -0,0 +1,116 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Numerics; + +namespace IOB_UT_NEXT +{ + public class BinaryUtils : IFormatProvider, ICustomFormatter + { + #region Public Methods + + public string Format(string format, object arg, IFormatProvider formatProvider) + { + if (arg == null) return string.Empty; + + // 1. Estrazione del formato (B, O, H) + string thisFmt = string.IsNullOrEmpty(format) ? string.Empty : format.Substring(0, 1).ToUpper(); + + // 2. Pattern matching supportato da C# 7.0+ + byte[] bytes; + switch (arg) + { + case sbyte sb: + bytes = new byte[] { unchecked((byte)sb) }; + break; + + case byte b: + bytes = new byte[] { b }; + break; + + case short s: + bytes = BitConverter.GetBytes(s); + break; + + case ushort us: + bytes = BitConverter.GetBytes(us); + break; + + case int i: + bytes = BitConverter.GetBytes(i); + break; + + case uint ui: + bytes = BitConverter.GetBytes(ui); + break; + + case long l: + bytes = BitConverter.GetBytes(l); + break; + + case ulong ul: + bytes = BitConverter.GetBytes(ul); + break; + + case BigInteger bi: + bytes = bi.ToByteArray(); + break; + + default: + // Se non è un numero supportato, delega alla formattazione standard + return HandleOtherFormats(format, arg); + } + + // 3. Formattazione e unione dei byte + switch (thisFmt) + { + case "B": + return FormatBytes(bytes, 2, 8); + + case "O": + return FormatBytes(bytes, 8, 4); + + case "H": + return FormatBytes(bytes, 16, 2); + + default: + return HandleOtherFormats(format, arg); + } + } + + public object GetFormat(Type formatType) + { + return formatType == typeof(ICustomFormatter) ? this : null; + } + + #endregion Public Methods + + #region Private Methods + + private string FormatBytes(byte[] bytes, int baseNumber, int padding) + { + // Reverse per rispettare l'ordine Big-Endian dell'originale + var formattedParts = bytes.Reverse().Select(b => Convert.ToString(b, baseNumber).PadLeft(padding, '0')); + return string.Join(" ", formattedParts); + } + + private string HandleOtherFormats(string format, object arg) + { + try + { + // Pattern matching base disponibile in C# 7.0 + if (arg is IFormattable formattable) + { + return formattable.ToString(format, CultureInfo.CurrentCulture); + } + return arg.ToString(); + } + catch (FormatException e) + { + throw new FormatException($"The format of '{format}' is invalid.", e); + } + } + + #endregion Private Methods + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/IOB-UT-NEXT.csproj b/IOB-UT-NEXT/IOB-UT-NEXT.csproj index 2ee59c5c..298588a6 100644 --- a/IOB-UT-NEXT/IOB-UT-NEXT.csproj +++ b/IOB-UT-NEXT/IOB-UT-NEXT.csproj @@ -215,7 +215,7 @@ - + diff --git a/IOB-UT-NEXT/IobConfiguration.cs b/IOB-UT-NEXT/IobConfiguration.cs deleted file mode 100644 index 9f91c40a..00000000 --- a/IOB-UT-NEXT/IobConfiguration.cs +++ /dev/null @@ -1,175 +0,0 @@ -using IOB_UT_NEXT; -using System; -using System.Collections.Generic; - -namespace IOB_UT_NEXT -{ - /// - /// Classe principale di configurazione di base per IOB, da cui derivano configurazioni + articolate x singoli IOB - /// - [Serializable] - public class IobConfiguration - { - #region Public Constructors - - /// - /// Avvio configurazione DUMMY - /// - public IobConfiguration() - { - } - - /// - /// Avvio configurazione da file di conf - /// - /// File di conf json/yaml valido - public IobConfiguration(string pathConfFile) - { - } - - #endregion Public Constructors - - #region Public Properties - - /// - /// Valore intero corrispondente ai BIT da filtrare x blinking - /// - public int BLINK_FILT { get; set; } = 0; - - /// - /// Indirizzo Ip del CNC Controllato - /// - public string cncIpAddr { get; set; } = "127.0.0.1"; - - /// - /// Indirizzo Ip per PING dell'impianto (se NON valorizzato usa cncIpAddr x ping) - /// - public string cncPingAddr { get; set; } = ""; - - /// - /// Porta del CNC Controllato - /// - public string cncPort { get; set; } = "0"; - - /// - /// Codice univoco IOB - /// - public string codIOB { get; set; } = "ND"; - - /// - /// TipoCPU (es: Siemens) - /// - public string cpuType { get; set; } = ""; - - /// - /// Indica che sono disabilitati i Task2Exe (tipicamente gestione scrittura verso PLC) - /// - public bool disableExeTask { get; set; } = false; - - /// - /// Indica che sono disabilitate le fasi controllo stato/semafori (tipicamente x impianti - /// con PLC "suddivisi", PLC + HMI) - /// - public bool disableStateCh { get; set; } = false; - - /// - /// Indica se le code vadano gestite su redis o meno - /// - public bool EnableRedisQueue { get; set; } = false; - - /// - /// Nome del file IOB di avvio (REDIS - MAN) - /// - public string filenameIOB { get; set; } = "ND"; - - /// - /// Nome file di INI - /// - public string iniFileName { get; set; } = ""; - - /// - /// Array degli elementi di traduzione item - /// - public Dictionary itemTranslation { get; set; } = new Dictionary(); - - /// - /// Valore MAX per countdown segnali blinking - /// - public int MAX_COUNTER_BLINK { get; set; } = 10; - - /// - /// Minimo delta in sec x considerare variazioni info - /// - public int minDeltaSec { get; set; } = 2; - - /// - /// Modello della macchina - /// - public string model { get; set; } = "ND"; - - /// - /// Dizionario dei parametri opzionali - /// - public Dictionary optPar { get; set; } = new Dictionary(); - - /// - /// Timeout test PING - /// - public int pingMsTimeout { get; set; } = 500; - - /// - /// Rack (Siemens S7) - /// - public short rack { get; set; } = 0; - -#if false - /// - /// Dati di conf del server MoonPro cui comunicare - /// - public serverMapo serverData { get; set; } = new serverMapo("127.0.0.1", "/", "/IOB/input/", "/IOB/flog/", "/IOB/ulog/", "/IOB", "/IOB/enabled/", "/sendReboot.aspx?idxMacchina=", "/IOB/getCurrOdlStart/", "SteamWare", "/IOB/forceSplitOdlFull", "/IOB/getIdlePeriod", "/IOB/rawTransfJson"); -#endif - - /// - /// Slot (Siemens S7) - /// - public short slot { get; set; } = 0; - - /// - /// Fattore lambda (innovazione) per calcolo EWMA valore TCiclo corrente - /// - public double TCLambda { get; set; } = 0.4; - - /// - /// Fattore massimo ammesso di delay x il TCiclo - /// - public double TCMaxDelayFactor { get; set; } = 1.2; - - /// - /// Incremento amssimo pezzi per cui fare calcolo del tempociclo attuale - /// - public double TCMaxIncrPz { get; set; } = 2; - - /// - /// Tipologia dell'adapter/CNC Controllato - /// - public tipoAdapter tipoIob { get; set; } = tipoAdapter.SIMULA; - - /// - /// Vendor della macchina - /// - public string vendor { get; set; } = "ND"; - - /// - /// Versione IOB - /// - public string versIOB { get; set; } = "0"; - - /// - /// Attesa riconnessione standard - /// - public int waitRecMSec { get; set; } = 59000; - - #endregion Public Properties - } - -} \ No newline at end of file diff --git a/IOB-UT-NEXT/baseUtils.cs b/IOB-UT-NEXT/baseUtils.cs index 4d9d95d0..aab1b465 100644 --- a/IOB-UT-NEXT/baseUtils.cs +++ b/IOB-UT-NEXT/baseUtils.cs @@ -73,39 +73,23 @@ namespace IOB_UT_NEXT #endregion Public Properties #region Public Methods - /// /// formatta un numero in forma binaria 0/1 /// - /// - /// - public static string binaryForm(int valore) + /// Il valore numerico (int, uint, short, byte, ecc.) + /// La stringa binaria formattata + public static string binaryForm(T valore) where T : struct { - string answ = ""; try { - answ = string.Format(new BinaryUtils(), "{0:B}", valore); + // Il compilatore passerà automaticamente il tipo corretto (int, uint, ecc.) + // alla tua classe BinaryUtils, che lo gestirà nel suo blocco switch. + return string.Format(new BinaryUtils(), "{0:B}", valore); } catch - { } - return answ; - } - - /// - /// formatta un numero in forma binaria 0/1 - /// - /// - /// - public static string binaryForm(uint valore) - { - string answ = ""; - try { - answ = string.Format(new BinaryUtils(), "{0:B}", valore); + return string.Empty; } - catch - { } - return answ; } /// @@ -227,64 +211,6 @@ namespace IOB_UT_NEXT return num; } -#if false - /// - /// IP della macchina - /// - /// - public static string GetIP() - { - NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); - String sIpAddr = string.Empty; - try - { - foreach (NetworkInterface adapter in nics) - { - if (sIpAddr == String.Empty)// only return IP Address from first card - { - IPInterfaceProperties properties = adapter.GetIPProperties(); - foreach (var item in properties.UnicastAddresses) - { - if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) - { - sIpAddr = item.Address.ToString(); - } - } - } - } - } - catch (Exception exc) - { - // controllo log permesso... - if (logValuePermit("GetIP")) - { - lg.Error(exc); - } - } - return sIpAddr; - } - - /// - /// Macaddress della macchina - /// - /// - public static string GetMACAddress() - { - NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); - String sMacAddress = string.Empty; - foreach (NetworkInterface adapter in nics) - { - if (sMacAddress == String.Empty)// only return MAC Address from first card - { - IPInterfaceProperties properties = adapter.GetIPProperties(); - //sMacAddress = adapter.GetPhysicalAddress().ToString(); - sMacAddress = string.Join(":", (from z in adapter.GetPhysicalAddress().GetAddressBytes() select z.ToString("X2")).ToArray()); - } - } - return sMacAddress; - } -#endif - /// /// Restituisce una stringa di soli caratteri numerici (stripe caratteri alfabetici) /// @@ -724,11 +650,6 @@ namespace IOB_UT_NEXT #region Private Fields - /// - /// Client HTTP statico e riutilizzabile per tutto il ciclo di vita dell'app - /// - private static readonly HttpClient _httpClient = new HttpClient(); - /// /// Ultima ora registrata x statistiche track urlCall ///