Ancora riorganizzazione codice per separare ambiti

This commit is contained in:
Samuele Locatelli
2026-05-21 18:07:25 +02:00
parent 6dcf2b103a
commit 8a30c6c07e
5 changed files with 124 additions and 405 deletions
-143
View File
@@ -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
}
}
+116
View File
@@ -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
}
}
+1 -1
View File
@@ -215,7 +215,7 @@
<Compile Include="TimeUtils.cs" />
<Compile Include="ToMapo.cs" />
<Compile Include="baseUtils.cs" />
<Compile Include="BinaryFormatter.cs" />
<Compile Include="BinaryUtils.cs" />
<Compile Include="Enums.cs" />
<Compile Include="fileMover.cs" />
<Compile Include="Logging.cs" />
-175
View File
@@ -1,175 +0,0 @@
using IOB_UT_NEXT;
using System;
using System.Collections.Generic;
namespace IOB_UT_NEXT
{
/// <summary>
/// Classe principale di configurazione di base per IOB, da cui derivano configurazioni + articolate x singoli IOB
/// </summary>
[Serializable]
public class IobConfiguration
{
#region Public Constructors
/// <summary>
/// Avvio configurazione DUMMY
/// </summary>
public IobConfiguration()
{
}
/// <summary>
/// Avvio configurazione da file di conf
/// </summary>
/// <param name="pathConfFile">File di conf json/yaml valido</param>
public IobConfiguration(string pathConfFile)
{
}
#endregion Public Constructors
#region Public Properties
/// <summary>
/// Valore intero corrispondente ai BIT da filtrare x blinking
/// </summary>
public int BLINK_FILT { get; set; } = 0;
/// <summary>
/// Indirizzo Ip del CNC Controllato
/// </summary>
public string cncIpAddr { get; set; } = "127.0.0.1";
/// <summary>
/// Indirizzo Ip per PING dell'impianto (se NON valorizzato usa cncIpAddr x ping)
/// </summary>
public string cncPingAddr { get; set; } = "";
/// <summary>
/// Porta del CNC Controllato
/// </summary>
public string cncPort { get; set; } = "0";
/// <summary>
/// Codice univoco IOB
/// </summary>
public string codIOB { get; set; } = "ND";
/// <summary>
/// TipoCPU (es: Siemens)
/// </summary>
public string cpuType { get; set; } = "";
/// <summary>
/// Indica che sono disabilitati i Task2Exe (tipicamente gestione scrittura verso PLC)
/// </summary>
public bool disableExeTask { get; set; } = false;
/// <summary>
/// Indica che sono disabilitate le fasi controllo stato/semafori (tipicamente x impianti
/// con PLC "suddivisi", PLC + HMI)
/// </summary>
public bool disableStateCh { get; set; } = false;
/// <summary>
/// Indica se le code vadano gestite su redis o meno
/// </summary>
public bool EnableRedisQueue { get; set; } = false;
/// <summary>
/// Nome del file IOB di avvio (REDIS - MAN)
/// </summary>
public string filenameIOB { get; set; } = "ND";
/// <summary>
/// Nome file di INI
/// </summary>
public string iniFileName { get; set; } = "";
/// <summary>
/// Array degli elementi di traduzione item
/// </summary>
public Dictionary<string, string> itemTranslation { get; set; } = new Dictionary<string, string>();
/// <summary>
/// Valore MAX per countdown segnali blinking
/// </summary>
public int MAX_COUNTER_BLINK { get; set; } = 10;
/// <summary>
/// Minimo delta in sec x considerare variazioni info
/// </summary>
public int minDeltaSec { get; set; } = 2;
/// <summary>
/// Modello della macchina
/// </summary>
public string model { get; set; } = "ND";
/// <summary>
/// Dizionario dei parametri opzionali
/// </summary>
public Dictionary<string, string> optPar { get; set; } = new Dictionary<string, string>();
/// <summary>
/// Timeout test PING
/// </summary>
public int pingMsTimeout { get; set; } = 500;
/// <summary>
/// Rack (Siemens S7)
/// </summary>
public short rack { get; set; } = 0;
#if false
/// <summary>
/// Dati di conf del server MoonPro cui comunicare
/// </summary>
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
/// <summary>
/// Slot (Siemens S7)
/// </summary>
public short slot { get; set; } = 0;
/// <summary>
/// Fattore lambda (innovazione) per calcolo EWMA valore TCiclo corrente
/// </summary>
public double TCLambda { get; set; } = 0.4;
/// <summary>
/// Fattore massimo ammesso di delay x il TCiclo
/// </summary>
public double TCMaxDelayFactor { get; set; } = 1.2;
/// <summary>
/// Incremento amssimo pezzi per cui fare calcolo del tempociclo attuale
/// </summary>
public double TCMaxIncrPz { get; set; } = 2;
/// <summary>
/// Tipologia dell'adapter/CNC Controllato
/// </summary>
public tipoAdapter tipoIob { get; set; } = tipoAdapter.SIMULA;
/// <summary>
/// Vendor della macchina
/// </summary>
public string vendor { get; set; } = "ND";
/// <summary>
/// Versione IOB
/// </summary>
public string versIOB { get; set; } = "0";
/// <summary>
/// Attesa riconnessione standard
/// </summary>
public int waitRecMSec { get; set; } = 59000;
#endregion Public Properties
}
}
+7 -86
View File
@@ -73,39 +73,23 @@ namespace IOB_UT_NEXT
#endregion Public Properties
#region Public Methods
/// <summary>
/// formatta un numero in forma binaria 0/1
/// </summary>
/// <param name="valore"></param>
/// <returns></returns>
public static string binaryForm(int valore)
/// <param name="valore">Il valore numerico (int, uint, short, byte, ecc.)</param>
/// <returns>La stringa binaria formattata</returns>
public static string binaryForm<T>(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;
}
/// <summary>
/// formatta un numero in forma binaria 0/1
/// </summary>
/// <param name="valore"></param>
/// <returns></returns>
public static string binaryForm(uint valore)
{
string answ = "";
try
{
answ = string.Format(new BinaryUtils(), "{0:B}", valore);
return string.Empty;
}
catch
{ }
return answ;
}
/// <summary>
@@ -227,64 +211,6 @@ namespace IOB_UT_NEXT
return num;
}
#if false
/// <summary>
/// IP della macchina
/// </summary>
/// <returns></returns>
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;
}
/// <summary>
/// Macaddress della macchina
/// </summary>
/// <returns></returns>
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
/// <summary>
/// Restituisce una stringa di soli caratteri numerici (stripe caratteri alfabetici)
/// </summary>
@@ -724,11 +650,6 @@ namespace IOB_UT_NEXT
#region Private Fields
/// <summary>
/// Client HTTP statico e riutilizzabile per tutto il ciclo di vita dell'app
/// </summary>
private static readonly HttpClient _httpClient = new HttpClient();
/// <summary>
/// Ultima ora registrata x statistiche track urlCall
/// </summary>