From 0e2164f6110f8bb0401d2ec9548b1c9561463555 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 21 May 2026 16:24:03 +0200 Subject: [PATCH 1/7] Cleanup aree commetnate + spostamento serializzatori --- IOB-UT-NEXT/Config/Base/IobDto.cs | 17 - IOB-UT-NEXT/Config/Base/OdlDto.cs | 25 - IOB-UT-NEXT/Config/EnumConf.cs | 372 +-------------- IOB-UT-NEXT/Config/IobConfTree.cs | 15 - IOB-UT-NEXT/Config/Special/SpecializedDto.cs | 7 - IOB-UT-NEXT/Config/Special/StepActionDto.cs | 8 - IOB-UT-NEXT/IOB-UT-NEXT.csproj | 2 + IOB-UT-NEXT/Iob/BaseObj.cs | 63 --- .../Iob/Services/DataSerializer.cs | 2 +- .../Iob/Services/XmlDataSerializer.cs | 4 +- IOB-UT-NEXT/JobTask2Exe.cs | 8 - IOB-UT-NEXT/RedisIobCache.cs | 39 -- IOB-UT-NEXT/baseUtils.cs | 37 -- IOB-UT-NEXT/plcMemMapExt.cs | 11 - IOB-WIN-FORM/AdapterForm.Designer.cs | 124 +++-- IOB-WIN-FORM/AdapterForm.cs | 436 +++++------------- IOB-WIN-FORM/IOB-WIN-FORM.csproj | 2 - IOB-WIN-FORM/Iob/Generic.cs | 2 +- IOB-WIN-FORM/Iob/Simula.cs | 4 - IOB-WIN-FORM/MainForm.Designer.cs | 10 - IOB-WIN-FORM/MainForm.cs | 11 - refactoring_wip.md | 21 +- 22 files changed, 185 insertions(+), 1035 deletions(-) rename {IOB-WIN-FORM => IOB-UT-NEXT}/Iob/Services/DataSerializer.cs (98%) rename {IOB-WIN-FORM => IOB-UT-NEXT}/Iob/Services/XmlDataSerializer.cs (92%) diff --git a/IOB-UT-NEXT/Config/Base/IobDto.cs b/IOB-UT-NEXT/Config/Base/IobDto.cs index 4a6bab14..9bb9642f 100644 --- a/IOB-UT-NEXT/Config/Base/IobDto.cs +++ b/IOB-UT-NEXT/Config/Base/IobDto.cs @@ -45,23 +45,6 @@ namespace IOB_UT_NEXT.Config.Base /// public string CodIOB { get; set; } = "ND"; -#if false - /// - /// Codice dei vari codici aggiuntivi IOB multi x funzioni slave (es autoOdl) - /// - public string MultiIobListRaw { get; set; } = ""; - - /// - /// Lista dei vari IOB multi x funzioni slave (es autoOdl) - /// - public List MultiIobList { get; set; } - - /// - /// Lista dei vari IOB multi x funzioni slave (es autoOdl) - /// - public bool IsMultiIobList { get; set; } = false; -#endif - /// /// Tempo di attesa (in minuti) x lettura contapezzi standard (default 30 sec) /// diff --git a/IOB-UT-NEXT/Config/Base/OdlDto.cs b/IOB-UT-NEXT/Config/Base/OdlDto.cs index c54a337f..11678d2e 100644 --- a/IOB-UT-NEXT/Config/Base/OdlDto.cs +++ b/IOB-UT-NEXT/Config/Base/OdlDto.cs @@ -65,30 +65,5 @@ namespace IOB_UT_NEXT.Config.Base /// public int ResetCountMaxPost { get; set; } = 10; -#if false - /// - /// Parametri opzionali di configurazione cambio ODL, ad esempio - /// - OdlDurationHours - /// - IdleStateMin - /// - ResetMinCountPre - /// - ResetMaxCountPost - /// - public Dictionary OptPar { get; set; } = new Dictionary(); - - /// - /// Recupera valore della chiave specifica richiesta - /// - /// - /// - public string OptParGet(string key) - { - string answ = ""; - if (OptPar != null && OptPar.Count > 0 && OptPar.ContainsKey(key)) - { - answ = OptPar[key]; - } - return answ; - } -#endif } } diff --git a/IOB-UT-NEXT/Config/EnumConf.cs b/IOB-UT-NEXT/Config/EnumConf.cs index 1cbfeb43..0a32efc3 100644 --- a/IOB-UT-NEXT/Config/EnumConf.cs +++ b/IOB-UT-NEXT/Config/EnumConf.cs @@ -10,6 +10,7 @@ namespace IOB_UT_NEXT.Config { public class EnumConf { + #region Public Enums /// /// Macro tipologia sistema di comunicazione (macro-adapter) @@ -26,373 +27,6 @@ namespace IOB_UT_NEXT.Config Serial } -#if false - /// - /// Tipologia di adapters ammessi - /// - [JsonConverter(typeof(StringEnumConverter))] - public enum AdapterType - { - /// - /// Adapter SIMULAZIONE - /// - SIMULA, - - /// - /// Adapter Beckhoff - /// - BECKHOFF, - - /// - /// Adapter Beckhoff x CPA (selezionatrici ex Jetco) - /// - BECKHOFF_CPA, - - /// - /// adapter FANUC - /// - FANUC, - - /// - /// File Based exchange generic adapter - /// - FILE_GEN, - - /// - /// File Based exchange Euromap63 - /// - FILE_EUROM63, - - ///// - ///// File Based exchange SCM Xylog - ///// - //FILE_XYLOG, - - /// - /// File Based Log file analisys per Soitaab - /// - FILE_SOITAAB, - - /// - /// Gestione sync FTP - /// - FTP, - - /// - /// Adapter KAWASAKI e-controller - /// - KAWASAKI, - - /// - /// Adapter Icoel per DB (barcode, tracciatura, produzione,...) - /// - IcoelDb, - - /// - /// Adapter Icoel per WS SOAP (sizer) - /// - IcoelSoap, - - /// - /// Adapter non specificato - /// - ND, - - /// - /// Adapter MITSUBISHI con EZCnc lib - /// - MITSUBISHI, - - /// - /// Adapter ModBus TCP generico - /// - MODBUS_TCP, - - /// - /// Adapter ModBus TCP versione Cedax (Giacovelli) - /// - MODBUS_TCP_CEDAX, - - /// - /// Adapter ModBus TCP versione Centerfrigo (Giacovelli) - /// - MODBUS_TCP_CENTERFRIGO, - - /// - /// Adapter modbus (+ file) x FIMAT (Tenditalia) - /// - MODBUS_TCP_FIMAT, - - /// - /// Adapter ModBus TCP versione HAM (Pizzaferri) - /// - MODBUS_TCP_HAM, - - /// - /// Adapter ModBus TCP versione HELPI (Cererie Finassi) - /// - MODBUS_TCP_HELPI, - - /// - /// Adapter Modubus TCP versione IMAX Aeromacchine (Jetco) - /// - MODBUS_TCP_IMAS_AEROMEC, - - /// - /// Adapter Modubus TCP versione Rimor (IMI Remosa) - /// - MODBUS_TCP_RIMOR, - - /// - /// Adapter Modubus TCP versione Saim (Giacovelli) - /// - MODBUS_TCP_SAIM, - - /// - /// Adapter Modubus TCP versione Zetapack (Giacovelli) - /// - MODBUS_TCP_ZETAPACK, - - /// - /// Adapter MTConnect - /// - MTConnect, - - /// - /// Adapter OMRON - /// - OMRON, - - /// - /// Adapter OPC-UA - /// - OpcUa, - - /// - /// Adapter OPC-UA CMS - /// - OpcUaCMS, - - /// - /// Adapter OPC-UA per Ewon - /// - OpcUaEwon, - - /// - /// Adapter OPC-UA per Ewon x Adige (BLM) / STIL - /// - OpcUaEwonAdige, - - /// - /// Adapter OPC-UA per Ewon x BLM / Mecart - /// - OpcUaEwonBLM, - - /// - /// Adapter OPC-UA per Ewon x Monti / Tenditalia - /// - OpcUaEwonMonti, - - /// - /// Adapter OPC-UA per Ewon x Mecolpress (BLM) / STIL - /// - OpcUaEwonMecolpress, - - /// - /// Adapter OPC-UA per KeepWare - /// - OpcUaKwp, - - /// - /// Adapter OPC-UA per KeepWare, UnitechRama - /// - OpcUaKwpRama, - - /// - /// Adapter OPC-UA per IMAS Aeromec / Jetco - /// - OpcUaImasAeromec, - - /// - /// Adapter MBH (es Cimolai) - /// - OpcUaMBH, - - /// - /// Adapter MBH implementazione Cimolai x travel lift - /// - OpcUaMBHCimolai, - - /// - /// Adapter OMRON (es ICOEL) - /// - OpcUaOmron, - - /// - /// Implementaizone OMRON specifica x ICOEL - /// - OpcUaOmronIcoel, - - /// - /// Adapter OPC-UA SCM - /// - OpcUaSCM, - - /// - /// Adapter OPC-UA Siemens generico - /// - OpcUaSiemens, - - /// - /// Adapter OPC-UA Siemens OMP - /// - OpcUaSiemensOMP, - - /// - /// Adapter OPC-UA Siemens Rama - /// - OpcUaSiemensRama, - - /// - /// Adapter OPC-UA Ulma (packaging, Giacovelli) - /// - OpcUaUlma, - - /// - /// Adapter OSAI CNDEX (Cndex) - /// - OSAI_CNDEX, - - /// - /// Adapter OSAI OPEN (ws) - /// - OSAI_OPEN, - - /// - /// Adapter OSAI VB6 - /// - OSAI_VB6, - - /// - /// Adapter tipo watchdog via ping (per impianti spenti e non rilevati) - /// - PingWatchdog, - - /// - /// Adapter REST (base) - /// - REST, - - /// - /// Adapter REST Citizen - /// - REST_CITIZEN, - - /// - /// Shelly's Device (tipicamente PM series) - /// - Shelly, - - /// - /// Adapter SIEMENS - /// - SIEMENS, - - /// - /// Adapter SIEMENS, interfaccia versione APROCHIM (filtro liquidi rettifiche) - /// - SIEMENS_APROCHIM, - - /// - /// Adapter SIEMENS, interfaccia versione VIPA @2001 - /// - SIEMENS_AT2001, - - /// - /// Adapter SIEMENS, interfaccia versione FAPE (punzonatrici) vers 2018 - /// - SIEMENS_FAPE, - - /// - /// Adapter SIEMENS, interfaccia versione FAPE (punzonatrici) vers 2024 - /// - SIEMENS_FAPE_2, - - /// - /// Adapter SIEMENS, interfaccia versione COMECA (impianti gestione GNL) - /// - SIEMENS_COMECA, - - /// - /// Adapter SIEMENS, interfaccia versione COMUR (dentatrice) - /// - SIEMENS_COMUR, - - /// - /// Adapter SIEMENS, interfaccia versione COSMAP (transfer smerigliatrice donati) - /// - SIEMENS_COSMAP, - - /// - /// Adapter SIEMENS, interfaccia versione INGENIA (Valvital, Automazione) - /// - SIEMENS_INGENIA, - - /// - /// Adapter SIEMENS, interfaccia versione LASCO (Valvital, Pressa Bilancere) - /// - SIEMENS_LASCO, - - /// - /// Adapter SIEMENS, interfaccia versione NWSE (Giacovelli, impianto filtrazione NWS) - /// - SIEMENS_NWSE, - - /// - /// Adapter SIEMENS, interfaccia versione PRESSOIL + CEI (Valvital, Pressa Idraulica) - /// - SIEMENS_PRESSOIL_CEI, - - /// - /// Adapter SIEMENS, interfaccia verisone RobotService (Donati, smerigliatrici) - /// - SIEMENS_ROBOTSERVICE, - - /// - /// Adapter SIEMENS, interfaccia versione SAET (Valvital, forni / tempra) - /// - SIEMENS_SAET, - - /// - /// Adapter SIEMENS, interfaccia versione SIMEC (Valvital, taglio) - /// - SIEMENS_SIMEC, - - /// - /// Adapter SIEMENS, interfaccia versione Torri - /// - SIEMENS_TORRI, - - /// - /// Adapter SOAP x bilance Gomba - /// - SOAP_GOMBA, - - /// - /// Adapter basato su DB scambio Microsoft SqlServer, macchine LANTEK - /// - SQLSERVER_LANTEK, - - /// - /// Adapter basato su DB scambio Microsoft SqlServer, macchine PAMA - /// - SQLSERVER_PAMA, - - /// - /// Metodi di WPS WebPageScraping (es x compressori Atlas Copco) - /// - WPS - } -#endif + #endregion Public Enums } -} +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Config/IobConfTree.cs b/IOB-UT-NEXT/Config/IobConfTree.cs index d7d9c13b..c6c84b86 100644 --- a/IOB-UT-NEXT/Config/IobConfTree.cs +++ b/IOB-UT-NEXT/Config/IobConfTree.cs @@ -659,21 +659,6 @@ namespace IOB_UT_NEXT.Config { newConfObj.Special.OpcUaConf = JsonConvert.DeserializeObject(jsonData); newConfObj.lgDebug($"Decodifica aree OpcUaParamConf: trovati {newConfObj.Special.OpcUaConf.paramsEndThresh.Count} valori paramsEndThresh"); -#if false - // sistemo se ci sono dati memMap... - if (newConfObj.Memory == null) - { - newConfObj.Memory = new plcMemMapExt(); - } - try - { - newConfObj.Memory = JsonConvert.DeserializeObject(jsonData); - } - catch (Exception exc) - { - newConfObj.lgError($"Eccezione in decodifica conf json{Environment.NewLine}{exc}"); - } -#endif // elimino conf memoria da area OPC che tanto è già OK... newConfObj.Special.OpcUaConf.mMapRead = new Dictionary(); diff --git a/IOB-UT-NEXT/Config/Special/SpecializedDto.cs b/IOB-UT-NEXT/Config/Special/SpecializedDto.cs index ed5ecba5..953e378c 100644 --- a/IOB-UT-NEXT/Config/Special/SpecializedDto.cs +++ b/IOB-UT-NEXT/Config/Special/SpecializedDto.cs @@ -18,13 +18,6 @@ namespace IOB_UT_NEXT.Config.Special /// public MemBankDto BankConf { get; set; } -#if false - /// - /// Configurazione specifica per Fanuc - /// - public FanucDto FanucConf { get; set; } -#endif - /// /// Configurazione specifica per gestione file esterni (es Saim x Giacovelli) /// diff --git a/IOB-UT-NEXT/Config/Special/StepActionDto.cs b/IOB-UT-NEXT/Config/Special/StepActionDto.cs index 49e8b969..2e37ec51 100644 --- a/IOB-UT-NEXT/Config/Special/StepActionDto.cs +++ b/IOB-UT-NEXT/Config/Special/StepActionDto.cs @@ -31,14 +31,6 @@ namespace IOB_UT_NEXT.Config.Special /// public string CompoValMMap { get; set; } = null; -#if false - /// - /// Valore composto (a partire da altri valori in ProdData),da usare se != null - /// Sostituzione token espressi nel formato [[token]] - /// - public string CompoValProdData { get; set; } = null; -#endif - /// /// Valore fix da inviare alla memoria se != null /// diff --git a/IOB-UT-NEXT/IOB-UT-NEXT.csproj b/IOB-UT-NEXT/IOB-UT-NEXT.csproj index be331be1..8d65d909 100644 --- a/IOB-UT-NEXT/IOB-UT-NEXT.csproj +++ b/IOB-UT-NEXT/IOB-UT-NEXT.csproj @@ -202,6 +202,8 @@ + + diff --git a/IOB-UT-NEXT/Iob/BaseObj.cs b/IOB-UT-NEXT/Iob/BaseObj.cs index a7c5c09c..c53a9160 100644 --- a/IOB-UT-NEXT/Iob/BaseObj.cs +++ b/IOB-UT-NEXT/Iob/BaseObj.cs @@ -371,69 +371,6 @@ namespace IOB_UT_NEXT.Iob #region Public Methods -#if false - /// - /// Effettua chiamata URL e restituisce risultato - /// - /// - /// invio in modalità async (NON GARANTITO ordine...) - /// - public static async Task callUrl(string URL, bool doAsync) - { - string answ = ""; - // verifica URL preliminare - if (URL.StartsWith("http://ND")) - { - lg.Warn($"callUrl | wrong URL data: {URL}"); - } - else - { - if (doAsync) - { - answ = await utils.callUrlAsync(URL); - } - else - { - answ = await Task.Run(() => utils.callUrl(URL)); - } - - if (urlRandWait > 0) - { - // NON blocca il thread, libera risorse per le altre 20 istanze - await Task.Delay(rnd.Next(urlRandWait / 10, urlRandWait)); - } - } - return answ; - } - - /// - /// Effettua chiamata URL e restituisce risultato - /// - /// - /// - /// invio in modalità async (NON GARANTITO ordine...) - /// - public static async Task callUrlWithPayloadAsync(string URL, string payload, bool doAsync) - { - string answ = ""; - if (doAsync) - { - answ = await utils.callUrlAsync(URL, payload); - } - else - { - answ = await Task.Run(() => utils.callUrl(URL, payload)); - } - - if (urlRandWait > 0) - { - // NON blocca il thread, libera risorse per le altre 20 istanze - await Task.Delay(rnd.Next(urlRandWait / 10, urlRandWait)); - } - return answ; - } -#endif - /// /// processa dataLayer e se necessario salva/mostra /// diff --git a/IOB-WIN-FORM/Iob/Services/DataSerializer.cs b/IOB-UT-NEXT/Iob/Services/DataSerializer.cs similarity index 98% rename from IOB-WIN-FORM/Iob/Services/DataSerializer.cs rename to IOB-UT-NEXT/Iob/Services/DataSerializer.cs index 99ed9405..d0bdad59 100644 --- a/IOB-WIN-FORM/Iob/Services/DataSerializer.cs +++ b/IOB-UT-NEXT/Iob/Services/DataSerializer.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; -namespace IOB_WIN_FORM.Iob.Services +namespace IOB_UT_NEXT.Iob.Services { /// /// Gestisce tutte le operazioni di serializzazione e deserializzazione dei dati. diff --git a/IOB-WIN-FORM/Iob/Services/XmlDataSerializer.cs b/IOB-UT-NEXT/Iob/Services/XmlDataSerializer.cs similarity index 92% rename from IOB-WIN-FORM/Iob/Services/XmlDataSerializer.cs rename to IOB-UT-NEXT/Iob/Services/XmlDataSerializer.cs index 2770b758..e05e339c 100644 --- a/IOB-WIN-FORM/Iob/Services/XmlDataSerializer.cs +++ b/IOB-UT-NEXT/Iob/Services/XmlDataSerializer.cs @@ -2,7 +2,7 @@ using System; using System.IO; using System.Xml.Serialization; -namespace IOB_WIN_FORM.Iob.Services +namespace IOB_UT_NEXT.Iob.Services { /// /// Gestisce le operazioni di serializzazione e deserializzazione in formato XML. @@ -30,8 +30,6 @@ namespace IOB_WIN_FORM.Iob.Services } catch (Exception ex) { - // Log l'errore se necessario. In un contesto di refactoring, - // potremmo voler passare l'eccezione verso l'alto. throw new InvalidOperationException($"Errore durante la serializzazione XML per il tipo {typeof(T).Name}", ex); } } diff --git a/IOB-UT-NEXT/JobTask2Exe.cs b/IOB-UT-NEXT/JobTask2Exe.cs index da465db4..c43adffc 100644 --- a/IOB-UT-NEXT/JobTask2Exe.cs +++ b/IOB-UT-NEXT/JobTask2Exe.cs @@ -23,14 +23,6 @@ namespace IOB_UT_NEXT #endregion Public Constructors -#if false - public JobTaskData(string codTav, Dictionary newDict) - { - CodTav = codTav; - RawData = JsonConvert.SerializeObject(newDict); - } -#endif - #region Public Properties /// diff --git a/IOB-UT-NEXT/RedisIobCache.cs b/IOB-UT-NEXT/RedisIobCache.cs index d4fb3ca7..884d02f0 100644 --- a/IOB-UT-NEXT/RedisIobCache.cs +++ b/IOB-UT-NEXT/RedisIobCache.cs @@ -874,12 +874,6 @@ namespace IOB_UT_NEXT /// num max di elementi da recuperare public List redQueuePopAll(RedisKey queueName) { - // vecchio metodo (NON resetta) -#if false - long nCount = currDb.ListLength(queueName); - List listData = currDb.ListRange(queueName, 0, nCount).ToList(); - return listData; -#endif // lettura + reset in blocco var listData = currDb.ListRange(queueName, 0, -1).ToList(); if (listData.Count > 0) @@ -888,16 +882,6 @@ namespace IOB_UT_NEXT } return listData; - // in alternativa lettura 1:1 -#if false - var results = new List(); - RedisValue item; - while ((item = currDb.ListLeftPop(queueName)) != RedisValue.Null) - { - results.Add(item); - } - return results; -#endif } /// @@ -907,14 +891,6 @@ namespace IOB_UT_NEXT /// num max di elementi da recuperare public List redQueuePopList(RedisKey queueName, int maxElem) { - // vecchia modalità senza rimozione -#if false - long nCount = currDb.ListLength(queueName); - nCount = nCount < maxElem ? nCount : maxElem; - List listData = currDb.ListRange(queueName, 0, nCount).ToList(); - return listData; -#endif - // nuovo metodo con rimozione var results = new List(maxElem); @@ -1454,21 +1430,6 @@ namespace IOB_UT_NEXT // Memorizza i dettagli nella Hash Table: field = eventId, value = dataQty await currDb.HashSetAsync(rkeyHash, eventId, dataQty.ToString()); -#if false - // Crea un batch per eseguire le operazioni in modo transazionale - var batch = cache.CreateBatch(); - - // Aggiungi al Sorted Set: score = timestamp, member = eventId - await batch.SortedSetAddAsync(EventsTimeSeriesKey, eventId, timestamp); - - // Memorizza i dettagli nella Hash Table: field = eventId, value = dataExchanged - await batch.HashSetAsync(EventDetailsHashKey, eventId, dataExchanged.ToString()); // StackExchange.Redis memorizza RedisValue - - // Esegui il batch in modo sincrono (o non va...) - batch.Execute(); - //await batch.ExecuteAsync(); -#endif - Logging.Instance.Debug($"Evento registrato: ID={eventId}, Timestamp={timestamp}, Dati={dataQty}"); return eventId; } diff --git a/IOB-UT-NEXT/baseUtils.cs b/IOB-UT-NEXT/baseUtils.cs index 330d2642..ead71e34 100644 --- a/IOB-UT-NEXT/baseUtils.cs +++ b/IOB-UT-NEXT/baseUtils.cs @@ -1121,41 +1121,4 @@ namespace IOB_UT_NEXT #endregion Private Methods } - /// - /// Override metodo WebClient con gesitone TimeOut corto - /// - public class WebClientWT : WebClient - { - #region Protected Properties - - /// - /// timeout da conf - /// - protected int urlCallTOut - { - get - { - int answ = 5000; - answ = baseUtils.CRI("urlCallTOut"); - if (answ < 0 || answ > 10000) - { - answ = 3000; - } - return answ; - } - } - - #endregion Protected Properties - - #region Protected Methods - - protected override WebRequest GetWebRequest(Uri address) - { - WebRequest wr = base.GetWebRequest(address); - wr.Timeout = urlCallTOut; // timeout in milliseconds (ms) - return wr; - } - - #endregion Protected Methods - } } \ No newline at end of file diff --git a/IOB-UT-NEXT/plcMemMapExt.cs b/IOB-UT-NEXT/plcMemMapExt.cs index e93bab12..74d9fa29 100644 --- a/IOB-UT-NEXT/plcMemMapExt.cs +++ b/IOB-UT-NEXT/plcMemMapExt.cs @@ -52,16 +52,5 @@ namespace IOB_UT_NEXT /// public Dictionary> DataDecodMap { get; set; } = new Dictionary>(); -#if false - /// - /// Base del NameSpace usato per le funzionalità di translate (parametri ACT-SET), da inserire come PRE - /// - public string BaseKeyTranslate { get; set; } = ""; - - /// - /// Dizionario per la traduzione delle ricette (se gestite) tra valori acquisiti in dossier e impostazioni da inviare (ACTual, SETup) - /// - public Dictionary RecipeKeyTranslate { get; set; } = new Dictionary(); -#endif } } \ No newline at end of file diff --git a/IOB-WIN-FORM/AdapterForm.Designer.cs b/IOB-WIN-FORM/AdapterForm.Designer.cs index 5edc3218..a676c61c 100644 --- a/IOB-WIN-FORM/AdapterForm.Designer.cs +++ b/IOB-WIN-FORM/AdapterForm.Designer.cs @@ -1,35 +1,21 @@ namespace IOB_WIN_FORM { - partial class AdapterForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - -#if false - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) + partial class AdapterForm { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } -#endif + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AdapterForm)); this.gather = new System.Windows.Forms.Timer(this.components); @@ -164,7 +150,7 @@ // // tableLayoutPanel1 // - this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 10; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 24F)); @@ -197,8 +183,8 @@ // // restart // - this.restart.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.restart.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.restart.BackColor = System.Drawing.Color.Red; this.restart.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); @@ -213,8 +199,8 @@ // // stop // - this.stop.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.stop.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.stop.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.stop.ForeColor = System.Drawing.SystemColors.ControlText; @@ -240,8 +226,8 @@ // // start // - this.start.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.start.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.start.BackColor = System.Drawing.SystemColors.Control; this.start.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); @@ -256,8 +242,8 @@ // // bIN // - this.bIN.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.bIN.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.bIN.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bIN.Location = new System.Drawing.Point(2, 2); @@ -271,8 +257,8 @@ // // bOUT // - this.bOUT.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.bOUT.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.bOUT.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bOUT.Location = new System.Drawing.Point(879, 2); @@ -299,8 +285,8 @@ // // lblPzCountIob // - this.lblPzCountIob.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.lblPzCountIob.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblPzCountIob.AutoSize = true; this.lblPzCountIob.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); @@ -621,8 +607,8 @@ // // panel2 // - this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel2.AutoScroll = true; this.panel2.Controls.Add(this.lblTaskLog); @@ -889,8 +875,8 @@ // // flowLayoutPanel1 // - this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.flowLayoutPanel1.Controls.Add(this.lblLogfile); this.flowLayoutPanel1.Location = new System.Drawing.Point(6, 22); @@ -924,8 +910,8 @@ // // tableLayoutPanel2 // - this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel2.BackColor = System.Drawing.Color.Black; this.tableLayoutPanel2.ColumnCount = 4; @@ -988,7 +974,7 @@ // // lblRawData // - this.lblRawData.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + this.lblRawData.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblRawData.AutoSize = true; this.lblRawData.Font = new System.Drawing.Font("Microsoft Sans Serif", 7F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); @@ -1025,7 +1011,7 @@ // // lblOutMessage3 // - this.lblOutMessage3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + this.lblOutMessage3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblOutMessage3.AutoSize = true; this.lblOutMessage3.Font = new System.Drawing.Font("Microsoft Sans Serif", 7F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); @@ -1039,7 +1025,7 @@ // // lblOutMessage2 // - this.lblOutMessage2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + this.lblOutMessage2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblOutMessage2.AutoSize = true; this.lblOutMessage2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); @@ -1052,8 +1038,8 @@ // // tabData // - this.tabData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) + this.tabData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabData.Controls.Add(this.tabRealtime); this.tabData.Controls.Add(this.tabLog); @@ -1111,26 +1097,26 @@ this.ResumeLayout(false); this.PerformLayout(); - } + } - #endregion + #endregion - private System.Windows.Forms.Timer gather; - private System.Windows.Forms.StatusStrip statusStrip1; - private System.Windows.Forms.ToolStripStatusLabel lblCNC; - private System.Windows.Forms.ToolStripStatusLabel lblSrvUrl; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; - private System.Windows.Forms.Button stop; - private System.Windows.Forms.Button start; - private System.Windows.Forms.TextBox nLines; - private System.Windows.Forms.Button bIN; - private System.Windows.Forms.Timer displTimer; - private System.Windows.Forms.Button restart; - private System.Windows.Forms.CheckBox chkForceDequeue; - private System.Windows.Forms.Button bOUT; - private System.Windows.Forms.Label lblQueueLenTop; - private System.Windows.Forms.Label lblPzCountIob; - private System.Windows.Forms.Label lblPzCountMac; + private System.Windows.Forms.Timer gather; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel lblCNC; + private System.Windows.Forms.ToolStripStatusLabel lblSrvUrl; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.Button stop; + private System.Windows.Forms.Button start; + private System.Windows.Forms.TextBox nLines; + private System.Windows.Forms.Button bIN; + private System.Windows.Forms.Timer displTimer; + private System.Windows.Forms.Button restart; + private System.Windows.Forms.CheckBox chkForceDequeue; + private System.Windows.Forms.Button bOUT; + private System.Windows.Forms.Label lblQueueLenTop; + private System.Windows.Forms.Label lblPzCountIob; + private System.Windows.Forms.Label lblPzCountMac; private System.Windows.Forms.TabPage tabMes; private System.Windows.Forms.Button btnForceAutoOdl; private System.Windows.Forms.Panel panel1; diff --git a/IOB-WIN-FORM/AdapterForm.cs b/IOB-WIN-FORM/AdapterForm.cs index 89233c02..03a838c5 100644 --- a/IOB-WIN-FORM/AdapterForm.cs +++ b/IOB-WIN-FORM/AdapterForm.cs @@ -1326,6 +1326,8 @@ namespace IOB_WIN_FORM /// private readonly SemaphoreSlim _plcLock = new SemaphoreSlim(1, 1); + private readonly object _threadLock = new object(); + /// /// Cancellation token x processi verso macchina /// @@ -1346,27 +1348,21 @@ namespace IOB_WIN_FORM private FormWindowState _lastState = FormWindowState.Minimized; + private Thread _machineThread; private Task _workerTask; + /// + /// Counter esecuzione WorkerLoopMachine + /// + private int idxWLM = 0; + + /// + /// Counter esecuzione WorkerLoopServer + /// + private int idxWLS = 0; + private bool stopForced = false; -#if false - /// - /// Contatore chiamate timers x debug timing - /// - private Dictionary TimersCycleCount = new Dictionary(); - - /// - /// Contatore durata exec x debug timing - /// - private Dictionary TimersCycleElaps = new Dictionary(); - - /// - /// Dizionario scadenza timers interni x esecuzione dei vari task a differente frequenza di chiamata - /// - private Dictionary TimersVeto = new Dictionary(); -#endif - /// /// Obj gestione Timer per esecuzione Task con Machine /// @@ -1438,7 +1434,6 @@ namespace IOB_WIN_FORM string callKey = iobObj.redisMan.redHash($"IOB:Status:{IOBConfFull.General.FilenameIOB}:CallStats"); await CallMetricsCollector.LoadFromRedisAsync(iobObj.redisMan.currDb, callKey); - // Start timer periodico comunicazione gather.Interval = IOBConfFull.General.Timers.MsUI; gather.Enabled = true; @@ -1561,64 +1556,6 @@ namespace IOB_WIN_FORM } } - /// - /// Verifica scadenza task nell'oggetto Pool - /// - /// - private async Task checkScadPoolAsync() - { - DateTime adesso = DateTime.Now; - bool sendDone = false; - // ciclo su tutti i timers enum superiori a VHF - var priorities = (gatherCycle[])Enum.GetValues(typeof(gatherCycle)); - // prendo solo > VHF e ordino discendenti x dare priorità ai più rari... - var ordered = priorities.Where(x => x > gatherCycle.VHF).OrderByDescending(x => x); - foreach (gatherCycle item in ordered) - { - if (TimerServer.Veto.ContainsKey(item)) - { - if (TimerServer.Veto[item] <= adesso) - { - // se non ho già processato a questo giro... - if (!sendDone) - { - TimerServer.CycleCount[item]++; - - Stopwatch sw = Stopwatch.StartNew(); - await iobObj.doServerTaskAsync(item); - sw.Stop(); - - sendDone = true; - // metto una piccola attesa se ho altre scadenze - TimerServer.CycleElaps[item] += sw.Elapsed.TotalMilliseconds; - // metto nuova scadenza perturbata 10% - TimerServer.Veto[item] = adesso.AddMilliseconds(iobObj.IOBConfFull.TimerMs(item, 0.1)); - } - // log + reset se ho contato ALMENO 100 exec o il tempo totale supera 1000msec - int limMs = 10000; - double totalMs = TimerServer.CycleElaps.ContainsKey(item) ? TimerServer.CycleElaps[item] : 0; - if (TimerServer.CycleCount[item] >= 100 || totalMs > limMs) - { - int nCount = Math.Max(TimerServer.CycleCount[item], 1); - lgDebug($"Timer.{TimerServer.Contesto} | checkScadPoolAsync | {item} | {totalMs / nCount:F1}ms x {nCount}"); - TimerServer.CycleCount[item] = 0; - TimerServer.CycleElaps[item] = 0; - } - } - } - else - { - TimerServer.Veto.Add(item, adesso.AddMilliseconds(iobObj.IOBConfFull.TimerMs(item, 0))); - TimerServer.CycleCount.Add(item, 0); - if (!TimerServer.CycleElaps.ContainsKey(item)) - { - TimerServer.CycleElaps.Add(item, 0); - } - } - } - } - - /// /// Verifica scadenza task Machine /// @@ -1676,14 +1613,11 @@ namespace IOB_WIN_FORM } } -#if false /// - /// Verifica scadenza task + /// Verifica scadenza task nell'oggetto Pool /// - /// Indica se siano abilitate operazioni Pool (Thread Safe) - /// Indica se siano abilitate le operazioni Single Thread /// - private async Task checkScad(bool enabPool, bool enabSTID) + private async Task checkScadPoolAsync() { DateTime adesso = DateTime.Now; bool sendDone = false; @@ -1693,47 +1627,48 @@ namespace IOB_WIN_FORM var ordered = priorities.Where(x => x > gatherCycle.VHF).OrderByDescending(x => x); foreach (gatherCycle item in ordered) { - if (TimersVeto.ContainsKey(item)) + if (TimerServer.Veto.ContainsKey(item)) { - if (TimersVeto[item] <= adesso) + if (TimerServer.Veto[item] <= adesso) { // se non ho già processato a questo giro... if (!sendDone) { - TimersCycleCount[item]++; + TimerServer.CycleCount[item]++; + Stopwatch sw = Stopwatch.StartNew(); - - // chiamata di processing x frequenza - await iobObj.getAndSendAsync(item, enabPool, enabSTID); - + await iobObj.doServerTaskAsync(item); sw.Stop(); + sendDone = true; // metto una piccola attesa se ho altre scadenze - TimersCycleElaps[item] += sw.Elapsed.TotalMilliseconds; + TimerServer.CycleElaps[item] += sw.Elapsed.TotalMilliseconds; // metto nuova scadenza perturbata 10% - TimersVeto[item] = adesso.AddMilliseconds(iobObj.IOBConfFull.TimerMs(item, 0.1)); + TimerServer.Veto[item] = adesso.AddMilliseconds(iobObj.IOBConfFull.TimerMs(item, 0.1)); } // log + reset se ho contato ALMENO 100 exec o il tempo totale supera 1000msec int limMs = 10000; - double totalMs = TimersCycleElaps.ContainsKey(item) ? TimersCycleElaps[item] : 0; - if (TimersCycleCount[item] >= 100 || totalMs > limMs) + double totalMs = TimerServer.CycleElaps.ContainsKey(item) ? TimerServer.CycleElaps[item] : 0; + if (TimerServer.CycleCount[item] >= 100 || totalMs > limMs) { - int nCount = Math.Max(TimersCycleCount[item], 1); - lgDebug($"checkScad | {item} | {totalMs / nCount:F1}ms x {nCount}"); - TimersCycleCount[item] = 0; - TimersCycleElaps[item] = 0; + int nCount = Math.Max(TimerServer.CycleCount[item], 1); + lgDebug($"Timer.{TimerServer.Contesto} | checkScadPoolAsync | {item} | {totalMs / nCount:F1}ms x {nCount}"); + TimerServer.CycleCount[item] = 0; + TimerServer.CycleElaps[item] = 0; } } } else { - TimersVeto.Add(item, adesso.AddMilliseconds(iobObj.IOBConfFull.TimerMs(item, 0))); - TimersCycleCount.Add(item, 0); - if (!TimersCycleElaps.ContainsKey(item)) TimersCycleElaps.Add(item, 0); + TimerServer.Veto.Add(item, adesso.AddMilliseconds(iobObj.IOBConfFull.TimerMs(item, 0))); + TimerServer.CycleCount.Add(item, 0); + if (!TimerServer.CycleElaps.ContainsKey(item)) + { + TimerServer.CycleElaps.Add(item, 0); + } } } - } -#endif + } private void ChkEdit_CheckedChanged(object sender, EventArgs e) { @@ -1763,7 +1698,6 @@ namespace IOB_WIN_FORM { } - /// /// Metodo principale esecuzione task in thread background (no interferenza con UI) x processi IO bound /// @@ -1836,7 +1770,6 @@ namespace IOB_WIN_FORM } } - /// /// Metodo principale esecuzione task in thread background (no interferenza con UI) x processi IO bound /// @@ -1860,7 +1793,6 @@ namespace IOB_WIN_FORM // verifico non ci sia veto comunicazioni lettura... if (iobObj.queueInEnabCurr) { - // MAIN: controllo TUTTE le scadenze Server... await checkScadPoolAsync(); @@ -1876,22 +1808,6 @@ namespace IOB_WIN_FORM iobObj.checkVetoQueueIn(); } } -#if false - else - { - // qui attende meno... - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec / 2); - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) - { - if (doLog) - { - lgInfo($"Retry Time Elapsed ({waitRecMSec / 2} ms)--> tryConnect"); - } - lastStartTry = DateTime.Now; - iobObj.tryConnect(); - } - } -#endif } else { @@ -1919,116 +1835,6 @@ namespace IOB_WIN_FORM } } -#if false - /// - /// Metodo principale esecuzione task in thread background (no interferenza con UI) x processi IO bound - /// - /// Richiesta esecuzone su single thread (es FANUC) - /// - private async Task DoExecTasksAsync(bool reqSingle) - { - // Attende il proprio turno. Se un task è già in corso, questo aspetta. - await _plcLock.WaitAsync(); - bool doLog = iobObj.periodicLog; - try - { - // imposto variabili x esecuzione separata task Single Thread / Pooled Thread - bool reqSTE = iobObj.IOBConfFull.General.MachWLoopSingleThread; - bool enabSTID = reqSTE ? reqSingle : true; - bool enabPool = !reqSTE; - - if (enabPool) - { - // check esecuzione SendTask (MsVHF) COMUNQUE... - await iobObj.getAndSendAsync(gatherCycle.VHF, enabPool, enabSTID); - } - // eseguo cicli attivi SOLO se adapter è in EFFETTIVO running... - if (iobObj.adpRunning) - { - if (iobObj.connectionOk) - { - DateTime adesso = DateTime.Now; - // verifico non ci sia veto comunicazioni lettura... - if (iobObj.queueInEnabCurr) - { - if (enabSTID) - { - // se richiesto faccio memory DUMP INIZIALE! - if (iobObj.doStartMemDump) - { - lgInfo("Inizio dump memoria"); - iobObj.saveMemDump(dumpType.STARTUP); - // fatto! non ripeto... - iobObj.doStartMemDump = false; - lgInfo("Finito dump memoria"); - } - } - if (enabPool) - { - // controllo se sia abilitato sampleDump della meoria (periodico) - if (iobObj.doSampleMemory) - { - checkSampleMem(); - } - } - - // MAIN: controllo TUTTE le scadenze... - await checkScad(enabPool, enabSTID); - - // wait opzionale in coda - if (utils.CRI("waitEndCycle") > 0) - { - await Task.Delay(utils.CRI("waitEndCycle")); - } - } - else - { - lgTrace($"VETO queueInEnabCurr | veto attivo | {adesso:yyyy.MM.dd HH:mm:ss}"); - iobObj.checkVetoQueueIn(); - } - } - else - { - // qui attende meno... - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec / 2); - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) - { - if (doLog) - { - lgInfo($"Retry Time Elapsed ({waitRecMSec / 2} ms)--> tryConnect"); - } - lastStartTry = DateTime.Now; - iobObj.tryConnect(); - } - } - } - else - { - if (doLog) - { - lgInfo("Adapter stopped"); - } - // verifico SE debba tentare il riavvio, ovvero NON running ma adpTryRestart - // e non ho riprovato x oltre waitRecMSec - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec); - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) - { - lastStartTry = DateTime.Now; - AvviaAdapter(chkForceDequeue.Checked); - } - } - } - catch (Exception exc) - { - lgError($"Eccezione in fase di DoExecTasksAsync: {Environment.NewLine}{exc}"); - } - finally - { - _plcLock.Release(); - } - } -#endif - /// /// Ferma tutti i componenti adapter + update buttons /// @@ -2527,7 +2333,6 @@ namespace IOB_WIN_FORM /// private void StartWorker() { - //// FixMe ToDo !!! togliere o fare alternativa pooled //if (iobObj.IOBConfFull.General.MachWLoopSingleThread || true) //{ @@ -2577,19 +2382,8 @@ namespace IOB_WIN_FORM _workerTask = Task.Run(() => WorkerLoopAsync(_ctsServer.Token)); lgInfo("--- WORKER SERVER AVVIATO ---"); } - - } - - private Thread _machineThread; - private readonly object _threadLock = new object(); - - -#if false - private BlockingCollection _workQueue = new BlockingCollection(); -#endif - /// /// fermata dell'adapter /// @@ -2656,13 +2450,81 @@ namespace IOB_WIN_FORM } /// - /// Counter esecuzione WorkerLoopMachine + /// Loop di gestione worker /// - private int idxWLM = 0; - /// - /// Counter esecuzione WorkerLoopServer - /// - private int idxWLS = 0; + /// + /// + private async Task WorkerLoopAsync(CancellationToken ct) + { + try + { + lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] Inizio WorkerLoopAsync"); + + while (!ct.IsCancellationRequested) + { + // incremento indice x mostrare esecuzione... + idxWLS++; + idxWLS = idxWLS > 999 ? 0 : idxWLS; + //lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync"); + if (!_isSuspended) + { + try + { + await DoExecServerTasksAsync(false); + } + catch (Exception ex) + { + lgError($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] Errore durante i task: " + ex.Message); + } + } + else + { + lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync suspended"); + // se non fosse stop richiesto da utente... + if (!stopForced) + { + DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec / 2); + // verifica scadenza controllo SE fosse offline x eseguire test riconnessione... + if (iobObj.adpTryRestart && (DateTime.Now > dtVeto) && iobObj.adpRunning && !iobObj.connectionOk) + { + lgTrace($"WorkerLoopAsync sospeso: tentativo riavvio periodico"); + lastStartTry = DateTime.Now; + iobObj.tryConnect(); + } + else + { + lgTrace($"WorkerLoopAsync sospeso: NON esegue task specifici | _isSuspended: {_isSuspended}"); + } + } + } + + // Calcolo del delay dinamico tra standard e suspended da Timers.MsVHF + int currentDelay = _isSuspended ? 10 * IOBConfFull.General.Timers.MsVHF : IOBConfFull.General.Timers.MsVHF; + + // se ho error delay --> log! + if (_errorDelay > 0) + { + currentDelay += _errorDelay; + lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync | delay: {currentDelay}"); + } + + // 4. ATTESA INTERROMPIBILE + // Il delay asincrono permette al sistema di riutilizzare il thread se necessario, + // ma il 'while' garantisce che non inizieremo il prossimo DoExecTasksAsync prematuramente. + //await Task.Delay(currentDelay, ct).ConfigureAwait(false); + await Task.Delay(currentDelay, ct); + + // Logga l'ID Thread + //lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync | End"); + } + lgInfo("WorkerLoopAsync interrotto per cancellation token."); + } + catch (OperationCanceledException) + { + // Eccezione normale quando si preme Stop/Cancel + lgInfo("WorkerLoopAsync interrotto correttamente."); + } + } /// /// Loop di gestione worker comunicazione con la macchina (single threaded) @@ -2745,84 +2607,6 @@ namespace IOB_WIN_FORM } } - /// - /// Loop di gestione worker - /// - /// - /// - private async Task WorkerLoopAsync(CancellationToken ct) - { - try - { - lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] Inizio WorkerLoopAsync"); - - while (!ct.IsCancellationRequested) - { - // incremento indice x mostrare esecuzione... - idxWLS++; - idxWLS = idxWLS > 999 ? 0 : idxWLS; - //lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync"); - if (!_isSuspended) - { - try - { - await DoExecServerTasksAsync(false); - - } - catch (Exception ex) - { - lgError($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] Errore durante i task: " + ex.Message); - } - } - else - { - lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync suspended"); - // se non fosse stop richiesto da utente... - if (!stopForced) - { - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec / 2); - // verifica scadenza controllo SE fosse offline x eseguire test riconnessione... - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto) && iobObj.adpRunning && !iobObj.connectionOk) - { - lgTrace($"WorkerLoopAsync sospeso: tentativo riavvio periodico"); - lastStartTry = DateTime.Now; - iobObj.tryConnect(); - } - else - { - lgTrace($"WorkerLoopAsync sospeso: NON esegue task specifici | _isSuspended: {_isSuspended}"); - } - } - } - - // Calcolo del delay dinamico tra standard e suspended da Timers.MsVHF - int currentDelay = _isSuspended ? 10 * IOBConfFull.General.Timers.MsVHF : IOBConfFull.General.Timers.MsVHF; - - // se ho error delay --> log! - if (_errorDelay > 0) - { - currentDelay += _errorDelay; - lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync | delay: {currentDelay}"); - } - - // 4. ATTESA INTERROMPIBILE - // Il delay asincrono permette al sistema di riutilizzare il thread se necessario, - // ma il 'while' garantisce che non inizieremo il prossimo DoExecTasksAsync prematuramente. - //await Task.Delay(currentDelay, ct).ConfigureAwait(false); - await Task.Delay(currentDelay, ct); - - // Logga l'ID Thread - //lgTrace($"[Thread: {Thread.CurrentThread.ManagedThreadId} ({idxWLS})] WorkerLoopAsync | End"); - } - lgInfo("WorkerLoopAsync interrotto per cancellation token."); - } - catch (OperationCanceledException) - { - // Eccezione normale quando si preme Stop/Cancel - lgInfo("WorkerLoopAsync interrotto correttamente."); - } - } - #endregion Private Methods } } \ No newline at end of file diff --git a/IOB-WIN-FORM/IOB-WIN-FORM.csproj b/IOB-WIN-FORM/IOB-WIN-FORM.csproj index 9df513cc..ca506eea 100644 --- a/IOB-WIN-FORM/IOB-WIN-FORM.csproj +++ b/IOB-WIN-FORM/IOB-WIN-FORM.csproj @@ -133,8 +133,6 @@ - - Form diff --git a/IOB-WIN-FORM/Iob/Generic.cs b/IOB-WIN-FORM/Iob/Generic.cs index 5b06e56a..ab7cb93c 100644 --- a/IOB-WIN-FORM/Iob/Generic.cs +++ b/IOB-WIN-FORM/Iob/Generic.cs @@ -1,7 +1,7 @@ using EgwProxy.Ftp; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_WIN_FORM.Iob.Services; +using IOB_UT_NEXT.Iob.Services; using MapoSDK; using MathNet.Numerics.Statistics; using Newtonsoft.Json; diff --git a/IOB-WIN-FORM/Iob/Simula.cs b/IOB-WIN-FORM/Iob/Simula.cs index 58c82e1b..8ac522b9 100644 --- a/IOB-WIN-FORM/Iob/Simula.cs +++ b/IOB-WIN-FORM/Iob/Simula.cs @@ -737,10 +737,6 @@ namespace IOB_WIN_FORM.Iob { case urlType.ULog: string[] elencoMulti = null; -#if false - // devo chiamare cambio ODL x OGNI tavola: mi servono i parametri opzionali... - elencoMulti = IOBConfFull.Device.MultiIobListRaw.Split(','); -#endif elencoMulti = IOBConfFull.Device.MultiIobList.ToArray(); // aggiungo tav 1 / 2 a caso secondo secondi attuali, se pari/dispari int idxTav = DateTime.Now.Second % 2; diff --git a/IOB-WIN-FORM/MainForm.Designer.cs b/IOB-WIN-FORM/MainForm.Designer.cs index 089952b1..2e46304c 100644 --- a/IOB-WIN-FORM/MainForm.Designer.cs +++ b/IOB-WIN-FORM/MainForm.Designer.cs @@ -45,7 +45,6 @@ this.closeChildToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.closeALLAdaptersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.restartALLAdaptersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.uploadIOBConfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.downloadIOBConfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sendIOBAssignmentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.getIOBAssignmentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -162,7 +161,6 @@ this.closeChildToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.closeALLAdaptersToolStripMenuItem, this.restartALLAdaptersToolStripMenuItem, - this.uploadIOBConfToolStripMenuItem, this.downloadIOBConfToolStripMenuItem, this.sendIOBAssignmentsToolStripMenuItem, this.getIOBAssignmentsToolStripMenuItem}); @@ -186,13 +184,6 @@ this.restartALLAdaptersToolStripMenuItem.Text = "&Restart ALL Adapters"; this.restartALLAdaptersToolStripMenuItem.Click += new System.EventHandler(this.restartALLAdaptersToolStripMenuItem_Click); // - // uploadIOBConfToolStripMenuItem - // - this.uploadIOBConfToolStripMenuItem.Name = "uploadIOBConfToolStripMenuItem"; - this.uploadIOBConfToolStripMenuItem.Size = new System.Drawing.Size(203, 22); - this.uploadIOBConfToolStripMenuItem.Text = "Upload IOB Conf files"; - this.uploadIOBConfToolStripMenuItem.Click += new System.EventHandler(this.uploadIOBConfToolStripMenuItem_Click); - // // downloadIOBConfToolStripMenuItem // this.downloadIOBConfToolStripMenuItem.Name = "downloadIOBConfToolStripMenuItem"; @@ -302,7 +293,6 @@ private System.Windows.Forms.ToolStripStatusLabel tslRunTime; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3; private System.Windows.Forms.ToolStripMenuItem closeChildToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem uploadIOBConfToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem downloadIOBConfToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sendIOBAssignmentsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem getIOBAssignmentsToolStripMenuItem; diff --git a/IOB-WIN-FORM/MainForm.cs b/IOB-WIN-FORM/MainForm.cs index 9a23c6d0..f7729be3 100644 --- a/IOB-WIN-FORM/MainForm.cs +++ b/IOB-WIN-FORM/MainForm.cs @@ -1183,10 +1183,6 @@ namespace IOB_WIN_FORM { openChild(item); } -#if false - // effettuo upload dei file di configurazione... - uploadIobConfFile(); -#endif } /// @@ -1214,13 +1210,6 @@ namespace IOB_WIN_FORM } } - private void uploadIOBConfToolStripMenuItem_Click(object sender, EventArgs e) - { -#if false - uploadIobConfFile(); -#endif - } - #endregion Private Methods } } \ No newline at end of file diff --git a/refactoring_wip.md b/refactoring_wip.md index 2e843efb..d12226cc 100644 --- a/refactoring_wip.md +++ b/refactoring_wip.md @@ -1,6 +1,6 @@ # WIP: Refactoring Phase 1 - Infrastructure Extraction -## Status: COMPLETED +## Status: IN_PROGRESS ## Objective Extract infrastructure and helper components from `Generic.cs` to improve modularity and reduce the monolithic footprint. @@ -10,7 +10,7 @@ Extract infrastructure and helper components from `Generic.cs` to improve modula ### 1. Communication Service Extraction (COMPLETED/REFACTORED) - [x] Identify redundant `callUrl` and `callUrlWithPayloadAsync` wrappers in `BaseObj.cs`. - [x] Instead of creating a new service, cleaned up `BaseObj.cs` by removing pass-through methods that merely delegated to `utils`. -- [x] Updated `Generic.cs` to call `utils.callUrl` directly, removing the unnecessary indirection layer. +- [x] Updated `Generic.cs` to call `utils.callUrl` directly, eliminating the unnecessary indirection layer. ### 2. Redis Service Extraction (COMPLETED) - [x] Encapsulate all `redisMan` calls into a `RedisService`. @@ -18,9 +18,13 @@ Extract infrastructure and helper components from `Generic.cs` to improve modula - [x] **Refactored**: Moved semantic key construction from `RedisService` to `BaseObj` to eliminate redundant service layer. - [x] Eliminated `RedisService.cs` as it was absorbed by the `BaseObj` identity-aware implementation. -### 3. Data Serializer Extraction -- [ ] Move all `JsonConvert` and custom string formatting (e.g., `qEncodeFLog`, `qEncodeIN`) to a `DataSerializer` service. -- [ ] Centralize `CultureInfo.InvariantCulture` usage. +### 3. Data Serializer Extraction (IN_PROGRESS) +- [x] Analyzed current `DataSerializer.cs` (JSON) and `XmlDataSerializer.cs` (XML) in `IOB-WIN-FORM`. +- [x] Decided to move these to `IOB_UT_NEXT` to make them available to the entire IOB hierarchy. +- [ ] Move files to `IOB_UT_NEXT\Iob\Services\`. +- [ ] Update namespaces and references. +- [ ] Integrate into `BaseObj.cs` via `protected` helper methods (e.g., `JsonSerialize`, `XmlSerialize`). +- [ ] Update `Generic.cs` to use the new `BaseObj` helpers. ### 4. BaseObj Simplification (COMPLETED) - [x] Analyze `BaseObj` responsibilities (State, Config, Messaging, Diagnostics). @@ -29,8 +33,7 @@ Extract infrastructure and helper components from `Generic.cs` to improve modula ## Progress Log - [x] Created WIP document. -- [x] Analyzed `Generic.cs` for Phase 1 candidates. - [x] Completed Redis Semantic Refactoring. -- [x] Completed BaseObj Cleanup (Removal of redundant wrappers and commented code). -- [x] Verified compilation stability after removing `BaseObj` wrappers. -- [ ] **Next Task**: Data Serializer Extraction. +- [x] Completed BaseObj Cleanup. +- [x] Identified Data Serializer components for extraction. +- [ ] Started migration of Serializers to `IOB_UT_NEXT`. From 64f017c5304baf60eb63eb79b5abcce21e24d74c Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 21 May 2026 16:49:45 +0200 Subject: [PATCH 2/7] TYpo cleanup --- IOB-UT-NEXT/CallMetricsCollector.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/IOB-UT-NEXT/CallMetricsCollector.cs b/IOB-UT-NEXT/CallMetricsCollector.cs index 4ed4fc3b..6b5891e1 100644 --- a/IOB-UT-NEXT/CallMetricsCollector.cs +++ b/IOB-UT-NEXT/CallMetricsCollector.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text.Json; using System.Threading.Tasks; namespace IOB_UT_NEXT @@ -39,7 +38,7 @@ namespace IOB_UT_NEXT { parsed = JsonConvert.DeserializeObject>(json.ToString()); } - catch (Exception ex) + catch //(Exception ex) { // Log: dati Redis corrotti o schema incompatibile. Si ignora per sicurezza. return; From 9d1b39be71f5f81d3d6b70fd5dced1e12419cbbf Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Thu, 21 May 2026 17:11:14 +0200 Subject: [PATCH 3/7] Modifiche da pi.dev x metodi http call --- IOB-UT-NEXT/Iob/Services/HttpService.cs | 308 ++++++++++++++++++++++++ 1 file changed, 308 insertions(+) create mode 100644 IOB-UT-NEXT/Iob/Services/HttpService.cs diff --git a/IOB-UT-NEXT/Iob/Services/HttpService.cs b/IOB-UT-NEXT/Iob/Services/HttpService.cs new file mode 100644 index 00000000..0a63f768 --- /dev/null +++ b/IOB-UT-NEXT/Iob/Services/HttpService.cs @@ -0,0 +1,308 @@ +using NLog; +using RestSharp; +using System; +using System.Diagnostics; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace IOB_UT_NEXT.Iob.Services +{ + /// + /// Servizio dedicato alla gestione delle chiamate HTTP. + /// + public class HttpService + { + /// + /// Effettua chiamata URL e restituisce risultato, SE NON E' in veto send. + /// + public static string CallUrl(string url) + { + if (baseUtils.dtVetoSend < DateTime.Now) + { + return CallUrlGet(url); + } + return string.Empty; + } + + /// + /// Effettua chiamata URL e restituisce risultato con payload. + /// + public static string CallUrl(string url, string payload) + { + if (baseUtils.dtVetoSend < DateTime.Now) + { + return CallUrlPost(url, payload); + } + return string.Empty; + } + + /// + /// Metodo chiamata URL con POST async. + /// + public static async Task CallUrlAsync(string url, string payload, CancellationToken ct = default) + { + try + { + Stopwatch sw = Stopwatch.StartNew(); + var content = new StringContent(payload, Encoding.UTF8, "application/json"); + + using (var client = new HttpClient()) // Note: In a real app, use IHttpClientFactory + { + HttpResponseMessage response = await client.PostAsync(url, content, ct); + response.EnsureSuccessStatusCode(); + + sw.Stop(); + baseUtils.TrackUrlCall(url, sw.Elapsed); + + return await response.Content.ReadAsStringAsync(); + } + } + catch (OperationCanceledException) + { + return "Canceled"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + /// + /// Metodo chiamata URL con GET async. + /// + public static async Task CallUrlAsync(string url, CancellationToken ct = default) + { + try + { + Stopwatch sw = Stopwatch.StartNew(); + using (var client = new HttpClient()) + { + HttpResponseMessage response = await client.GetAsync(url, ct); + response.EnsureSuccessStatusCode(); + + sw.Stop(); + baseUtils.TrackUrlCall(url, sw.Elapsed); + return await response.Content.ReadAsStringAsync(); + } + } + catch (OperationCanceledException) + { + return "Canceled"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + /// + /// Effettua chiamata URL IMMEDIATAMENTE (GET) e restituisce risultato. + /// + public static string CallUrlGet(string url) + { + try + { + HttpClientHandler handler = new HttpClientHandler(); + if (url.Contains("10.74.82.")) + { + handler.ServerCertificateCustomValidationCallback = + HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; + } + + using (var client = new HttpClient(handler)) + { + Stopwatch sw = Stopwatch.StartNew(); + client.Timeout = TimeSpan.FromMilliseconds(5000); + client.DefaultRequestHeaders.UserAgent.ParseAdd(baseUtils.CRS("appName")); + + var response = client.GetAsync(url).Result; + string answ = response.Content.ReadAsStringAsync().Result; + + sw.Stop(); + baseUtils.TrackUrlCall(url, sw.Elapsed); + + return answ; + } + } + catch (Exception exc) + { + int pauseSendMSec = baseUtils.nextPauseSendMSec; + baseUtils.dtVetoSend = DateTime.Now.AddMilliseconds(pauseSendMSec); + + if (baseUtils.logValuePermit(url)) + { + baseUtils.lg.Error($"CallUrlGet | Errore chiamando {url} | wait {pauseSendMSec} ms{Environment.NewLine}Eccezione:{Environment.NewLine}{exc}"); + } + + return ""; + } + } + + /// + /// Effettua chiamata IMMEDIATAMENTE URL (POST) e restituisce risultato. + /// + public static string CallUrlPost(string url, string payload) + { + string answ = ""; + Stopwatch sw = Stopwatch.StartNew(); + + try + { + HttpClientHandler handler = new HttpClientHandler(); + if (url.Contains("10.74.")) + { + handler.ServerCertificateCustomValidationCallback = + HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; + } + + using (var client = new HttpClient(handler)) + { + client.Timeout = TimeSpan.FromMilliseconds(5000); + client.DefaultRequestHeaders.UserAgent.ParseAdd($"{baseUtils.CRS("appName")}-PAYLOAD"); + + var content = new StringContent(payload, Encoding.UTF8, "application/json"); + var response = client.PostAsync(url, content).Result; + + answ = response.Content.ReadAsStringAsync().Result; + + if (answ != "OK") + { + if (baseUtils.logValuePermit($"{url}|[{answ}]")) + { + baseUtils.lg.Error($"CallUrlPost | POST fallito | ans: [{answ}]:{Environment.NewLine}- URL{Environment.NewLine}{url}{Environment.NewLine}- payload{Environment.NewLine}{payload}"); + } + } + } + } + catch (Exception exc) + { + int pauseSendMSec = baseUtils.nextPauseSendMSec; + baseUtils.dtVetoSend = DateTime.Now.AddMilliseconds(pauseSendMSec); + + if (baseUtils.logValuePermit(url)) + { + baseUtils.lg.Error($"CallUrlPost | Errore chiamando {url} | wait {pauseSendMSec} ms | Dump Payload:{Environment.NewLine}{payload}{Environment.NewLine}Eccezione:{Environment.NewLine}{exc}"); + } + } + + sw.Stop(); + baseUtils.TrackUrlCall(url, sw.Elapsed); + return answ; + } + + /// + /// Effettua chiamata URL tramite RestSharp (GET) + /// + public static string ExecCallGet(string url, bool fastCall = false) + { + string answ = ""; + Uri uri = new Uri(url); + string baseUrl = $"{uri.Scheme}://{uri.Host}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}"; + string resource = uri.AbsolutePath; + RestClientOptions restOptStd = new RestClientOptions + { + BaseUrl = new Uri(baseUrl), + Timeout = TimeSpan.FromSeconds(60) + }; + if (fastCall) restOptStd.Timeout = TimeSpan.FromSeconds(5); + + try + { + using (var client = new RestClient(restOptStd)) + { + var actReq = new RestRequest(resource, Method.Get); + var currResp = client.Get(actReq); + if (currResp.StatusCode == System.Net.HttpStatusCode.OK && currResp.Content != null) + { + answ = currResp.Content; + } + } + } + catch (Exception exc) + { + baseUtils.lg.Error($"Eccezione in ExecCallGet{Environment.NewLine}{exc}"); + } + return answ; + } + + /// + /// Effettua chiamata URL tramite RestSharp (POST JSON) + /// + public static string ExecCallPostJson(string url, string payload, bool fastCall = false) + { + string answ = ""; + Uri uri = new Uri(url); + string baseUrl = $"{uri.Scheme}://{uri.Host}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}"; + string resource = uri.AbsolutePath; + RestClientOptions restOptStd = new RestClientOptions + { + BaseUrl = new Uri(baseUrl), + Timeout = TimeSpan.FromSeconds(60) + }; + if (fastCall) restOptStd.Timeout = TimeSpan.FromSeconds(5); + + Stopwatch sw = Stopwatch.StartNew(); + try + { + using (var client = new RestClient(restOptStd)) + { + var actReq = new RestRequest(resource, Method.Post); + actReq.AddJsonBody(payload); + var currResp = client.Post(actReq); + if (currResp.StatusCode == System.Net.HttpStatusCode.OK && currResp.Content != null) + { + answ = currResp.Content; + } + } + } + catch (Exception exc) + { + baseUtils.lg.Error($"Eccezione in ExecCallPostJson{Environment.NewLine}{exc}"); + } + sw.Stop(); + baseUtils.TrackUrlCall(url, sw.Elapsed); + return answ; + } + + /// + /// Effettua chiamata URL tramite RestSharp (POST Plain) + /// + public static string ExecCallPostPlain(string url, string payload, bool fastCall = false) + { + string answ = ""; + Uri uri = new Uri(url); + string baseUrl = $"{uri.Scheme}://{uri.Host}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}"; + string resource = uri.AbsolutePath; + RestClientOptions restOptStd = new RestClientOptions + { + BaseUrl = new Uri(baseUrl), + Timeout = TimeSpan.FromSeconds(60) + }; + if (fastCall) restOptStd.Timeout = TimeSpan.FromSeconds(5); + + Stopwatch sw = Stopwatch.StartNew(); + try + { + using (var client = new RestClient(restOptStd)) + { + var actReq = new RestRequest(resource, Method.Post); + actReq.AddStringBody(payload, ContentType.Plain); + var currResp = client.Post(actReq); + if (currResp.StatusCode == System.Net.HttpStatusCode.OK && currResp.Content != null) + { + answ = currResp.Content; + } + } + } + catch (Exception exc) + { + baseUtils.lg.Error($"Eccezione in ExecCallPostPlain | rawUrl: {url} {Environment.NewLine}{exc}"); + } + sw.Stop(); + baseUtils.TrackUrlCall(url, sw.Elapsed); + return answ; + } + } +} From fba55e0d7c440b2482d188cf9a2622d6a03b89b1 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 21 May 2026 17:14:32 +0200 Subject: [PATCH 4/7] Fix metodi internal --- IOB-UT-NEXT/IOB-UT-NEXT.csproj | 1 + IOB-UT-NEXT/Iob/Services/HttpService.cs | 6 ++- IOB-UT-NEXT/baseUtils.cs | 63 ++++++++++++------------- 3 files changed, 37 insertions(+), 33 deletions(-) diff --git a/IOB-UT-NEXT/IOB-UT-NEXT.csproj b/IOB-UT-NEXT/IOB-UT-NEXT.csproj index 8d65d909..3d146a76 100644 --- a/IOB-UT-NEXT/IOB-UT-NEXT.csproj +++ b/IOB-UT-NEXT/IOB-UT-NEXT.csproj @@ -203,6 +203,7 @@ + diff --git a/IOB-UT-NEXT/Iob/Services/HttpService.cs b/IOB-UT-NEXT/Iob/Services/HttpService.cs index 0a63f768..9a2e5ab0 100644 --- a/IOB-UT-NEXT/Iob/Services/HttpService.cs +++ b/IOB-UT-NEXT/Iob/Services/HttpService.cs @@ -14,6 +14,8 @@ namespace IOB_UT_NEXT.Iob.Services /// public class HttpService { + #region Public Methods + /// /// Effettua chiamata URL e restituisce risultato, SE NON E' in veto send. /// @@ -304,5 +306,7 @@ namespace IOB_UT_NEXT.Iob.Services baseUtils.TrackUrlCall(url, sw.Elapsed); return answ; } + + #endregion Public Methods } -} +} \ No newline at end of file diff --git a/IOB-UT-NEXT/baseUtils.cs b/IOB-UT-NEXT/baseUtils.cs index ead71e34..8ba6c442 100644 --- a/IOB-UT-NEXT/baseUtils.cs +++ b/IOB-UT-NEXT/baseUtils.cs @@ -1022,47 +1022,23 @@ namespace IOB_UT_NEXT #endregion Public Methods - #region Protected Fields + #region Internal Fields /// /// Classe logger /// - protected static Logger lg = LogManager.GetCurrentClassLogger(); + internal static Logger lg = LogManager.GetCurrentClassLogger(); - #endregion Protected Fields + #endregion Internal Fields - #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 - /// - private static string LastHourCurr = ""; - - /// - /// Dizionario dei valori bloccati x evitare log eccessivo - /// - private static Dictionary vetoLogError = new Dictionary(); - - /// - /// Periodo di veto log in minuti - /// - private static int vetoPeriodMin = 30; - - #endregion Private Fields - - #region Private Methods + #region Internal Methods /// /// Verifica se il log di un dato errore sia permesso /// /// ID del valore log da loggare/verificare /// - private static bool logValuePermit(string logKey) + internal static bool logValuePermit(string logKey) { bool doLog = false; if (vetoLogError.ContainsKey(logKey)) @@ -1088,7 +1064,7 @@ namespace IOB_UT_NEXT /// /// URL chiamato /// durata chiamata - private static void TrackUrlCall(string rawUrl, TimeSpan elapsed) + internal static void TrackUrlCall(string rawUrl, TimeSpan elapsed) { // per l'URL tengo solo fino a prima dei parametri (prima di ?) string url = StripQueryAndFragment(rawUrl); @@ -1118,7 +1094,30 @@ namespace IOB_UT_NEXT CallMetricsCollector.AddCall(url, elapsed); } - #endregion Private Methods - } + #endregion Internal Methods + #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 + /// + private static string LastHourCurr = ""; + + /// + /// Dizionario dei valori bloccati x evitare log eccessivo + /// + private static Dictionary vetoLogError = new Dictionary(); + + /// + /// Periodo di veto log in minuti + /// + private static int vetoPeriodMin = 30; + + #endregion Private Fields + } } \ No newline at end of file From 6dcf2b103a99a4590eb5ad2b380bc7652c1576c0 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 21 May 2026 17:59:51 +0200 Subject: [PATCH 5/7] Spostamento metodi x dominio da baseUtils --- IOB-UT-NEXT/Config/IobConfTree.cs | 3 +- IOB-UT-NEXT/IOB-UT-NEXT.csproj | 1 + IOB-UT-NEXT/Iob/Services/NetService.cs | 78 +++++ IOB-UT-NEXT/baseUtils.cs | 380 +------------------------ IOB-UT-NEXT/utils.cs | 3 +- IOB-WIN-FORM/AdapterForm.cs | 9 +- IOB-WIN-FORM/Iob/Generic.cs | 118 ++++---- IOB-WIN-FORM/Iob/Simula.cs | 27 +- IOB-WIN-FORM/MainForm.cs | 178 +++++------- 9 files changed, 239 insertions(+), 558 deletions(-) create mode 100644 IOB-UT-NEXT/Iob/Services/NetService.cs diff --git a/IOB-UT-NEXT/Config/IobConfTree.cs b/IOB-UT-NEXT/Config/IobConfTree.cs index c6c84b86..ee6d6996 100644 --- a/IOB-UT-NEXT/Config/IobConfTree.cs +++ b/IOB-UT-NEXT/Config/IobConfTree.cs @@ -1,6 +1,7 @@ using IOB_UT_NEXT.Config; using IOB_UT_NEXT.Config.Base; using IOB_UT_NEXT.Config.Special; +using IOB_UT_NEXT.Iob.Services; using MapoSDK; using Newtonsoft.Json; using NLog; @@ -1067,7 +1068,7 @@ namespace IOB_UT_NEXT.Config { string rawData = GetYaml(); // prova anche ad inviare il contenuto al server IO... - string resp = utils.ExecCallPostPlain($"{urlSaveYaml}", rawData); + string resp = HttpService.ExecCallPostPlain($"{urlSaveYaml}", rawData); answ = resp == "OK"; } catch diff --git a/IOB-UT-NEXT/IOB-UT-NEXT.csproj b/IOB-UT-NEXT/IOB-UT-NEXT.csproj index 3d146a76..2ee59c5c 100644 --- a/IOB-UT-NEXT/IOB-UT-NEXT.csproj +++ b/IOB-UT-NEXT/IOB-UT-NEXT.csproj @@ -204,6 +204,7 @@ + diff --git a/IOB-UT-NEXT/Iob/Services/NetService.cs b/IOB-UT-NEXT/Iob/Services/NetService.cs new file mode 100644 index 00000000..3ef5415c --- /dev/null +++ b/IOB-UT-NEXT/Iob/Services/NetService.cs @@ -0,0 +1,78 @@ +using NLog; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.NetworkInformation; +using System.Text; +using System.Threading.Tasks; + +namespace IOB_UT_NEXT.Iob.Services +{ + public class NetService + { + #region Public Methods + + /// + /// 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) + { + 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; + } + + #endregion Public Methods + + #region Internal Fields + + /// + /// Classe logger + /// + internal static Logger lg = LogManager.GetCurrentClassLogger(); + + #endregion Internal Fields + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/baseUtils.cs b/IOB-UT-NEXT/baseUtils.cs index 8ba6c442..4d9d95d0 100644 --- a/IOB-UT-NEXT/baseUtils.cs +++ b/IOB-UT-NEXT/baseUtils.cs @@ -108,231 +108,6 @@ namespace IOB_UT_NEXT return answ; } - /// - /// Effettua chiamata URL e restituisce risultato, SE NON E' in veto send (x mitigare chiamate...) - /// - /// - /// - public static string callUrl(string URL) - { - string answ = ""; - // controllo se ho un VETO all'invio... - if (dtVetoSend < DateTime.Now) - { - answ = CallUrlGet(URL); - } - return answ; - } - - /// - /// Effettua chiamata URL e restituisce risultato - /// - /// - /// - /// - public static string callUrl(string URL, string payload) - { - string answ = ""; - // controllo se ho un VETO all'invio... - if (dtVetoSend < DateTime.Now) - { - answ = CallUrlPost(URL, payload); - } - // restituisco valore! - return answ; - } - - /// - /// Metodo chiamata URL con POST async - /// - /// - /// - /// - /// - public static async Task callUrlAsync(string URL, string payload, CancellationToken ct = default) - { - try - { - Stopwatch sw = new Stopwatch(); - sw.Start(); - - // Se hai un payload, probabilmente è una POST - var content = new StringContent(payload, Encoding.UTF8, "application/json"); - - // Qui il thread viene RILASCIATO. La CPU dell'istanza va a 0% - // mentre aspetta la risposta dal server. - HttpResponseMessage response = await _httpClient.PostAsync(URL, content, ct); - - response.EnsureSuccessStatusCode(); - - sw.Stop(); - TrackUrlCall(URL, sw.Elapsed); - - return await response.Content.ReadAsStringAsync(); - } - catch (OperationCanceledException) - { - // Gestisci la cancellazione (quando chiudi l'app o scade il timeout) - return "Canceled"; - } - catch (Exception ex) - { - // Gestisci errori di rete - return $"Error: {ex.Message}"; - } - } - - /// - /// Metodo chiamata URL con GET async - /// - /// - /// - /// - public static async Task callUrlAsync(string URL, CancellationToken ct = default) - { - try - { - Stopwatch sw = new Stopwatch(); - sw.Start(); - - // Qui il thread viene RILASCIATO. La CPU dell'istanza va a 0% - // mentre aspetta la risposta dal server. - HttpResponseMessage response = await _httpClient.GetAsync(URL, ct); - - response.EnsureSuccessStatusCode(); - - sw.Stop(); - TrackUrlCall(URL, sw.Elapsed); - return await response.Content.ReadAsStringAsync(); - } - catch (OperationCanceledException) - { - // Gestisci la cancellazione (quando chiudi l'app o scade il timeout) - return "Canceled"; - } - catch (Exception ex) - { - // Gestisci errori di rete - return $"Error: {ex.Message}"; - } - } - - /// - /// Effettua chiamata URL IMMEDIATAMENTE e restituisce risultato - /// - /// - /// - public static string CallUrlGet(string URL) - { - try - { - // Gestione certificati self-signed - HttpClientHandler handler = new HttpClientHandler(); - if (URL.Contains("10.74.82.")) - { - handler.ServerCertificateCustomValidationCallback = - HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; - } - - using (var client = new HttpClient(handler)) - { - Stopwatch sw = new Stopwatch(); - sw.Start(); - // Timeout personalizzabile - client.Timeout = TimeSpan.FromMilliseconds(5000); - - // Header custom - client.DefaultRequestHeaders.UserAgent.ParseAdd(CRS("appName")); - - // GET sincrona - var response = client.GetAsync(URL).Result; - - string answ = response.Content.ReadAsStringAsync().Result; - - sw.Stop(); - TrackUrlCall(URL, sw.Elapsed); - - return answ; - } - } - catch (Exception exc) - { - int pauseSendMSec = nextPauseSendMSec; - dtVetoSend = DateTime.Now.AddMilliseconds(pauseSendMSec); - - if (logValuePermit(URL)) - { - lg.Error($"CallUrlGet | Errore chiamando {URL} | wait {pauseSendMSec} ms{Environment.NewLine}Eccezione:{Environment.NewLine}{exc}"); - } - - return ""; - } - } - - /// - /// Effettua chiamata IMMEDIATAMENTE URL e restituisce risultato - /// - /// - /// - /// - public static string CallUrlPost(string URL, string payload) - { - string answ = ""; - Stopwatch sw = new Stopwatch(); - sw.Start(); - - try - { - // Gestione certificati self-signed - HttpClientHandler handler = new HttpClientHandler(); - if (URL.Contains("10.74.")) - { - handler.ServerCertificateCustomValidationCallback = - HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; - } - - using (var client = new HttpClient(handler)) - { - // Timeout personalizzabile - client.Timeout = TimeSpan.FromMilliseconds(5000); - - // Header custom - client.DefaultRequestHeaders.UserAgent.ParseAdd($"{CRS("appName")}-PAYLOAD"); - - // Corpo JSON - var content = new StringContent(payload, Encoding.UTF8, "application/json"); - - // POST sincrono - var response = client.PostAsync(URL, content).Result; - - answ = response.Content.ReadAsStringAsync().Result; - - // Log identico al tuo - if (answ != "OK") - { - if (logValuePermit($"{URL}|[{answ}]")) - { - lg.Error($"CallUrlPost | POST fallito | ans: [{answ}]:{Environment.NewLine}- URL{Environment.NewLine}{URL}{Environment.NewLine}- payload{Environment.NewLine}{payload}"); - } - } - } - } - catch (Exception exc) - { - int pauseSendMSec = nextPauseSendMSec; - dtVetoSend = DateTime.Now.AddMilliseconds(pauseSendMSec); - - if (logValuePermit(URL)) - { - lg.Error($"CallUrlPost | Errore chiamando {URL} | wait {pauseSendMSec} ms | Dump Payload:{Environment.NewLine}{payload}{Environment.NewLine}Eccezione:{Environment.NewLine}{exc}"); - } - } - - sw.Stop(); - TrackUrlCall(URL, sw.Elapsed); - return answ; - } - /// /// Test esistenza/creazione directory /// @@ -418,157 +193,6 @@ namespace IOB_UT_NEXT return ConfigurationManager.AppSettings[key] ?? string.Empty; } - /// - /// Effettua chiamata URL tramite RestSharp e restituisce risultato, SE NON E' in veto send (x mitigare chiamate...) - /// - /// URI da chiamare - /// Chiamata rapida (timeout rapido = 5sec) - /// - public static string ExecCallGet(string url, bool fastCall = false) - { - string answ = ""; - // divido key tra base e opzionale... - Uri uri = new Uri(url); - string baseUrl = $"{uri.Scheme}://{uri.Host}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}"; - string resource = uri.AbsolutePath; - RestClientOptions restOptStd = new RestClientOptions - { - BaseUrl = new Uri(baseUrl), - Timeout = TimeSpan.FromSeconds(60) - }; - if (!string.IsNullOrEmpty(url)) - { - if (fastCall) - { - restOptStd.Timeout = TimeSpan.FromSeconds(5); - } - try - { - // client chiamate rest - using (var client = new RestClient(restOptStd)) - { - var actReq = new RestRequest(resource, Method.Get); - // effettuo vera chiamata - var currResp = client.Get(actReq); - if (currResp.StatusCode == System.Net.HttpStatusCode.OK && currResp.Content != null) - { - answ = currResp.Content ?? ""; - } - } - } - catch (Exception exc) - { - lg.Error($"Eccezione in callRestUrl{Environment.NewLine}{exc}"); - } - } - return answ; - } - - /// - /// Effettua chiamata URL tramite RestSharp e restituisce risultato, SE NON E' in veto send (x mitigare chiamate...) - /// - /// URI da chiamare - /// Payload da allegare (già serializzato) - /// Chiamata rapida (timeout rapido = 5sec) - /// - public static string ExecCallPostJson(string url, string payload, bool fastCall = false) - { - string answ = ""; - - // divido key tra base e opzionale... - Uri uri = new Uri(url); - string baseUrl = $"{uri.Scheme}://{uri.Host}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}"; - string resource = uri.AbsolutePath; - RestClientOptions restOptStd = new RestClientOptions - { - BaseUrl = new Uri(baseUrl), - Timeout = TimeSpan.FromSeconds(60) - }; - Stopwatch sw = new Stopwatch(); - sw.Start(); - - if (!string.IsNullOrEmpty(url)) - { - if (fastCall) - { - restOptStd.Timeout = TimeSpan.FromSeconds(5); - } - try - { - // client chiamate rest - using (var client = new RestClient(restOptStd)) - { - var actReq = new RestRequest(resource, Method.Post); - actReq.AddJsonBody(payload); - // effettuo vera chiamata - var currResp = client.Post(actReq); - if (currResp.StatusCode == System.Net.HttpStatusCode.OK && currResp.Content != null) - { - answ = currResp.Content ?? ""; - } - } - } - catch (Exception exc) - { - lg.Error($"Eccezione in callRestUrlJson{Environment.NewLine}{exc}"); - } - } - return answ; - } - - /// - /// Effettua chiamata URL tramite RestSharp e restituisce risultato, SE NON E' in veto send (x mitigare chiamate...) - /// - /// URI da chiamare - /// Payload da allegare (già serializzato) - /// Chiamata rapida (timeout rapido = 5sec) - /// - public static string ExecCallPostPlain(string url, string payload, bool fastCall = false) - { - string answ = ""; - // divido key tra base e opzionale... - Uri uri = new Uri(url); - string baseUrl = $"{uri.Scheme}://{uri.Host}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}"; - string resource = uri.AbsolutePath; - RestClientOptions restOptStd = new RestClientOptions - { - BaseUrl = new Uri(baseUrl), - Timeout = TimeSpan.FromSeconds(60) - }; - Stopwatch sw = new Stopwatch(); - sw.Start(); - - if (!string.IsNullOrEmpty(url)) - { - if (fastCall) - { - restOptStd.Timeout = TimeSpan.FromSeconds(5); - } - try - { - // client chiamate rest - using (var client = new RestClient(restOptStd)) - { - var actReq = new RestRequest(resource, Method.Post); - actReq.AddStringBody(payload, ContentType.Plain); - // effettuo vera chiamata - var currResp = client.Post(actReq); - if (currResp.StatusCode == System.Net.HttpStatusCode.OK && currResp.Content != null) - { - answ = currResp.Content ?? ""; - } - } - } - catch (Exception exc) - { - lg.Error($"Eccezione in callRestUrlJson | rawUrl: {url} {Environment.NewLine}{exc}"); - } - } - sw.Stop(); - TrackUrlCall(url, sw.Elapsed); - return answ; - } - /// /// Calcolo MD5 del fine indicato /// @@ -603,6 +227,7 @@ namespace IOB_UT_NEXT return num; } +#if false /// /// IP della macchina /// @@ -657,7 +282,8 @@ namespace IOB_UT_NEXT } } return sMacAddress; - } + } +#endif /// /// Restituisce una stringa di soli caratteri numerici (stripe caratteri alfabetici) diff --git a/IOB-UT-NEXT/utils.cs b/IOB-UT-NEXT/utils.cs index 8c46fff2..cc7bd526 100644 --- a/IOB-UT-NEXT/utils.cs +++ b/IOB-UT-NEXT/utils.cs @@ -1,4 +1,5 @@ -using System; +using IOB_UT_NEXT.Iob.Services; +using System; using System.IO; using System.Linq; diff --git a/IOB-WIN-FORM/AdapterForm.cs b/IOB-WIN-FORM/AdapterForm.cs index 03a838c5..613b9706 100644 --- a/IOB-WIN-FORM/AdapterForm.cs +++ b/IOB-WIN-FORM/AdapterForm.cs @@ -1,6 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; using IOB_UT_NEXT.Config.Base; +using IOB_UT_NEXT.Iob.Services; using MapoSDK; using Newtonsoft.Json; using NLog; @@ -1461,7 +1462,7 @@ namespace IOB_WIN_FORM // salvo nuovo valore invio iobObj.LastSendSet(sendKey, DateTime.Now); // segnalo reboot (programma - url file)... - await utils.callUrlAsync(iobObj.urlReboot); + await HttpService.CallUrlAsync(iobObj.urlReboot); } } else @@ -2271,16 +2272,16 @@ namespace IOB_WIN_FORM if (utils.CRB("ConfToCloud")) { // invio su cloud... - answ = await utils.callUrlAsync($"{urlUploadFileCloud}{CurrIOB}", rawData); + answ = await HttpService.CallUrlAsync($"{urlUploadFileCloud}{CurrIOB}", rawData); } else { // provo invio locale - answ = utils.callUrl($"{urlUploadFile}{CurrIOB}", rawData); + answ = HttpService.CallUrl($"{urlUploadFile}{CurrIOB}", rawData); // se va male invio cloud... if (answ.ToUpper() != "OK") { - answ = await utils.callUrlAsync($"{urlUploadFileCloud}{CurrIOB}", rawData); + answ = await HttpService.CallUrlAsync($"{urlUploadFileCloud}{CurrIOB}", rawData); } } } diff --git a/IOB-WIN-FORM/Iob/Generic.cs b/IOB-WIN-FORM/Iob/Generic.cs index ab7cb93c..da8cc0ef 100644 --- a/IOB-WIN-FORM/Iob/Generic.cs +++ b/IOB-WIN-FORM/Iob/Generic.cs @@ -1426,7 +1426,7 @@ namespace IOB_WIN_FORM.Iob if (!isMulti) { // invio chiamata URL x reset ODL su macchina - rawSplit = await utils.callUrlAsync(urlForceSplit); + rawSplit = await HttpService.CallUrlAsync(urlForceSplit); fatto = (rawSplit != "KO") ? true : false; } // se multi gestisco il bit delle tavole... @@ -1437,7 +1437,7 @@ namespace IOB_WIN_FORM.Iob // invio chiamata URL x reset ODL su macchina, ATTENZIONE scriviamo // | al posto di "#" che in URL sarebbe filtrato... fullUrl = $"{urlForceSplit}&multi={item}"; - rawSplit = await utils.callUrlAsync(fullUrl); + rawSplit = await HttpService.CallUrlAsync(fullUrl); lgDebug($"Esecuzione forceSplit | URL: {fullUrl} | esito: {rawSplit}"); } fatto = (rawSplit == "OK") ? true : false; @@ -2063,7 +2063,7 @@ namespace IOB_WIN_FORM.Iob lgTrace("AutoSnapshotDossier abilitato"); // chiamo stored x creare Snapshot Dossier giornalieri fino alla data... - callResp = utils.callUrl(urlFixDailyDossier); + callResp = HttpService.CallUrl(urlFixDailyDossier); fatto = callResp == "OK"; lgDebug($"Esecuzione ProcessAutoDossier completata --> esito: {callResp}"); } @@ -2143,7 +2143,7 @@ namespace IOB_WIN_FORM.Iob if (dtStart.Date < adesso.Date) { // chiamo stored x creare ODL giornalieri alla data... - string autoOdlRes = utils.callUrl(urlFixDailyOdl); + string autoOdlRes = HttpService.CallUrl(urlFixDailyOdl); fatto = autoOdlRes == "OK"; // imposto x prox controllo veto a 10 min VetoProcessAutoOdl = adesso.AddMinutes(10); @@ -2165,7 +2165,7 @@ namespace IOB_WIN_FORM.Iob if (!isMulti) { // chiamo stored x creare ODL giornalieri alla data + conferma pezzi... - autoOdlRes = utils.callUrl(urlFixDailyOdlConfPzCount); + autoOdlRes = HttpService.CallUrl(urlFixDailyOdlConfPzCount); } else { @@ -2173,7 +2173,7 @@ namespace IOB_WIN_FORM.Iob foreach (var item in IOBConfFull.Device.MultiIobList) { fullUrl = $@"{urlCommand("fixDailyOdlConfPzCount")}{item}"; - autoOdlRes = await utils.callUrlAsync(fullUrl); + autoOdlRes = await HttpService.CallUrlAsync(fullUrl); } } fatto = autoOdlRes == "OK"; @@ -2197,7 +2197,7 @@ namespace IOB_WIN_FORM.Iob rawDataInizio = ""; if (!isMulti) { - rawDataInizio = await utils.callUrlAsync(urlInizioOdlIob); + rawDataInizio = await HttpService.CallUrlAsync(urlInizioOdlIob); DateTime.TryParse(rawDataInizio, out inizioOdl); } else @@ -2207,7 +2207,7 @@ namespace IOB_WIN_FORM.Iob foreach (var item in IOBConfFull.Device.MultiIobList) { fullUrl = $"{urlInizioOdlIob}|{item}"; - rawDataInizio = await utils.callUrlAsync(fullUrl); + rawDataInizio = await HttpService.CallUrlAsync(fullUrl); DateTime.TryParse(rawDataInizio, out tmpData); inizioOdl = (tmpData < inizioOdl) ? tmpData : inizioOdl; } @@ -2221,7 +2221,7 @@ namespace IOB_WIN_FORM.Iob { // controllo SE sono fermo (spento o in manuale) per il // periodo minimo richiesto... - rawIdle = await utils.callUrlAsync(urlIdleTime); + rawIdle = await HttpService.CallUrlAsync(urlIdleTime); int.TryParse(rawIdle, out idlePeriod); } else @@ -2231,7 +2231,7 @@ namespace IOB_WIN_FORM.Iob foreach (var item in IOBConfFull.Device.MultiIobList) { fullUrl = $"{urlIdleTime}|{item}"; - rawIdle = await utils.callUrlAsync(fullUrl); + rawIdle = await HttpService.CallUrlAsync(fullUrl); int.TryParse(rawIdle, out tmpIdle); idlePeriod = tmpIdle > idlePeriod ? tmpIdle : idlePeriod; } @@ -2246,7 +2246,7 @@ namespace IOB_WIN_FORM.Iob // fare, se sfora (RANDOM) > +(50...110)% --> cambia! if (!callChangeODL && IOBConfFull.Odl.ChangeOdlMode == "SIMUL") { - var rawCount = await utils.callUrlAsync(urlGetNumPzCurrODL); + var rawCount = await HttpService.CallUrlAsync(urlGetNumPzCurrODL); if (int.TryParse(rawCount, out var numPzReqOdl)) { int limitQty = (numPzReqOdl * rndGen.Next(150, 210)) / 100; @@ -2756,21 +2756,21 @@ namespace IOB_WIN_FORM.Iob { // leggo PRIMA ODL .... calcUrl = string.IsNullOrEmpty(forceMach) ? urlGetCurrODL : urlGetCurrODL.Replace(IOBConfFull.General.CodIOB, forceMach); - lastIdxODL = utils.callUrl(calcUrl); + lastIdxODL = HttpService.CallUrl(calcUrl); lgTrace($"Lettura ODL dall'url {calcUrl} --> {lastIdxODL}"); // se ho valori in coda da trasmettere uso dati REDIS if (forceCountRec) { // uso dati da TCiclo registrati... calcUrl = string.IsNullOrEmpty(forceMach) ? urlGetPzCountRec : urlGetPzCountRec.Replace(IOBConfFull.General.CodIOB, forceMach); - currServerCount = utils.callUrl(calcUrl); + currServerCount = HttpService.CallUrl(calcUrl); lgInfo($"Lettura contapezzi da TCiclo registrati dall'url {calcUrl} --> num pz: {currServerCount}"); } else { // uso il contapezzi dichiarato dall'IOB stesso calcUrl = string.IsNullOrEmpty(forceMach) ? urlGetPzCount : urlGetPzCount.Replace(IOBConfFull.General.CodIOB, forceMach); - currServerCount = utils.callUrl(calcUrl); + currServerCount = HttpService.CallUrl(calcUrl); lgInfo($"Lettura contapezzi dall'url {calcUrl} --> {currServerCount}"); } // controllo: SE NON HO ODL... @@ -3213,8 +3213,8 @@ namespace IOB_WIN_FORM.Iob } string rawData = JsonConvert.SerializeObject(ActiveAlarmList); - string resp = utils.CallUrlPost(lastUrl, rawData); - //string resp = utils.callUrlAsync(lastUrl, rawData); + string resp = HttpService.CallUrlPost(lastUrl, rawData); + //string resp = HttpService.CallUrlAsync(lastUrl, rawData); if (resp != null) { if (resp.ToUpper() == "OK") @@ -3258,7 +3258,7 @@ namespace IOB_WIN_FORM.Iob if (await CheckServerAliveAsync()) { // chiamo URL! - string answ = await utils.callUrlAsync(lastUrl, payload); + string answ = await HttpService.CallUrlAsync(lastUrl, payload); // loggo! lgInfo($"[SEND payload] TipoURL: {tipoUrl} | {listQueueVal.Count} records --> {answ}"); @@ -3346,7 +3346,7 @@ namespace IOB_WIN_FORM.Iob if (await CheckServerAliveAsync()) { // chiamo URL! - string answ = await utils.callUrlAsync(lastUrl); + string answ = await HttpService.CallUrlAsync(lastUrl); // loggo! lgDebug(string.Format("[SEND] {0} -> {1}", queueVal, answ)); // se oltre 1 min NON era online --> check pezzi! @@ -3870,7 +3870,7 @@ namespace IOB_WIN_FORM.Iob await Task.Delay(rand.Next(150, 500)); } - string resp = await utils.callUrlAsync(urlAlive); + string resp = await HttpService.CallUrlAsync(urlAlive); if (resp == "OK") return true; } catch (Exception ex) @@ -5252,7 +5252,7 @@ namespace IOB_WIN_FORM.Iob // vieto controllo prima di 5 sec... da configurare? if (DateTime.Now.Subtract(vetoCheckOdl).TotalSeconds > IOBConfFull.Odl.VetoCheckOdlSec) { - string sCurrODL = utils.CallUrlGet(urlGetCurrODL); + string sCurrODL = HttpService.CallUrlGet(urlGetCurrODL); int.TryParse(sCurrODL, out cODL); currIdxODL = cODL; vetoCheckOdl = DateTime.Now; @@ -5594,7 +5594,7 @@ namespace IOB_WIN_FORM.Iob { lgInfo("chiamata URL " + url2call); } - var rawData = utils.CallUrlGet(url2call); + var rawData = HttpService.CallUrlGet(url2call); // deserializzo e recupero KVP... var dictArtSrv = JsonConvert.DeserializeObject>(rawData); // se fosse una chiamata con valore vuoto --> salvo intera tabella... @@ -5641,7 +5641,7 @@ namespace IOB_WIN_FORM.Iob lgInfo("chiamata URL " + url2call); } // è direttamente il risultato! - answ = utils.CallUrlGet(url2call); + answ = HttpService.CallUrlGet(url2call); } // restituisco return answ; @@ -5659,11 +5659,11 @@ namespace IOB_WIN_FORM.Iob { lgInfo("chiamata URL " + url2call); } - answ = utils.CallUrlGet(url2call); + answ = HttpService.CallUrlGet(url2call); // se vuoto faccio seconda prova... if (string.IsNullOrEmpty(answ) || answ == "[]") { - answ = utils.CallUrlGet(url2call); + answ = HttpService.CallUrlGet(url2call); } return answ; } @@ -5704,7 +5704,7 @@ namespace IOB_WIN_FORM.Iob { lgInfo("chiamata URL " + url2call); } - answ = await utils.callUrlAsync(url2call); + answ = await HttpService.CallUrlAsync(url2call); } return answ; } @@ -6182,7 +6182,7 @@ namespace IOB_WIN_FORM.Iob // PONTE SYNC/ASYNC: Ora sw.Stop() aspetterà la fine reale dell'operazione Task.Run(async () => { - var rawListPODL = await utils.callUrlAsync(urlGetNextPODL); + var rawListPODL = await HttpService.CallUrlAsync(urlGetNextPODL); if (!string.IsNullOrEmpty(rawListPODL)) { reqPOdlList = JsonConvert.DeserializeObject>(rawListPODL) ?? new List(); @@ -6324,7 +6324,7 @@ namespace IOB_WIN_FORM.Iob DateTime dataDoc = DateTime.Today; DateTime.TryParse(fileName, out dataDoc); // cerco lotto x giornata... - string sIdxODL = utils.callUrl(urlGetOdlAtDate(dataDoc)); + string sIdxODL = HttpService.CallUrl(urlGetOdlAtDate(dataDoc)); int.TryParse(sIdxODL, out idxODL); // chiamo conversione TimeSpan timeElaps = fpm.doProcess(fileItem, idxODL); @@ -6435,7 +6435,7 @@ namespace IOB_WIN_FORM.Iob plcWriteParams(ref updatedPar); // invio su cloud parametri! string rawData = JsonConvert.SerializeObject(updatedPar); - utils.callUrl($"{urlUpdateWriteParams}", rawData); + HttpService.CallUrl($"{urlUpdateWriteParams}", rawData); lgInfo($"Notifica a server scrittura {updatedPar.Count} parametri"); } } @@ -6726,7 +6726,7 @@ namespace IOB_WIN_FORM.Iob // invio ANCHE in MP-IO l'update delle info... string remUrl = urlSetHashDict; string dictPayload = JsonConvert.SerializeObject(redHashWeek); - await utils.callUrlAsync(remUrl, dictPayload); + await HttpService.CallUrlAsync(remUrl, dictPayload); } } @@ -6986,7 +6986,7 @@ namespace IOB_WIN_FORM.Iob // PONTE SYNC/ASYNC: Ora sw.Stop() aspetterà la fine reale dell'operazione Task.Run(async () => { - var rawListPODL = await utils.callUrlAsync(urlGetNextPODL); + var rawListPODL = await HttpService.CallUrlAsync(urlGetNextPODL); if (!string.IsNullOrEmpty(rawListPODL)) { try @@ -7128,7 +7128,7 @@ namespace IOB_WIN_FORM.Iob url2call = $"{urlRemTask2ExeTav(codTav)}{taskName}"; } - await utils.callUrlAsync(url2call); + await HttpService.CallUrlAsync(url2call); } return answ; } @@ -7179,7 +7179,7 @@ namespace IOB_WIN_FORM.Iob { bool answ = false; DateTime dtCurr = DateTime.Now; - string resp = await utils.callUrlAsync($"{urlODLClose}{idxOdl}&dtEve={dtRif}&dtCurr={dtCurr}"); + string resp = await HttpService.CallUrlAsync($"{urlODLClose}{idxOdl}&dtEve={dtRif}&dtCurr={dtCurr}"); answ = resp == "OK"; return answ; } @@ -7200,7 +7200,7 @@ namespace IOB_WIN_FORM.Iob Task.Run(async () => { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); answ = callResp == "OK"; }) .GetAwaiter() @@ -7277,7 +7277,7 @@ namespace IOB_WIN_FORM.Iob // salvo nuovo valore invio LastSendSet(sendKey, DateTime.Now); // procedo - var result = await utils.callUrlAsync(urlSetM2IOB); + var result = await HttpService.CallUrlAsync(urlSetM2IOB); lgInfo($"chiamata URL {urlSetM2IOB} | result: {result}"); } } @@ -7351,7 +7351,7 @@ namespace IOB_WIN_FORM.Iob // invio e salvo... string remUrl = urlSaveMachIobConf; string dictPayload = JsonConvert.SerializeObject(currDict); - await utils.callUrlAsync(remUrl, dictPayload); + await HttpService.CallUrlAsync(remUrl, dictPayload); lgTrace("Invio MachineConf effettuato"); } } @@ -7377,7 +7377,7 @@ namespace IOB_WIN_FORM.Iob { string url2call = $"{urlSetOptVal}pName={paramName}&pValue={paramValue}"; lgInfo("chiamata URL " + url2call); - await utils.callUrlAsync(url2call); + await HttpService.CallUrlAsync(url2call); } } } @@ -7410,7 +7410,7 @@ namespace IOB_WIN_FORM.Iob Task.Run(async () => { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); answ = callResp == "OK"; }) .GetAwaiter() @@ -7440,7 +7440,7 @@ namespace IOB_WIN_FORM.Iob Task.Run(async () => { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); answ = callResp == "OK"; }) .GetAwaiter() @@ -7606,7 +7606,7 @@ namespace IOB_WIN_FORM.Iob // se abilitato faccio invio e salvo nuovo valore if (sendEnab) { - var resp = utils.callUrl($"{urlSaveMemMap}", rawData); + var resp = HttpService.CallUrl($"{urlSaveMemMap}", rawData); } } else @@ -7681,7 +7681,7 @@ namespace IOB_WIN_FORM.Iob // versione upsert tipoCall = urlUpdateWriteParams; } - var resp = utils.callUrl($"{tipoCall}", rawData); + var resp = HttpService.CallUrl($"{tipoCall}", rawData); } else { @@ -7993,7 +7993,7 @@ namespace IOB_WIN_FORM.Iob try { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); fatto = (callResp != "KO") ? true : false; } catch @@ -8037,7 +8037,7 @@ namespace IOB_WIN_FORM.Iob try { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); fatto = (callResp != "KO") ? true : false; } catch @@ -8083,7 +8083,7 @@ namespace IOB_WIN_FORM.Iob try { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); fatto = (callResp != "KO") ? true : false; } catch @@ -8107,7 +8107,7 @@ namespace IOB_WIN_FORM.Iob Task.Run(async () => { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); fatto = (callResp != "KO") ? true : false; }) .GetAwaiter() @@ -8139,7 +8139,7 @@ namespace IOB_WIN_FORM.Iob Task.Run(async () => { // invio chiamata URL x chiusura ODL su macchina - string callResp = await utils.callUrlAsync(fullUrl); + string callResp = await HttpService.CallUrlAsync(fullUrl); fatto = (callResp != "KO") ? true : false; }) .GetAwaiter() @@ -8168,7 +8168,7 @@ namespace IOB_WIN_FORM.Iob // PONTE SYNC/ASYNC: Ora sw.Stop() aspetterà la fine reale dell'operazione Task.Run(async () => { - string resp = await utils.callUrlAsync(urlEncoded); + string resp = await HttpService.CallUrlAsync(urlEncoded); int.TryParse(resp, out answ); }) .GetAwaiter() @@ -8214,7 +8214,7 @@ namespace IOB_WIN_FORM.Iob numIncr = delta > maxSendPzCountBlock + minSendPzCountBlock ? maxSendPzCountBlock : delta - minSendPzCountBlock; // invio il num max di pezzi ammesso in blocco! lastUrl = $"{urlAddPzCount}{numIncr}".Replace(IOBConfFull.General.CodIOB, fullCode); - string resp = utils.CallUrlGet(lastUrl); + string resp = HttpService.CallUrlGet(lastUrl); if (!string.IsNullOrEmpty(resp)) { // dalla risposta (come numero) capisco SE ha aggiunto i pezzi (e quanti) @@ -8226,7 +8226,7 @@ namespace IOB_WIN_FORM.Iob lgInfo($"SEND incremento contapezzi: send: {numIncr} | resp: {qtyAdded} | contapezziMES: {pzCountMes}"); // invio conferma contapezzi.. string fullUrl = $"{urlSetPzCount}{pzCountMes}".Replace(IOBConfFull.General.CodIOB, fullCode); - string retVal = utils.callUrl(fullUrl); + string retVal = HttpService.CallUrl(fullUrl); // verifica se tutto OK if (retVal != $"{pzCountMes}") { @@ -8288,7 +8288,7 @@ namespace IOB_WIN_FORM.Iob numIncr = delta > maxSendPzCountBlock + minSendPzCountBlock ? maxSendPzCountBlock : delta - minSendPzCountBlock; // invio il num max di pezzi ammesso in blocco! lastUrl = $"{urlAddPzCount}{numIncr}"; - string resp = utils.CallUrlGet(lastUrl); + string resp = HttpService.CallUrlGet(lastUrl); if (!string.IsNullOrEmpty(resp)) { // dalla risposta (come numero) capisco SE ha aggiunto i pezzi (e quanti) @@ -8300,7 +8300,7 @@ namespace IOB_WIN_FORM.Iob lgInfo($"SEND incremento contapezzi: send: {numIncr} | resp: {qtyAdded} | contapezziIOB: {contapezziIOB}"); // invio conferma contapezzi.. string fullUrl = $"{urlSetPzCount}{contapezziIOB}"; - string retVal = utils.callUrl(fullUrl); + string retVal = HttpService.CallUrl(fullUrl); // verifica se tutto OK if (retVal != contapezziIOB.ToString()) { @@ -8434,7 +8434,7 @@ namespace IOB_WIN_FORM.Iob try { // invio chiamata URL x avvio PODL su macchina - string rawSplit = await utils.callUrlAsync(fullUrl); + string rawSplit = await HttpService.CallUrlAsync(fullUrl); fatto = (rawSplit != "KO") ? true : false; } catch @@ -8459,7 +8459,7 @@ namespace IOB_WIN_FORM.Iob try { // invio chiamata URL x avvio PODL su macchina - string rawSplit = await utils.callUrlAsync(fullUrl); + string rawSplit = await HttpService.CallUrlAsync(fullUrl); fatto = (rawSplit != "KO") ? true : false; } catch @@ -8760,7 +8760,7 @@ namespace IOB_WIN_FORM.Iob private async Task currOdlStart() { DateTime inizioOdl = DateTime.Now; - string rawDataInizio = await utils.callUrlAsync(urlInizioOdlIob); + string rawDataInizio = await HttpService.CallUrlAsync(urlInizioOdlIob); DateTime.TryParse(rawDataInizio, out inizioOdl); return inizioOdl; } @@ -8900,7 +8900,7 @@ namespace IOB_WIN_FORM.Iob await Task.Delay(delay); } - string callResp = await utils.callUrlAsync(urlIobEnabled); + string callResp = await HttpService.CallUrlAsync(urlIobEnabled); if (callResp == "OK") return true; } catch (Exception exc) @@ -9208,7 +9208,7 @@ namespace IOB_WIN_FORM.Iob plcWriteParams(ref updatedPar); // invio su cloud parametri! string rawData = JsonConvert.SerializeObject(updatedPar); - utils.CallUrlPost($"{urlUpdateWriteParams}", rawData); + HttpService.CallUrlPost($"{urlUpdateWriteParams}", rawData); lgInfo($"Notificato a server scrittura {updatedPar.Count} parametri"); } else @@ -9218,7 +9218,7 @@ namespace IOB_WIN_FORM.Iob { // invio su cloud parametri! string rawData = JsonConvert.SerializeObject(currWritePar); - var res = utils.CallUrlPost($"{urlUpdateWriteParams}", rawData); + var res = HttpService.CallUrlPost($"{urlUpdateWriteParams}", rawData); lgInfo($"Reinviato a server stato {updatedPar.Count} parametri WRITE"); lastWriteParamsUpsert = adesso; } @@ -9473,12 +9473,12 @@ namespace IOB_WIN_FORM.Iob // prova ad avviare/chiudere PODL relativo (eventualmente duplicandolo) dtEve = $"{dtStartPOdl:yyyyMMddHHmmssfff}"; dtCurr = $"{DateTime.Now:yyyyMMddHHmmssfff}"; - await utils.callUrlAsync($"{urlOdlStartFromPOdl}{idxPOdl}&dtEve={dtEve}&dtCurr={dtCurr}"); + await HttpService.CallUrlAsync($"{urlOdlStartFromPOdl}{idxPOdl}&dtEve={dtEve}&dtCurr={dtCurr}"); // ora chiamo chiusura... dtEve = $"{dtEndPOdl:yyyyMMddHHmmssfff}"; dtCurr = $"{DateTime.Now:yyyyMMddHHmmssfff}"; - await utils.callUrlAsync($"{urlPODLClose}{idxPOdl}&dtEve={dtEve}&dtCurr={dtCurr}"); + await HttpService.CallUrlAsync($"{urlPODLClose}{idxPOdl}&dtEve={dtEve}&dtCurr={dtCurr}"); }) .GetAwaiter() .GetResult(); @@ -9506,7 +9506,7 @@ namespace IOB_WIN_FORM.Iob // invio ANCHE in MP-IO l'update delle info... string remUrl = urlSetHashDict; string dictPayload = JsonConvert.SerializeObject(currDict); - await utils.callUrlAsync(remUrl, dictPayload); + await HttpService.CallUrlAsync(remUrl, dictPayload); //await callUrlWithPayloadAsync(remUrl, dictPayload, true); //await callUrlWithPayloadAsync(remUrl, dictPayload, false); } diff --git a/IOB-WIN-FORM/Iob/Simula.cs b/IOB-WIN-FORM/Iob/Simula.cs index 8ac522b9..992dd3ec 100644 --- a/IOB-WIN-FORM/Iob/Simula.cs +++ b/IOB-WIN-FORM/Iob/Simula.cs @@ -1,5 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Iob.Services; using MapoSDK; using Newtonsoft.Json; using System; @@ -1045,7 +1046,7 @@ namespace IOB_WIN_FORM.Iob DateTime adesso = DateTime.Now; // faccio cmq tutto... - string autoOdlRes = utils.callUrl(urlFixDailyOdl); + string autoOdlRes = HttpService.CallUrl(urlFixDailyOdl); // salvo lettura lastReadPLC = adesso; @@ -1267,7 +1268,7 @@ namespace IOB_WIN_FORM.Iob { fullUrl = $"{urlSetPzCount.Replace(IOBConfFull.General.CodIOB, $"{IOBConfFull.General.CodIOB}|TAV_{nP}")}{contapezziPLC}"; } - string retVal = utils.callUrl(fullUrl); + string retVal = HttpService.CallUrl(fullUrl); // verifica salvataggio if (retVal != contapezziIOB.ToString()) { @@ -1279,7 +1280,7 @@ namespace IOB_WIN_FORM.Iob } else { - string retVal = utils.callUrl($"{urlSetPzCount}{contapezziIOB}"); + string retVal = HttpService.CallUrl($"{urlSetPzCount}{contapezziIOB}"); if (retVal != contapezziIOB.ToString()) { // errore salvataggio contapezzi @@ -1442,7 +1443,7 @@ namespace IOB_WIN_FORM.Iob { fullUrl = $"{urlSetPzCount.Replace(IOBConfFull.General.CodIOB, $"{IOBConfFull.General.CodIOB}|TAV_{nP}")}{contapezziIOB}"; } - string retVal = utils.callUrl(fullUrl); + string retVal = HttpService.CallUrl(fullUrl); // verifica se tutto OK if (retVal != contapezziIOB.ToString()) { @@ -1496,7 +1497,7 @@ namespace IOB_WIN_FORM.Iob contapezziPLC++; // invio contapezzi... string fullUrl = $"{urlSetPzCount.Replace(IOBConfFull.General.CodIOB, $"{IOBConfFull.General.CodIOB}|TAV_{nP}")}{contapezziIOB}"; - string retVal = utils.callUrl(fullUrl); + string retVal = HttpService.CallUrl(fullUrl); } // se cP > 0 --> segnalo bit tavola... if (cP == 1) @@ -1599,10 +1600,10 @@ namespace IOB_WIN_FORM.Iob // PONTE SYNC/ASYNC: Ora sw.Stop() aspetterà la fine reale dell'operazione Task.Run(async () => { - var rawListArt = await utils.callUrlAsync(urlGetCurrArt); - var rawListDOSS = await utils.callUrlAsync(urlGetCurrDOSS); - var rawListPODL = await utils.callUrlAsync(urlGetNextPODL); - var rawLVFasi = await utils.callUrlAsync(urlGetListValFasiPodl); + var rawListArt = await HttpService.CallUrlAsync(urlGetCurrArt); + var rawListDOSS = await HttpService.CallUrlAsync(urlGetCurrDOSS); + var rawListPODL = await HttpService.CallUrlAsync(urlGetNextPODL); + var rawLVFasi = await HttpService.CallUrlAsync(urlGetListValFasiPodl); if (!string.IsNullOrEmpty(rawListArt)) { @@ -1750,9 +1751,9 @@ namespace IOB_WIN_FORM.Iob // PONTE SYNC/ASYNC: Ora sw.Stop() aspetterà la fine reale dell'operazione Task.Run(async () => { - var rawListArt = await utils.callUrlAsync(urlGetCurrArt); - var rawListDOSS = await utils.callUrlAsync(urlGetCurrDOSS); - var rawListPODL = await utils.callUrlAsync(urlGetNextPODL); + var rawListArt = await HttpService.CallUrlAsync(urlGetCurrArt); + var rawListDOSS = await HttpService.CallUrlAsync(urlGetCurrDOSS); + var rawListPODL = await HttpService.CallUrlAsync(urlGetNextPODL); if (!string.IsNullOrEmpty(rawListArt)) { try @@ -2165,7 +2166,7 @@ namespace IOB_WIN_FORM.Iob private void sendDataItemsList(List dataItems) { string rawData = JsonConvert.SerializeObject(dataItems); - utils.CallUrlPost($"{urlSaveDataItems}", rawData); + HttpService.CallUrlPost($"{urlSaveDataItems}", rawData); } /// diff --git a/IOB-WIN-FORM/MainForm.cs b/IOB-WIN-FORM/MainForm.cs index f7729be3..72ec1d1d 100644 --- a/IOB-WIN-FORM/MainForm.cs +++ b/IOB-WIN-FORM/MainForm.cs @@ -1,5 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Iob.Services; using MapoSDK; using MathNet.Numerics.Distributions; using Newtonsoft.Json; @@ -29,6 +30,11 @@ namespace IOB_WIN_FORM /// public static Logger lg; + /// + /// Configurazione gerarchica completa (v 4.x.x.x) + /// + public IobConfTree IOBConfFull = new IobConfTree(); + /// /// Data ultimo controllo comunicazione /// @@ -113,7 +119,6 @@ namespace IOB_WIN_FORM } else { - if (utils.dtVetoPing < DateTime.Now) { IPStatus pingStatus = GetPingStatus(); @@ -123,7 +128,7 @@ namespace IOB_WIN_FORM try { // chiamo URL, se restituisce "OK" è alive! - string callResp = utils.callUrl(urlAlive); + string callResp = HttpService.CallUrl(urlAlive); answ = (callResp == "OK"); } catch (Exception exc) @@ -403,39 +408,17 @@ namespace IOB_WIN_FORM /// /// URL per recuperare i file dell'IOB (SENZA IOB) /// - protected string urlDownloadFile - { - get => $"http://{MPIP}{MPURL}/IOB/getFiles/"; - } + protected string urlDownloadFile => $"http://{MPIP}{MPURL}/IOB/getFiles/"; /// /// URL per recuperare i file dell'IOB su CLOUD (SENZA IOB) /// - protected string urlDownloadFileCloud - { - get - { - return $"{baseUrl}IOB/getFiles/"; - } - } + protected string urlDownloadFileCloud => $"{baseUrl}IOB/getFiles/"; /// /// URL per chiedere quale sia la IOB da acquisire/gestire (se c'è...) /// - protected string urlIob2call - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}{3}", MPIP, MPURL, CMDIOB2CALL, utils.GetIP()); - } - catch - { } - return answ; - } - } + protected string urlIob2call => $"http://{MPIP}{MPURL}{CMDIOB2CALL}{NetService.GetIP()}"; /// /// URL per segnalazione reboot... @@ -444,34 +427,31 @@ namespace IOB_WIN_FORM { get { - string answ = ""; + // 1. Creiamo l'URL base (chiamando GetIP una sola volta) + string baseUrl = $"http://{MPIP}{MPURL}{CMDREBO}{NetService.GetIP()}"; + try { - answ = string.Format(@"http://{0}{1}{2}{3}&mac={4}", MPIP, MPURL, CMDREBO, utils.GetIP(), utils.GetMACAddress()); + // 2. Proviamo ad accodare il MAC Address + return $"{baseUrl}&mac={NetService.GetMACAddress()}"; } catch { - answ = string.Format(@"http://{0}{1}{2}{3}", MPIP, MPURL, CMDREBO, utils.GetIP()); + // 3. Se GetMACAddress() fallisce, restituiamo l'URL senza MAC + return baseUrl; } - return answ; } } /// /// URL per salvare i file dell'IOB (SENZA IOB) /// - protected string urlUploadFile - { - get => $"http://{MPIP}{MPURL}/IOB/uploadFile/"; - } + protected string urlUploadFile => $"http://{MPIP}{MPURL}/IOB/uploadFile/"; /// /// URL per salvare i file dell'IOB su CLOUD (SENZA IOB) /// - protected string urlUploadFileCloud - { - get => $"{baseUrl}IOB/uploadFile/"; - } + protected string urlUploadFileCloud => $"{baseUrl}IOB/uploadFile/"; #endregion Protected Properties @@ -496,6 +476,7 @@ namespace IOB_WIN_FORM lg.Factory.Configuration.Variables["codIOB"] = "MAIN"; lg.Info(txt2log); } + /// /// Effettua logging WARN corretto impostando anche la variabile IOB prima di scrivere... /// @@ -526,14 +507,6 @@ namespace IOB_WIN_FORM this.LayoutMdi(MdiLayout.TileHorizontal); } - protected override void OnFormClosing(FormClosingEventArgs e) - { - MainTimer?.Stop(); - MainTimer?.Dispose(); - closeActiveChild(); - base.OnFormClosing(e); - } - /// /// Chiude le finestre child attive /// @@ -629,7 +602,7 @@ namespace IOB_WIN_FORM if (pingStatus == IPStatus.Success) { // segnalo reboot (programma)... - utils.callUrl(urlReboot); + HttpService.CallUrl(urlReboot); } else { @@ -643,6 +616,14 @@ namespace IOB_WIN_FORM displayTaskAndLog("Main Form OK"); } + protected override void OnFormClosing(FormClosingEventArgs e) + { + MainTimer?.Stop(); + MainTimer?.Dispose(); + closeActiveChild(); + base.OnFormClosing(e); + } + /// /// Apre la finestra child con conf /// @@ -702,6 +683,8 @@ namespace IOB_WIN_FORM /// private static bool closed = false; + private FormWindowState _lastState = FormWindowState.Minimized; + /// /// Nome applicazione (da app.config) /// @@ -709,58 +692,6 @@ namespace IOB_WIN_FORM #endregion Private Fields - #region Private Properties - - /// - /// Configurazione gerarchica completa (v 4.x.x.x) - /// - public IobConfTree IOBConfFull = new IobConfTree(); - - /// - /// test ping all'indirizzo impostato nei parametri - /// - /// - private IPStatus GetPingStatus() - { - IPStatus answ = IPStatus.Unknown; - // se disabilitato salto... - if (IOBConfFull != null && IOBConfFull.MapoMes.DisabPing) - { - answ = IPStatus.Success; - } - else - { - IPAddress address; - PingReply reply; - using (Ping pingSender = new Ping()) - { - address = IPAddress.Loopback; - string ipAdrr = MPIP; - IPAddress.TryParse(ipAdrr, out address); - try - { - // se != null --> uso address... - if (address != null) - { - reply = pingSender.Send(address, 500); - } - else - { - reply = pingSender.Send(MPIP, 500); - } - } - catch - { - reply = pingSender.Send(IPAddress.Loopback, 100); - } - } - answ = reply.Status; - } - return answ; - } - - #endregion Private Properties - #region Private Methods private void arrangeWindowsToolStripMenuItem_Click(object sender, EventArgs e) @@ -904,7 +835,7 @@ namespace IOB_WIN_FORM // invio in locale! url2call = $"{urlDownloadFile}{currIob}"; } - rawData = utils.CallUrlGet(url2call); + rawData = HttpService.CallUrlGet(url2call); if (!string.IsNullOrEmpty(rawData)) { // deserializzo @@ -956,6 +887,49 @@ namespace IOB_WIN_FORM // file MAIN di avvio ripartendo...) } + /// + /// test ping all'indirizzo impostato nei parametri + /// + /// + private IPStatus GetPingStatus() + { + IPStatus answ = IPStatus.Unknown; + // se disabilitato salto... + if (IOBConfFull != null && IOBConfFull.MapoMes.DisabPing) + { + answ = IPStatus.Success; + } + else + { + IPAddress address; + PingReply reply; + using (Ping pingSender = new Ping()) + { + address = IPAddress.Loopback; + string ipAdrr = MPIP; + IPAddress.TryParse(ipAdrr, out address); + try + { + // se != null --> uso address... + if (address != null) + { + reply = pingSender.Send(address, 500); + } + else + { + reply = pingSender.Send(MPIP, 500); + } + } + catch + { + reply = pingSender.Send(IPAddress.Loopback, 100); + } + } + answ = reply.Status; + } + return answ; + } + /// /// Carica file ini della configurazione richiesta /// @@ -1049,8 +1023,6 @@ namespace IOB_WIN_FORM _lastState = this.WindowState; } - private FormWindowState _lastState = FormWindowState.Minimized; - /// /// evento visualizzazione /// From 8a30c6c07ee7b401fe0331f8bd7592c5055fcdbb Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 21 May 2026 18:07:25 +0200 Subject: [PATCH 6/7] 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 /// From b4cc07c82c809651664bff0b76ad146b9265b464 Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 21 May 2026 18:08:07 +0200 Subject: [PATCH 7/7] Update x test in SIM --- IOB-WIN-FANUC/DATA/CONF/MAIN.ini | 1 - IOB-WIN-FTP/DATA/CONF/MAIN.ini | 1 - IOB-WIN-MTC/DATA/CONF/MAIN.ini | 1 - IOB-WIN-OPC-UA/DATA/CONF/MAIN.ini | 1 - IOB-WIN-PING/DATA/CONF/MAIN.ini | 1 - IOB-WIN-SIEMENS/DATA/CONF/MAIN.ini | 1 - IOB-WIN-WPS/DATA/CONF/MAIN.ini | 1 - 7 files changed, 7 deletions(-) diff --git a/IOB-WIN-FANUC/DATA/CONF/MAIN.ini b/IOB-WIN-FANUC/DATA/CONF/MAIN.ini index 51e0748d..f621315d 100644 --- a/IOB-WIN-FANUC/DATA/CONF/MAIN.ini +++ b/IOB-WIN-FANUC/DATA/CONF/MAIN.ini @@ -34,4 +34,3 @@ CLI_INST=SteamWareSim STARTLIST=SIMUL_01 MAXCNC=10 - diff --git a/IOB-WIN-FTP/DATA/CONF/MAIN.ini b/IOB-WIN-FTP/DATA/CONF/MAIN.ini index 2cb4f81c..ebc0bef6 100644 --- a/IOB-WIN-FTP/DATA/CONF/MAIN.ini +++ b/IOB-WIN-FTP/DATA/CONF/MAIN.ini @@ -20,4 +20,3 @@ CLI_INST=SteamWareSim STARTLIST=FTP_SONATEST MAXCNC=10 - diff --git a/IOB-WIN-MTC/DATA/CONF/MAIN.ini b/IOB-WIN-MTC/DATA/CONF/MAIN.ini index b8e74cd4..4b123815 100644 --- a/IOB-WIN-MTC/DATA/CONF/MAIN.ini +++ b/IOB-WIN-MTC/DATA/CONF/MAIN.ini @@ -27,4 +27,3 @@ STARTLIST=3024 ;STARTLIST=LVF652 MAXCNC=10 - diff --git a/IOB-WIN-OPC-UA/DATA/CONF/MAIN.ini b/IOB-WIN-OPC-UA/DATA/CONF/MAIN.ini index acfaebef..afc5df70 100644 --- a/IOB-WIN-OPC-UA/DATA/CONF/MAIN.ini +++ b/IOB-WIN-OPC-UA/DATA/CONF/MAIN.ini @@ -34,4 +34,3 @@ STARTLIST=3026 ;STARTLIST=SIMUL_01 MAXCNC=10 - diff --git a/IOB-WIN-PING/DATA/CONF/MAIN.ini b/IOB-WIN-PING/DATA/CONF/MAIN.ini index 14fc4c91..01bdf429 100644 --- a/IOB-WIN-PING/DATA/CONF/MAIN.ini +++ b/IOB-WIN-PING/DATA/CONF/MAIN.ini @@ -20,4 +20,3 @@ STARTLIST=SIMUL_01 ;STARTLIST=3023-PING MAXCNC=10 - diff --git a/IOB-WIN-SIEMENS/DATA/CONF/MAIN.ini b/IOB-WIN-SIEMENS/DATA/CONF/MAIN.ini index babafa34..41774edf 100644 --- a/IOB-WIN-SIEMENS/DATA/CONF/MAIN.ini +++ b/IOB-WIN-SIEMENS/DATA/CONF/MAIN.ini @@ -42,4 +42,3 @@ CLI_INST=SteamWareSim STARTLIST=3010 MAXCNC=10 - diff --git a/IOB-WIN-WPS/DATA/CONF/MAIN.ini b/IOB-WIN-WPS/DATA/CONF/MAIN.ini index 5b0016e5..a81dc4b2 100644 --- a/IOB-WIN-WPS/DATA/CONF/MAIN.ini +++ b/IOB-WIN-WPS/DATA/CONF/MAIN.ini @@ -24,4 +24,3 @@ STARTLIST=3018 ;STARTLIST=SIMUL_06 MAXCNC=10 -