diff --git a/AGENTS.md b/AGENTS.md index cee8e2b8..a7b7a80b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,11 +4,11 @@ A collection of .NET (C#/VB) projects for industrial communication with NC controls (Fanuc, Siemens, Mitsubishi, etc.) via the Mapo Protocol. ## Build & Release -- **Toolchain**: MSBuild (`x86` target). -- **Config**: Always use `Release` configuration and `x86` platform. +- **Toolchain**: MSBuild. +- **Config**: Always use `Release` configuration. - **Command Example**: ```powershell - & "$env:MSBUILD_PATH" "ProjectName\ProjectName.csproj" -target:Build /p:Configuration=Release /p:Platform="x86" /p:OutputPath=bin/ /nodeReuse:false /verbosity:minimal /m + & "$env:MSBUILD_PATH" "ProjectName\ProjectName.csproj" -target:Build /p:Configuration=Release /p:OutputPath=bin/ /nodeReuse:false /verbosity:minimal /m ``` - **NuGet**: Requires Steamware Nexus Proxy sources. Use `dotnet nuget restore` on the specific `.sln` before building. - **Versioning**: Automated via `VersGen\VersGen.cs` and `.nuspec` updates during CI. Manual updates to `VersGen.cs` might be needed if mimicking CI. diff --git a/AGENTS.pdf b/AGENTS.pdf new file mode 100644 index 00000000..07040a28 Binary files /dev/null and b/AGENTS.pdf differ diff --git a/IOB-UT-NEXT/Config/Base/AlarmDto.cs b/IOB-UT-NEXT/Config/Base/AlarmDto.cs index deb05245..2a52e6d2 100644 --- a/IOB-UT-NEXT/Config/Base/AlarmDto.cs +++ b/IOB-UT-NEXT/Config/Base/AlarmDto.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using static IOB_UT_NEXT.BaseAlarmConf; +using static IOB_UT_NEXT.Config.BaseAlarmConf; namespace IOB_UT_NEXT.Config.Base { diff --git a/IOB-UT-NEXT/GenActConf.cs b/IOB-UT-NEXT/Config/GenActConf.cs similarity index 98% rename from IOB-UT-NEXT/GenActConf.cs rename to IOB-UT-NEXT/Config/GenActConf.cs index cac92fbe..eed4447f 100644 --- a/IOB-UT-NEXT/GenActConf.cs +++ b/IOB-UT-NEXT/Config/GenActConf.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Config { public class GenActConf { diff --git a/IOB-UT-NEXT/IniFile.cs b/IOB-UT-NEXT/Config/IniFile.cs similarity index 99% rename from IOB-UT-NEXT/IniFile.cs rename to IOB-UT-NEXT/Config/IniFile.cs index 66114c6a..7675e142 100644 --- a/IOB-UT-NEXT/IniFile.cs +++ b/IOB-UT-NEXT/Config/IniFile.cs @@ -3,7 +3,7 @@ using System.Globalization; using System.Runtime.InteropServices; using System.Text; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Config { /// /// Create a new INI file to store or load data diff --git a/IOB-UT-NEXT/Config/IobConfTree.cs b/IOB-UT-NEXT/Config/IobConfTree.cs index ee6d6996..b092ac15 100644 --- a/IOB-UT-NEXT/Config/IobConfTree.cs +++ b/IOB-UT-NEXT/Config/IobConfTree.cs @@ -1,7 +1,9 @@ using IOB_UT_NEXT.Config; using IOB_UT_NEXT.Config.Base; +using IOB_UT_NEXT.Config.Mem; using IOB_UT_NEXT.Config.Special; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using NLog; @@ -16,7 +18,7 @@ using System.Runtime.InteropServices.ComTypes; using System.Threading; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; -using static IOB_UT_NEXT.BaseAlarmConf; +using static IOB_UT_NEXT.Config.BaseAlarmConf; using static IOB_UT_NEXT.Config.EnumConf; using static System.Net.Mime.MediaTypeNames; diff --git a/IOB-UT-NEXT/plcMemMapExt.cs b/IOB-UT-NEXT/Config/Mem/plcMemMapExt.cs similarity index 92% rename from IOB-UT-NEXT/plcMemMapExt.cs rename to IOB-UT-NEXT/Config/Mem/plcMemMapExt.cs index 74d9fa29..7395aeba 100644 --- a/IOB-UT-NEXT/plcMemMapExt.cs +++ b/IOB-UT-NEXT/Config/Mem/plcMemMapExt.cs @@ -1,12 +1,7 @@ -using IOB_UT_NEXT.Config.Special; -using MapoSDK; -using System; +using MapoSDK; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Config.Mem { public class plcMemMapExt : plcMemMap { diff --git a/IOB-UT-NEXT/Config/ExtToolConf.cs b/IOB-UT-NEXT/Config/Special/ExtToolConf.cs similarity index 98% rename from IOB-UT-NEXT/Config/ExtToolConf.cs rename to IOB-UT-NEXT/Config/Special/ExtToolConf.cs index 9ba5b529..cfb7f5e4 100644 --- a/IOB-UT-NEXT/Config/ExtToolConf.cs +++ b/IOB-UT-NEXT/Config/Special/ExtToolConf.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace IOB_UT_NEXT.Config +namespace IOB_UT_NEXT.Config.Special { /// /// Implementazione di riferimento x un file di configurazione x esecuzione task tramite EgwCApp diff --git a/IOB-UT-NEXT/FtpActConf.cs b/IOB-UT-NEXT/Config/Special/FtpActConf.cs similarity index 96% rename from IOB-UT-NEXT/FtpActConf.cs rename to IOB-UT-NEXT/Config/Special/FtpActConf.cs index 1d7d3e80..d915f6a1 100644 --- a/IOB-UT-NEXT/FtpActConf.cs +++ b/IOB-UT-NEXT/Config/Special/FtpActConf.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Config.Special { public class FtpActConf : GenActConf { diff --git a/IOB-UT-NEXT/ToMapo.cs b/IOB-UT-NEXT/Config/ToMapo.cs similarity index 99% rename from IOB-UT-NEXT/ToMapo.cs rename to IOB-UT-NEXT/Config/ToMapo.cs index cd5d82d8..34b333a0 100644 --- a/IOB-UT-NEXT/ToMapo.cs +++ b/IOB-UT-NEXT/Config/ToMapo.cs @@ -2,9 +2,8 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Collections.Generic; -using System; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Config { /// /// Classe gestione configurazione parametri di base x allarmi diff --git a/IOB-UT-NEXT/IOB-UT-NEXT.csproj b/IOB-UT-NEXT/IOB-UT-NEXT.csproj index 298588a6..4b3f227b 100644 --- a/IOB-UT-NEXT/IOB-UT-NEXT.csproj +++ b/IOB-UT-NEXT/IOB-UT-NEXT.csproj @@ -156,9 +156,35 @@ - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -176,7 +202,7 @@ - + @@ -188,41 +214,39 @@ - - + + - - - - - + + + + + - - + - - - - - - - - - - - - + + + + + + + + + + + + + - + - + - - - + diff --git a/IOB-UT-NEXT/Iob/BaseObj.cs b/IOB-UT-NEXT/Iob/BaseObj.cs index c53a9160..6702d662 100644 --- a/IOB-UT-NEXT/Iob/BaseObj.cs +++ b/IOB-UT-NEXT/Iob/BaseObj.cs @@ -1,13 +1,23 @@ using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Config.Mem; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Cache; +using IOB_UT_NEXT.Services.Core; +using IOB_UT_NEXT.Services.Data; +using IOB_UT_NEXT.Services.Files; +using MapoSDK; +using Newtonsoft.Json; using NLog; using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; using System.Net.NetworkInformation; -using System.Threading; -using System.Threading.Tasks; -using static IOB_UT_NEXT.BaseAlarmConf; +using System.Runtime.Serialization.Formatters.Binary; +using System.Text.Json; +using System.Text.Json.Serialization; +using static IOB_UT_NEXT.Config.BaseAlarmConf; namespace IOB_UT_NEXT.Iob { @@ -90,24 +100,14 @@ namespace IOB_UT_NEXT.Iob public bool doStartMemDump; /// - /// Data/ora ultimo avvio adapter + /// Collettore di tutte le variabili scadenza DateTime /// - public DateTime dtAvvioAdp = DateTime.Now; + public DateTimeHelper DtHelp; /// - /// Data/ora ultimo spegnimento adapter + /// Collettore di tutte le Queue gestite /// - public DateTime dtStopAdp = DateTime.Now; - - /// - /// Indicazione VETO check status IOB x evitare loop troppo stretti... - /// - public DateTime dtVetoCheckIOB = DateTime.Now.AddDays(-1); - - /// - /// Indicazione VETO check sync ricette x evitare loop troppo stretti... - /// - public DateTime dtVetoCheckSyncRecipe = DateTime.Now.AddHours(-1); + public QueueHelper QHelp; /// /// Abilitazione lettura PrgName @@ -129,56 +129,11 @@ namespace IOB_UT_NEXT.Iob /// public IobConfTree IOBConfFull; - /// - /// dataOra ultima verifica CNC disconnesso... - /// - public DateTime lastDisconnCheck; - - /// - /// Data/ora ultima volta che IOB è stato dichiarato online - /// - public DateTime lastIobOnline = DateTime.Now.AddHours(-1); - - /// - /// Ultima verifica status IOB x forzare display status SRV - /// - public DateTime lastIobStatusDisplUpdate = DateTime.Now; - - /// - /// dataOra ultimo log periodico... - /// - public DateTime lastPeriodicLog; - - /// - /// dataOra ultimo PING inviato verso il PLC... - /// - public DateTime lastPING = DateTime.Now.AddHours(-1); - - /// - /// DataOra ultima lettura da PLC - /// - public DateTime lastReadPLC; - /// /// ULtimo valore inviato (in caso di disconnessione lo reinvia x garantire watchdog...) /// public string lastSignInVal = ""; - /// - /// DateTime Ultimo valore simulazione generato - /// - public DateTime lastSim; - - /// - /// dataOra ultimo segnale inviato al SERVER... - /// - public DateTime lastWatchDog; - - /// - /// dataOra ultimo segnale inviato a macchina/PLC... - /// - public DateTime lastWatchDogPLC = DateTime.Now; - /// /// Massimo numero di px da inviare in blocco /// @@ -205,51 +160,6 @@ namespace IOB_UT_NEXT.Iob /// public bool procIotMem = false; - /// - /// Coda valori ALLARMI ove gestiti... - /// - public DataQueue QueueAlarm; - - /// - /// Oggetto della coda degli elementi letti di tipo FluxLog (e non ancora trasmessi) - /// - public DataQueue QueueFLog; - - /// - /// Oggetto della coda degli elementi letti (e non ancora trasmessi) - /// - public DataQueue QueueIN; - - /// - /// Coda valori MESSAGGI/EVENTI (da non sottocampionare come samples)... - /// - public DataQueue QueueMessages; - - /// - /// Coda degli esiti di ping x calcolo stato macchina - /// - public DataQueue QueuePing; - - /// - /// Oggetto della coda degli elementi di tipo RawTransf (e non ancora trasmessi) - /// NB: sono salvati serializzati come stringhe - /// - public DataQueue QueueRawTransf;// = new DataQueue("000", "QueueRawTransf", false); - - /// - /// Coda delle richieste dal server (Task2Exe) - /// - public DataQueue QueueSrvReq; - - /// - /// Coda delle risposte al server (Task2Exe) - /// - public DataQueue QueueSrvResp; - - /// - /// Coda valori LOG UTENTE (da non sottocampionare come samples)... - /// - public DataQueue QueueULog;// = new DataQueue("000", "QueueULog", false); /// /// alias booleano false = R @@ -276,37 +186,11 @@ namespace IOB_UT_NEXT.Iob /// public Stopwatch sw = new Stopwatch(); - /// - /// Oggetto gestione TempiCiclo e contapezzi - /// - public TCMan tcMan = new TCMan(0.5, 1.3, 5); - - /// - /// Imposta veto lettura dati (es per DB a 2 sec) - /// - public DateTime vetoDataRead = DateTime.Now; - - /// - /// Imposta veto SYNC dati (es per DB 2 DB a 10 sec) - /// - public DateTime vetoDataSync = DateTime.Now; - /// /// Veto (in sec) a nuovi ping (x IOB PING, FTP...) /// public int vetoPingSec = 1; - /// - /// Veto specifico per la gestione (svuotamento) coda contapezzi (es in fase di attrezzaggio e reset lenti) - /// Tipicamente impostato a DelayReadPzCountSetup dopo attrezzaggio... - /// - public DateTime vetoQueuePzCount = DateTime.Now; - - /// - /// Imposta veto chiamata split (durante chiamata, per 60 sec) - /// - public DateTime vetoSplit = DateTime.Now.AddMinutes(1); - /// /// alias booleano true = W /// @@ -326,33 +210,6 @@ namespace IOB_UT_NEXT.Iob /// public static bool DemoOut => utils.CRB("DemoOut"); - /// - /// Indicazione VETO PING a server sino alla data-ora indicata - /// - public static DateTime dtVetoPing - { - get => utils.dtVetoPing; - set => utils.dtVetoPing = value; - } - - /// - /// Indicazione VETO accodamento valori INGRESSI/EVENTI sino alla data-ora indicata - /// - public static DateTime dtVetoQueueIN - { - get => utils.dtVetoQueueIN; - set => utils.dtVetoQueueIN = value; - } - - /// - /// Indicazione VETO invio a server sino alla data-ora indicata - /// - public static DateTime dtVetoSend - { - get => utils.dtVetoSend; - set => utils.dtVetoSend = value; - } - /// /// Verifica se sia abilitato test lettura blocchi memoria all'avvio /// @@ -398,18 +255,121 @@ namespace IOB_UT_NEXT.Iob #region Protected Fields - + /// + /// Variabile numero errori vari (in lettura) --> se supera soglia maxErroriCheck --> disconnette + /// + protected static int numErroriCheck = 0; /// /// Valore di attesa (random) dopo ogni invio x evitare congestione send... /// protected static int urlRandWait = 0; + /// + /// Stato connessione con macchina gestita + /// + protected bool _connOk = false; + + /// + /// valore booleano di check se sia in fase di COMUNICAZIONE ATTIVA con il PLC/NC + /// + protected bool adpCommAct; + + /// + /// porta x adapter (x restart) + /// + protected int adpPortNum; + + /// + /// Vettore 32 BIT valori in ingresso al filtro + /// + protected int B_input; + + /// + /// Vettore 32 BIT valori in uscita dal filtro + /// + protected int B_output; + + /// + /// Vettore 32 BIT valori precedenti + /// + protected int B_previous = -1; + + /// + /// Cod grupo IOB x creazione PODL al volo + /// + protected string CodGruppoIob = "ND-00"; + + /// + /// Num errori check alive + /// + protected int currAliveErrors = 0; + + /// + /// Dizionario valori impostati x produzione + /// + protected Dictionary currProdData = new Dictionary(); + + /// + /// num corrente errori read PLC + /// + protected int currReadErrors = 0; + + /// + /// num errori send + /// + protected int currSendErrors = 0; + + /// + /// Tempo di attesa in minuti x lettura contapezzi standard (da .ini / OptPar) + /// + protected double delayMinReadPzCount = 0; + + /// + /// Fattore di demoltiplicazione dei DynData x ridurre campionamento + /// + protected int demFactDynData = 1; + /// /// Disabilitazione gestione ODL (lettura e gestione) /// protected bool disableOdl = false; + /// + /// Boolean x indicare contapezzi disabilitato forzatamente da IOB + /// + protected bool disablePzCountByIob = false; + + /// + /// Determina se sia prevista gestione PODL (creazione/avvio/chiusura) come Soitaab + /// + protected bool EnabelPodlManFull = false; + + /// + /// Abilita riscrittura memoria se trova differenze lettura/richiesti + /// + protected bool ENABLE_MEM_REWRITE = true; + + /// + /// Abilitazione restart (da opt par...) + /// + protected bool enableCliRestart = false; + + /// + /// Boolean x indicare contapezzi abilitato a livello di conf applicazione + /// + protected bool enablePzCountByApp = true; + + /// + /// Abilitazione invio dataitem + /// + protected bool enableSendDataItem = true; + + /// + /// Abilitazione gestione slow data + /// + protected bool enableSlowData = false; + //protected static Logger lg = LogManager.GetCurrentClassLogger(); /// /// Abilitazione invio conf macchine @@ -417,30 +377,226 @@ namespace IOB_UT_NEXT.Iob protected bool enabSendMachineConf = true; /// - /// Ultimo LOG registrazione avvio (x ridurre log notturni...) + /// dizionario (opzionale) xz decodifica file da importare /// - protected DateTime lastLogStartup = DateTime.Today.AddHours(-1); + protected Dictionary FileDecod = new Dictionary(); + + /// + /// DeadBand x riduzione dati FluxLog (se 0 non gestita) + /// + protected double fluxLogRedDeadBand = 0; + + /// + /// Determina se sia gestita riduzione dati FluxLog + /// + protected bool fluxLogReduce = false; + + /// + /// Dizionario dei valori FluxLog ultimi verificati x veto + /// + protected Dictionary fluxLogReduceLast = new Dictionary(); + + /// + /// Dizionario dei valori FluxLog ultimi tipo STRING verificati x veto + /// + protected Dictionary fluxLogReduceLastString = new Dictionary(); + + /// + /// Dizionario dei veto send x ogni variabile quando non variata + /// + protected Dictionary fluxLogReduceVeto = new Dictionary(); + + /// + /// Finestra in minuti x invio dati FluxLog quando invariati + /// + protected int fluxLogResendPeriod = 60; + + /// + /// indica che è richiesto forzatamente reset contapezzi + /// + protected bool forcePzReset = false; + + /// + /// DEADBAND globale se impostata (es x gestire variazioni minime valori FluxLog da inviare...) + /// + protected float GLOBAL_DBAND = 0; + + /// + /// Determina se siano gestite le ricette + /// + protected bool hasRecipe = false; + + /// + /// Array dei contatori x segnali blinking + /// + protected int[] i_counters; + + /// + /// Indica impianto IN SETUP (fino a quando SMETTE di esserlo...) + /// + protected bool inSetup = false; + + /// + /// Dizionario ULTIMI valori impostati x produzione + /// + protected Dictionary lastProdData = new Dictionary(); + + /// + /// Dizionario ultimi valori (string) delle TSS + /// + protected Dictionary LastTSS = new Dictionary(); + + /// + /// Dizionario ultimi valori (string) delle TSS + /// + protected Dictionary LastTSSSend = new Dictionary(); + + /// + /// Dizionario ultimi valori (double) delle TSVC + /// + protected Dictionary LastTSVC = new Dictionary(); + + /// + /// Separatore linea (tipicamente x commenti) + /// + protected string lineSep = "--------------------------"; + + /// + /// Elenco parametri calcolati da inviare alla macchina (es ricetta con traduzione, RAMA/TFT) + /// + protected List list2Write = new List(); + + /// + /// Elenco delle eventuali condizioni di veto conditions attive + /// + protected List ListVetoCond = new List(); + + /// + /// Num massimo di errori in funzionalità check alive + /// + protected int maxAliveErrors = utils.CRI("maxAliveErrors"); + + /// + /// Soglia massima errori prima della disconnessione automatica in check + /// + protected int maxErroriCheck = utils.CRI("maxErroriCheck"); + + /// + /// Quantità massima per singola ricetta (per determinare num ricette da inviare) + /// + protected int maxQtyPerFile = 0; /// /// Dimensione coda di ping x valutazione /// protected int maxQueuePing = 11; + /// + /// Num massimo di errori di rete read (dal PLC) + /// + protected int maxReadErrors = utils.CRI("maxReadErrors"); + + /// + /// Periodo massimo (in sec) per letture dati in mancanza di eventi di aggiornamento + /// + protected int MaxSecReload = 120; + + /// + /// Num massimodi errori di rete send al server + /// + protected int maxSendErrors = utils.CRI("maxSendErrors"); + + /// + /// Numero massimo di tentativi x test ping preliminare + /// + protected int maxTryPing = 1; + + protected string mem2trace = ""; + /// /// Tempo minimo ammissibile di risposta (es x errori ModBus che risponde troppo in fretta) in millisec /// protected int minRespTimeMs = 5; + protected int minVetoSendDataItem = 60; + + /// + /// indica se serva refresh parametri e quindi PLC... + /// + protected bool needRefresh = true; + + /// + /// Indica se usare la parte numerica di un articolo come codice INT + /// + protected bool numArtCharTrim = false; + + /// + /// Timeout x ping al server + /// + protected int pingServerMsTimeout = utils.CRI("PingMsTimeout"); + + + /// + /// Ritardo minimo x invio contapezzi + /// + protected int pzCountDelay = 2500; + /// /// Indica se resettare allarmi all'avvio e inviare il reset appena parte adapter /// protected bool resetAlarmOnStart = false; + /// + /// Periodo di campionamento x refresh info + /// + protected int samplePeriod = 1000; + + /// + /// MsSample Period base x campionamenti tpo OCP-UA + /// + protected int samplePeriodBase = 600; + + /// + /// Dizionario di VC da trattare come TimeSeries (con conf decodificata + processing successivo...) + /// + protected Dictionary TSVC_Data = new Dictionary(); + + /// + /// Indica se usare archivio locale ricette vs scarico http/REST + /// + protected bool useLocalRecipe = true; + + /// + /// Dizionario di VARIABILI da trattare come eventi (da inviare quando cambiano oppure a + /// scadenza periodo...) + /// + protected Dictionary VarArray = new Dictionary(); + + /// + /// Dizionario dei divieti di invio x ogni counter gestito + /// + protected Dictionary VetoCounterSend = new Dictionary(); + /// /// Veto per registrazione completa log di startup (minuti) /// protected int vetoLogStartupDuration = 60; + /// + /// Durata in secondi del divieto accodamento segnali IN alla fase di startup + /// + protected int vetoQueueIn = 10; + + /// + /// Periodo di veto prima di invio nuova conferma dei valori write correnti, default ogni 5 min + /// + protected double vetoSendWriteUpsert = 1; + + /// + /// Periodo wathdog di default (2 sec se non specificato) + /// + protected int watchDogPeriod = 2; + #endregion Protected Fields #region Protected Properties @@ -459,6 +615,88 @@ namespace IOB_UT_NEXT.Iob #region Protected Methods + /// + /// Decodifica file MAP (caso .bit) + /// + /// + /// + /// indirizzo Byte: indirizzo di partenza memoria + /// dimensione singolo slot in byte + /// indirizzo bit: numero riga x calcolo indice bit + /// + protected static otherData decodeBitData(string linea, char separator, int ByteNum, int memSize, int BitNum) + { + if (linea != null) + { + string[] valori = linea.Split(separator); + int shift = 0; + try + { + shift = Convert.ToInt32(valori[0]) - 1; + } + catch + { } + int resto = 0; + Math.DivRem(BitNum, 8, out resto); + string memAddr = string.Format("{0}.{1}", ByteNum + shift * memSize, resto); + return new otherData(valori[0], memAddr, valori[1].Trim(), valori[2].Trim()); + } + else + { + return null; + } + } + + /// + /// Decodifica file MAP generico + /// + /// + /// + /// + /// + /// + /// + protected static otherData decodeOtherData(string linea, char separator, string memPre, int baseAddr, int memSize) + { + if (linea != null) + { + string[] valori = linea.Split(separator); + int shift = 0; + try + { + shift = Convert.ToInt32(valori[0]) - 1; + } + catch + { } + string memAddr = string.Format("{0}{1}", memPre, baseAddr + shift * memSize); + return new otherData(valori[0], memAddr, valori[1].Trim(), valori[2].Trim()); + } + else + { + return null; + } + } + + protected static long GetObjectSize(object genObj, bool isSerializable) + { + long result = 0; + if (isSerializable) + { + using (var stream = new MemoryStream()) + { + var formatter = new BinaryFormatter(); + formatter.Serialize(stream, genObj); + result = stream.Length; + } + } + else + { + string rawVal = System.Text.Json.JsonSerializer.Serialize(genObj, options); + result = rawVal.Length; + } + return result; + } + /// /// Verifica se ci sia veto log attivo e gestisce casistiche /// @@ -556,6 +794,21 @@ namespace IOB_UT_NEXT.Iob /// protected string GetWeekStatsKey() => redisMan.redHash($"IOB:Status:{IOBConfFull.General.FilenameIOB}:WeekStats"); + /// + /// Deserializza una stringa JSON in un oggetto. + /// + protected T JsonDeserialize(string json) => DataSerializer.Deserialize(json); + + /// + /// Serializza un oggetto in formato JSON. + /// + protected string JsonSerialize(T obj) => DataSerializer.Serialize(obj); + + /// + /// Serializza un oggetto in formato JSON con opzioni serializzazione. + /// + protected string JsonSerialize(T obj, Formatting reqFormat) => DataSerializer.Serialize(obj, reqFormat); + /// /// Imposta un valore nel hash dello stato dell'IOB. /// @@ -573,19 +826,28 @@ namespace IOB_UT_NEXT.Iob string codIob = IOBConfFull.General.FilenameIOB; bool useRedis = IOBConfFull.General.EnabRedisQue; // valutare se portare di nuovo in redis... - QueueIN = new DataQueue(codIob, "QueueIN", useRedis, redisMan); - QueueSrvResp = new DataQueue(codIob, "QueueServResp", useRedis, redisMan); + QHelp.QueueIN = new DataQueue(codIob, "QueueIN", useRedis, redisMan); + QHelp.QueueSrvResp = new DataQueue(codIob, "QueueServResp", useRedis, redisMan); // fix a NON redis - QueueAlarm = new DataQueue(codIob, "QueueAlarm", false, redisMan); - QueueFLog = new DataQueue(codIob, "QueueFLog", false, redisMan); - //QueueFLog = new DataQueue(codIob, "QueueFLog", useRedis, redisMan); - QueueMessages = new DataQueue(codIob, "QueueMessages", false, redisMan); - QueuePing = new DataQueue(codIob, "QueuePing", false, redisMan); - QueueRawTransf = new DataQueue(codIob, "QueueRawTransf", false, redisMan); - QueueSrvReq = new DataQueue(codIob, "QueueServReq", false, redisMan); - QueueULog = new DataQueue(codIob, "QueueULog", false, redisMan); + QHelp.QueueAlarm = new DataQueue(codIob, "QueueAlarm", false, redisMan); + QHelp.QueueFLog = new DataQueue(codIob, "QueueFLog", false, redisMan); + QHelp.QueueMessages = new DataQueue(codIob, "QueueMessages", false, redisMan); + QHelp.QueuePing = new DataQueue(codIob, "QueuePing", false, redisMan); + QHelp.QueueRawTransf = new DataQueue(codIob, "QueueRawTransf", false, redisMan); + QHelp.QueueSrvReq = new DataQueue(codIob, "QueueServReq", false, redisMan); + QHelp.QueueULog = new DataQueue(codIob, "QueueULog", false, redisMan); } + /// + /// Deserializza una stringa XML in un oggetto. + /// + protected T XmlDeserialize(string xml) => XmlDataSerializer.Deserialize(xml); + + /// + /// Serializza un oggetto in formato XML. + /// + protected string XmlSerialize(T obj) => XmlDataSerializer.Serialize(obj); + #endregion Protected Methods #region Private Fields @@ -595,7 +857,11 @@ namespace IOB_UT_NEXT.Iob /// private static readonly Logger lg = LogManager.GetCurrentClassLogger(); - private static Random rnd = new Random(); + private static readonly JsonSerializerOptions options = new JsonSerializerOptions + { + ReferenceHandler = ReferenceHandler.IgnoreCycles, + WriteIndented = false // Optional: set to true for pretty-printing + }; #endregion Private Fields } diff --git a/IOB-UT-NEXT/Iob/DateTimeHelper.cs b/IOB-UT-NEXT/Iob/DateTimeHelper.cs new file mode 100644 index 00000000..3c8964cc --- /dev/null +++ b/IOB-UT-NEXT/Iob/DateTimeHelper.cs @@ -0,0 +1,186 @@ +using IOB_UT_NEXT.Services.Files; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace IOB_UT_NEXT.Iob +{ + /// + /// Classe helper di tutti gli oggetti DateTime impiegati + /// ...da validare... + /// + public class DateTimeHelper + { + #region Public Fields + + /// + /// DataOra ultimo avvio adapter x watchdog + /// + public DateTime adpStartRun; + + /// + /// Data/ora ultimo avvio adapter + /// + public DateTime AvvioAdp = DateTime.Now; + + /// + /// Veto x esecuzione task AutoDossier + /// + public DateTime dtVetoAutoDossier = DateTime.Now; + + /// + /// Veto x lettura contapezzi (in caso di autoODL con attesa reset ad esempio...) + /// + public DateTime dtVetoReadPzCount = DateTime.Now; + + /// + /// DataOra x veto all'invio dataItem + /// + public DateTime dtVetoSenDataItem = DateTime.Now; + + /// + /// Veto x esecuzione Task2Exe troppo frequenti + /// + public DateTime dtVetoTask2Exe = DateTime.Now; + + /// + /// indica che è richiesto forzatamente reset contapezzi + /// + public DateTime forcePzResetUntil = DateTime.Now.AddMinutes(-1); + + /// + /// ultimo tentativo connessione... + /// + public DateTime lastConnectTry; + + /// + /// dataOra ultima verifica CNC disconnesso... + /// + public DateTime lastDisconnCheck; + + /// + /// ultimo controllo decremento eventi + /// + public DateTime lastEvCheck; + + /// + /// Data/ora ultima volta che IOB è stato dichiarato online + /// + public DateTime lastIobOnline = DateTime.Now.AddHours(-1); + + /// + /// Ultima verifica status IOB x forzare display status SRV + /// + public DateTime lastIobStatusDisplUpdate = DateTime.Now; + + /// + /// Ultimo LOG registrazione avvio (x ridurre log notturni...) + /// + public DateTime lastLogStartup = DateTime.Today.AddHours(-1); + + /// + /// dataOra ultimo log periodico... + /// + public DateTime lastPeriodicLog; + + /// + /// dataOra ultimo PING inviato verso il PLC... + /// + public DateTime lastPING = DateTime.Now.AddHours(-1); + + /// + /// Ultimo controllo ping x evitare ping flood... + /// + public DateTime lastPingConn = DateTime.Now.AddMinutes(-10); + + /// + /// Ultimo invio contapezzi (x invio delayed) + /// + public DateTime lastPzCountSend; + + /// + /// DataOra ultima lettura da PLC + /// + public DateTime lastReadPLC; + + /// + /// Ultimo istante in cui sono stati ridotti dati simulazione duration + /// + public DateTime lastRedDuration; + + /// + /// DateTime Ultimo valore simulazione generato + /// + public DateTime lastSim; + + /// + /// Ultimo istante in cui sono stati generati dati di simulazione + /// + public DateTime lastSimData; + + /// + /// Ultima registrazione warning x ODL mancante (x scrivere solo ogni 15 secondi) + /// + public DateTime lastWarnODL; + + /// + /// dataOra ultimo segnale inviato al SERVER... + /// + public DateTime lastWatchDog; + + /// + /// dataOra ultimo segnale inviato a macchina/PLC... + /// + public DateTime lastWatchDogPLC = DateTime.Now; + + /// + /// ultima data-ora invio parametri write x ribadire status + /// + public DateTime lastWriteParamsUpsert = DateTime.Now; + + /// + /// DataOra avvio Programma x check avvio + /// + public DateTime prgStarted = DateTime.Now; + + /// + /// Data/ora ultimo spegnimento adapter + /// + public DateTime StopAdp = DateTime.Now; + + /// + /// Indicazione VETO check status IOB x evitare loop troppo stretti... + /// + public DateTime VetoCheckIOB = DateTime.Now.AddDays(-1); + + /// + /// Indicazione VETO check sync ricette x evitare loop troppo stretti... + /// + public DateTime VetoCheckSyncRecipe = DateTime.Now.AddHours(-1); + + /// + /// Imposta veto lettura dati (es per DB a 2 sec) + /// + public DateTime vetoDataRead = DateTime.Now; + + /// + /// Imposta veto SYNC dati (es per DB 2 DB a 10 sec) + /// + public DateTime vetoDataSync = DateTime.Now; + + /// + /// Veto specifico per la gestione (svuotamento) coda contapezzi (es in fase di attrezzaggio e reset lenti) + /// Tipicamente impostato a DelayReadPzCountSetup dopo attrezzaggio... + /// + public DateTime vetoQueuePzCount = DateTime.Now; + + /// + /// Imposta veto chiamata split (durante chiamata, per 60 sec) + /// + public DateTime vetoSplit = DateTime.Now.AddMinutes(1); + + #endregion Public Fields + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Iob/QueueHelper.cs b/IOB-UT-NEXT/Iob/QueueHelper.cs new file mode 100644 index 00000000..75d47ebc --- /dev/null +++ b/IOB-UT-NEXT/Iob/QueueHelper.cs @@ -0,0 +1,66 @@ +using IOB_UT_NEXT.Services.Data; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace IOB_UT_NEXT.Iob +{ + /// + /// Classe helper di tutti gli oggetti Queue impiegati + /// ...da validare... + /// + public class QueueHelper + { + #region Public Fields + + /// + /// Coda valori ALLARMI ove gestiti... + /// + public DataQueue QueueAlarm; + + /// + /// Oggetto della coda degli elementi letti di tipo FluxLog (e non ancora trasmessi) + /// + public DataQueue QueueFLog; + + /// + /// Oggetto della coda degli elementi letti (e non ancora trasmessi) + /// + public DataQueue QueueIN; + + /// + /// Coda valori MESSAGGI/EVENTI (da non sottocampionare come samples)... + /// + public DataQueue QueueMessages; + + /// + /// Coda degli esiti di ping x calcolo stato macchina + /// + public DataQueue QueuePing; + + /// + /// Oggetto della coda degli elementi di tipo RawTransf (e non ancora trasmessi) + /// NB: sono salvati serializzati come stringhe + /// + public DataQueue QueueRawTransf; + + /// + /// Coda delle richieste dal server (Task2Exe) + /// + public DataQueue QueueSrvReq; + + /// + /// Coda delle risposte al server (Task2Exe) + /// + public DataQueue QueueSrvResp; + + /// + /// Coda valori LOG UTENTE (da non sottocampionare come samples)... + /// + public DataQueue QueueULog; + + #endregion Public Fields + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Iob/Services/CommunicationService.cs b/IOB-UT-NEXT/Iob/Services/CommunicationService.cs new file mode 100644 index 00000000..3ba5e6b9 --- /dev/null +++ b/IOB-UT-NEXT/Iob/Services/CommunicationService.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Services.Cache; +using IOB_UT_NEXT.Services.Networking; +using NLog; + +namespace IOB_UT_NEXT.Services.Networking +{ + /// + /// Orchestratore delle comunicazioni. + /// Coordina HttpService e RedisIobCache per eseguire workflow di business. + /// Riduce la profondità dello stack in Generic.cs. + /// + public class CommunicationService + { + #region Public Constructors + + public CommunicationService(IobConfTree config, RedisIobCache redisMan) + { + _config = config; + _redisMan = redisMan; + } + + #endregion Public Constructors + + #region Public Methods + + /// + /// Esegue una chiamata HTTP e salva il risultato direttamente su Redis (Workflow orchestrato). + /// + public async Task CallAndSaveToRedisAsync(string url, string redisKey) + { + try + { + string result = await HttpService.CallUrlAsync(url); + if (!string.IsNullOrEmpty(result)) + { + _redisMan.setRSV(redisKey, result); + } + return result; + } + catch (Exception ex) + { + logger.Error(ex, $"Error in CallAndSaveToRedisAsync: URL={url}, Key={redisKey}"); + throw; + } + } + + /// + /// Recupera dati da una URL e li deserializza (Workflow orchestrato). + /// + public async Task GetAndDeserializeAsync(string url) + { + string raw = await HttpService.CallUrlAsync(url); + return IOB_UT_NEXT.Services.Data.DataSerializer.Deserialize(raw); + } + + /// + /// Esegue una chiamata POST e salva il payload/risposta (Workflow orchestrato). + /// + public async Task PostAndStoreAsync(string url, string payload, string redisKey) + { + try + { + string response = await Task.Run(() => HttpService.CallUrlPost(url, payload)); + if (!string.IsNullOrEmpty(response)) + { + _redisMan.setRSV(redisKey, response); + } + return response; + } + catch (Exception ex) + { + logger.Error(ex, $"Error in PostAndStoreAsync: URL={url}, Key={redisKey}"); + throw; + } + } + + #endregion Public Methods + + #region Private Fields + + private static readonly Logger logger = LogManager.GetCurrentClassLogger(); + private readonly IobConfTree _config; + private readonly RedisIobCache _redisMan; + + #endregion Private Fields + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Iob/Services/Machine/MachineCommunicationService.cs b/IOB-UT-NEXT/Iob/Services/Machine/MachineCommunicationService.cs new file mode 100644 index 00000000..e04741d1 --- /dev/null +++ b/IOB-UT-NEXT/Iob/Services/Machine/MachineCommunicationService.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Config.Mem; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Core; +using NLog; + +namespace IOB_UT_NEXT.Services.Machine +{ + /// + /// MachineCommunicationService: Orchestratore per il dominio MACCHINA (_machineThread). + /// Gestisce l'interazione con tcMan e memMap, incapsulando la logica di "maneggio" dei dati. + /// + public class MachineCommunicationService + { + #region Public Constructors + + public MachineCommunicationService(IobConfTree config, TCMan tcMan, plcMemMapExt memMap) + { + _config = config ?? throw new ArgumentNullException(nameof(config)); + _tcMan = tcMan ?? throw new ArgumentNullException(nameof(tcMan)); + _memMap = memMap ?? throw new ArgumentNullException(nameof(memMap)); + } + + #endregion Public Constructors + + #region Public Methods + + /// + /// Ottiene la media dei tempi ciclo (TC) rilevati. + /// + public double GetAverageTc() => _tcMan.avgTC > 0 ? _tcMan.avgTC : 1.0; + + /// + /// Ottiene l'ultimo timestamp osservato dal PLC. + /// + public DateTime GetLastObservedData() => _tcMan.lastObservedData; + + /// + /// Gestione conteggio pezzi attuale dal driver della macchina. + /// + /// + public int ContapezziIOB + { + get => _tcMan.pzCountIOB; + set => _tcMan.pzCountIOB=value; + } + + /// + /// Gestione conteggio pezzi attuale dal PLC. + /// + public int ContapezziPLC + { + get => _tcMan.pzCountPLC; + set => _tcMan.pzCountPLC = value; + } + + /// + /// Abilitazione allarme in caso di TC superiore a soglia + /// + public bool AlarmDelayTC + { + get => _tcMan.alarmDelayTC; + } + + /// + /// Legge un valore dalla memoria condivisa (MemMap) ricevuta dal PLC. + /// + public string ReadFromMemMap(string key) + { + if (_memMap != null && _memMap.mMapRead != null && _memMap.mMapRead.ContainsKey(key)) + { + return _memMap.mMapRead[key].value; + } + return null; + } + + /// + /// Scrive un valore nella memoria condivisa (MemMap) per l'invio al PLC. + /// + public bool WriteToMemMap(string key, string value) + { + bool fatto = false; + if (_memMap != null && _memMap.mMapWrite != null) + { + if (_memMap.mMapWrite.ContainsKey(key)) + { + _memMap.mMapWrite[key].value = value; + fatto = true; + logger.Debug($"[MachineComm] MemMap Write: {key} = {value}"); + } + else + { + logger.Warn($"[MachineComm] Attempted write to non-existent MemMap key: {key}"); + } + } + return fatto; + } + + #endregion Public Methods + + #region Private Fields + + private static readonly Logger logger = LogManager.GetCurrentClassLogger(); + private readonly IobConfTree _config; + private readonly plcMemMapExt _memMap; + private readonly TCMan _tcMan; + + #endregion Private Fields + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Iob/Services/Networking/ServerCommunicationService.cs b/IOB-UT-NEXT/Iob/Services/Networking/ServerCommunicationService.cs new file mode 100644 index 00000000..200fc251 --- /dev/null +++ b/IOB-UT-NEXT/Iob/Services/Networking/ServerCommunicationService.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Services.Cache; +using IOB_UT_NEXT.Services.Networking; +using IOB_UT_NEXT.Services.Data; +using NLog; + +namespace IOB_UT_NEXT.Services.Networking +{ + /// + /// ServerCommunicationService: Orchestratore per i task del dominio SERVER (_workerTask). + /// Gestisce il coordinamento tra chiamate HTTP, persistenza Redis e code di comunicazione. + /// + public class ServerCommunicationService + { + #region Public Constructors + + public ServerCommunicationService(IobConfTree config, RedisIobCache redisMan) + { + _config = config ?? throw new ArgumentNullException(nameof(config)); + _redisMan = redisMan ?? throw new ArgumentNullException(nameof(redisMan)); + } + + #endregion Public Constructors + + #region Public Methods + + /// + /// Esegue una chiamata HTTP GET e deserializza il risultato. + /// + public async Task GetAndDeserializeAsync(string url) + { + try + { + string response = await HttpService.CallUrlAsync(url); + return JsonDeserialize(response); + } + catch (Exception ex) + { + logger.Error(ex, $"[ServerComm] Error in GetAndDeserializeAsync | URL: {url}"); + throw; + } + } + + /// + /// Recupera dati da un URL e li salva su Redis. + /// Workflow: HTTP GET -> Redis Set. + /// + public async Task GetAndPersistAsync(string url, string redisKey) + { + try + { + string response = await HttpService.CallUrlAsync(url); + + if (!string.IsNullOrEmpty(response) && !string.IsNullOrEmpty(redisKey)) + { + _redisMan.setRSV(redisKey, response); + } + + return response; + } + catch (Exception ex) + { + logger.Error(ex, $"[ServerComm] Error in GetAndPersistAsync | URL: {url} | Key: {redisKey}"); + throw; + } + } + + /// + /// Esegue una chiamata HTTP POST e salva il risultato su Redis. + /// Workflow: Serialize -> HTTP POST -> Redis Set. + /// + public async Task PostAndPersistAsync(string url, T payload, string redisKey) + { + try + { + string serializedPayload = JsonSerialize(payload); + logger.Debug($"[ServerComm] POST to {url} | Payload: {serializedPayload}"); + + string response = await HttpService.CallUrlAsync(url, serializedPayload); + + if (!string.IsNullOrEmpty(response) && !string.IsNullOrEmpty(redisKey)) + { + _redisMan.setRSV(redisKey, response); + logger.Info($"[ServerComm] Data persisted to Redis: {redisKey}"); + } + + return response; + } + catch (Exception ex) + { + logger.Error(ex, $"[ServerComm] Error in PostAndPersistAsync | URL: {url} | Key: {redisKey}"); + throw; + } + } + + #endregion Public Methods + + #region Private Fields + + private static readonly Logger logger = LogManager.GetCurrentClassLogger(); + private readonly IobConfTree _config; + private readonly RedisIobCache _redisMan; + + #endregion Private Fields + + #region Private Methods + + private T JsonDeserialize(string json) => IOB_UT_NEXT.Services.Data.DataSerializer.Deserialize(json); + + // Helper per mantenere la compatibilità con la logica di serializzazione esistente + private string JsonSerialize(T obj) => IOB_UT_NEXT.Services.Data.DataSerializer.Serialize(obj); + + #endregion Private Methods + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Objects.cs b/IOB-UT-NEXT/Objects.cs deleted file mode 100644 index e58db839..00000000 --- a/IOB-UT-NEXT/Objects.cs +++ /dev/null @@ -1,699 +0,0 @@ -using MapoSDK; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace IOB_UT_NEXT -{ - /// - /// informazioni di produzione - /// - public struct prodData - { - #region Public Fields - - public int AccTime; - public bool EmrStop; - public string FuncMode; - public string MessageCode; - public string MessageText; - public string Operator; - - public int Power; - public bool Status; - - #endregion Public Fields - } - - /// - /// Gestione Endianness - /// - public static class Endian - { - #region Public Methods - - /// - /// Scambia MSB/LSB per 16bit - /// - /// - /// - public static UInt16 SwapUInt16(UInt16 inValue) - { - return (UInt16)(((inValue & 0xff00) >> 8) | - ((inValue & 0x00ff) << 8)); - } - - /// - /// Scambia MSB/LSB per 32bit - /// - /// - /// - public static UInt32 SwapUInt32(UInt32 inValue) - { - return ((inValue & 0xff000000) >> 24) | - ((inValue & 0x00ff0000) >> 8) | - ((inValue & 0x0000ff00) << 8) | - ((inValue & 0x000000ff) << 24); - } - - #endregion Public Methods - } - - /// - /// Elenco task di tipo FTP - /// - public class FtpTaskList - { - public List ListTask { get; set; } = new List(); - } - - /// - /// Elenco task generici - /// - public class GenTaskList - { - public List ListTask { get; set; } = new List(); - } - - /// - /// Gestione dati di timing - /// - public static class TimingData - { - #region Public Fields - - public static List results = new List(); - - #endregion Public Fields - - #region Public Methods - - /// - /// aggiorno vettore aggiungendo risultato - /// - /// Codice chiamante - /// Codice da registrare (univoco con chiamante) - /// Tempo esecuzione in ticks - public static void addResult(string caller, string codice, long ticks) - { - if (results.Count == 0) - { - results.Add(new TimeRec(caller, codice, ticks)); - } - int indice = -1; - for (int i = 0; i < results.Count; i++) - { - // se il codice è quello cercato... - if (results[i].codCall == codice && results[i].classCall == caller) - { - indice = i; - } - } - // se c'è aggiorno... - if (indice >= 0) - { - results[indice].numCall++; - results[indice].totMsec = results[indice].totMsec.Add(new TimeSpan(ticks)); - } - // altrimenti aggiungo... - else - { - results.Add(new TimeRec(caller, codice, ticks)); - } - } - - /// - /// Resetta i dati registrati (ad avvio adapter...) - /// - public static void resetData() - { - results = new List(); - } - - #endregion Public Methods - } - - /// - /// Cache a tempo valori INT - /// - public class CachedInt - { - #region Public Properties - - public DateTime ValidUntil { get; set; } = DateTime.Now; - public int Value { get; set; } = 0; - - #endregion Public Properties - } - - /// - /// Cache a tempo valori String - /// - public class CachedString - { - #region Public Properties - - public DateTime ValidUntil { get; set; } = DateTime.Now; - public string Value { get; set; } = ""; - - #endregion Public Properties - } - - /// - /// Classe conf x item DynData - /// - public class DynDataItem - { - #region Public Fields - - /// - /// DataOra scadenza invio forzato - /// - public DateTime DTScad = DateTime.Now; - - #endregion Public Fields - - #region Public Properties - - /// - /// Valore effettivo da salvare - /// - public string actVal { get; set; } = ""; - - public string func { get; set; } = ""; - public string key { get; set; } = ""; - public int maxVal { get; set; } - public int minVal { get; set; } - public string name { get; set; } = ""; - public int sPeriod { get; set; } = 60; - public string unit { get; set; } = ""; - public string val { get; set; } = ""; - - #endregion Public Properties - } - - /// - /// Configurazione per Eventi/Variabili - /// - public class EVData - { - #region Public Fields - - /// - /// DataOra scadenza invio forzato - /// - public DateTime DTScad = DateTime.Now; - - #endregion Public Fields - - #region Public Properties - - /// - /// Unità di misura - /// - public string UM { get; set; } = "num"; - - /// - /// Valore salvato - /// - public string Val { get; set; } = ""; - - #endregion Public Properties - } - - /// - /// Elenco oggetti del monitoraggio (DynData, Status) per WPS - /// - public class MonitoredItemsConf - { - #region Public Properties - - public List DynData { get; set; } - public srvData SrvData { get; set; } - public List Status { get; set; } - - #endregion Public Properties - } - - /// - /// Classe che contiene tutte le NUOVE informazioni da aggiornare sulla form - /// - public class newDisplayData - { - #region Public Properties - - /// - /// Oggetto COUTNER generico (pezzi, portata...) - /// - public int counter { get; set; } = -9999; - - /// - /// Bitmap attuale segnali letti - /// - public string currBitmap { get; set; } = ""; - - /// - /// Verifica se contenga valori (NON default/empty) - /// - public bool hasData - { - get - { - bool answ = false; - // true se qualcosa NON E' come default - if (!string.IsNullOrWhiteSpace(newInData) || !string.IsNullOrWhiteSpace(newSignalData) || !string.IsNullOrWhiteSpace(newFLogData) || !string.IsNullOrWhiteSpace(newUrlCallData) || !string.IsNullOrWhiteSpace(newLiveLogData) || counter > -9999 || !string.IsNullOrWhiteSpace(currBitmap) || semIn != Semaforo.ND || semOut != Semaforo.ND) - { - answ = true; - } - return answ; - } - } - - /// - /// Dati tipo FluxLog - /// - public string newFLogData { get; set; } = ""; - - /// - /// Dati tipo IN (RAW) - /// - public string newInData { get; set; } = ""; - - /// - /// Dati tipo LiveLog - /// - public string newLiveLogData { get; set; } = ""; - - /// - /// Dati tipo Signal - /// - public string newSignalData { get; set; } = ""; - - /// - /// Dati tipo UrlCall - /// - public string newUrlCallData { get; set; } = ""; - - /// - /// Stato semaforo IN verso PLC - /// - public Semaforo semIn { get; set; } = Semaforo.ND; - - /// - /// Stato semaforo OUT verso MES - /// - public Semaforo semOut { get; set; } = Semaforo.ND; - - #endregion Public Properties - } - - /// - /// Dato generico (per decodifica) - /// - public class otherData - { - #region Public Fields - - public string codNum; - public string dataType; - public string memAddr; - public string varName; - - #endregion Public Fields - - #region Public Constructors - - public otherData() - { - codNum = ""; - memAddr = ""; - varName = ""; - dataType = ""; - } - - public otherData(string _codNum, string _memAddr, string _varName, string _dataType) - { - codNum = _codNum; - memAddr = _memAddr; - varName = _varName; - dataType = _dataType; - } - - #endregion Public Constructors - } - - /// - /// Classe gestione valori campionati su periodo - /// - public class sampleVect - { - #region Public Constructors - - /// - /// Inizializzo l'oggetto - /// - public sampleVect() - { - // init valori default... - windSize = baseUtils.CRI("countWindSize") > 0 ? baseUtils.CRI("countWindSize") : 60; - lTime = new List(); - lVal = new List(); - } - - #endregion Public Constructors - - #region Public Properties - - /// - /// Calcola il valore mediano... - /// - public double vcMedian - { - get - { - double answ = 0; - // restituisce la mediana SE valida, altrimenti null... - if (numElem > 2 && flWindSize > windSize) - { - try - { - // calcolo mediana! - //answ = Statistics.Median(lVal.ToArray()); - - // rif: https://blogs.msmvps.com/deborahk/linq-mean-median-and-mode/ - var sortedNumbers = lVal.OrderBy(n => n); - int numCount = lVal.Count; - int indice50 = lVal.Count / 2; - if ((numCount % 2) == 0) - { - answ = ((sortedNumbers.ElementAt(indice50) + sortedNumbers.ElementAt(indice50 - 1)) / 2); - } - else - { - answ = sortedNumbers.ElementAt(indice50); - } - } - catch - { } - } - return answ; - } - } - - /// - /// Verifica se la vc sia valida (ovvero almeno 2 valori e intervallo > window richiesta) - /// - public bool vcValid - { - get - { - return (flWindSize > windSize && numElem > 1); - } - } - - #endregion Public Properties - - #region Public Methods - - /// - /// Aggiunge un valore alla serie ed eventualmente elimina i valori superflui a garantirne - /// una finestra temporale valida - /// - /// - /// - public void addValue(DateTime tempo, int valore) - { - lTime.Add(tempo); - lVal.Add(valore); - // verifico se siano da accorciare le serie... ovvero i 2 intervalli ENTRAMBI sono - // superiori al periodo minimo (in tal caso riduco.. - while (flWindSize > windSize && slWindSize > windSize) - { - // elimino i 2 valori + vecchi - lTime.RemoveAt(0); - lVal.RemoveAt(0); - // ora ricontrollo... - } - } - - #endregion Public Methods - - #region Protected Fields - - /// - /// vettore valori temporali della serie - /// - protected List lTime; - - /// - /// vettore valori puntuali della serie - /// - protected List lVal; - - /// - /// Dimensione finestra di campionamento (secondi) - /// - protected int windSize; - - #endregion Protected Fields - - #region Protected Properties - - /// - /// Verifica ampiezza finestra valori First-Last - /// - protected double flWindSize - { - get - { - double answ = 0; - if (numElem > 1) - { - answ = lTime.Last().Subtract(lTime[0]).TotalSeconds; - } - return answ; - } - } - - /// - /// Conteggio elementi - /// - protected int numElem - { - get - { - int answ = 0; - try - { - answ = lTime.Count; - } - catch - { } - return answ; - } - } - - /// - /// Verifica ampiezza finestra valori Second-Last - /// - protected double slWindSize - { - get - { - double answ = 0; - if (numElem > 2) // altrimenti SE non ne ho almeno 3 NON posso avere secondo/ultimo... - { - answ = lTime.Last().Subtract(lTime[1]).TotalSeconds; - } - return answ; - } - } - - #endregion Protected Properties - } - - /// - /// Classe x descrivere status server MP - /// - public class ServerMpStatus - { - #region Public Properties - - /// - /// IP server - /// - public string IP { get; set; } - - /// - /// DataOra ultima comunicazione OUT (con MP Server) - /// - public DateTime lastUpdate { get; set; } = DateTime.Now.AddDays(-1); - - /// - /// Status del server - /// - public bool online { get; set; } = false; - - #endregion Public Properties - } - - /// - /// Classe conf server html - /// - public class srvData - { - #region Public Properties - - public string baseUri { get; set; } = ""; - public string driverName { get; set; } = ""; - - #endregion Public Properties - } - - /// - /// Classe conf x decodifica status - /// - public class StatusItem : DynDataItem - { - #region Public Fields - - public Dictionary codeMapping; - - #endregion Public Fields - } - - /// - /// Oggetto timing x archiviazione dati perfomances - /// - public class TimeRec - { - #region Public Fields - - /// - /// Classe chiamante della funzione (es codice univoco IOB) - /// - public string classCall; - - /// - /// Codice univoco chiamata: tipo R4 (read 4 byte), W2 (write 2 Byte) - /// - public string codCall; - - /// - /// Num chiamate totale - /// - public int numCall; - - /// - /// Totale Msec accumulati - /// - public TimeSpan totMsec; - - #endregion Public Fields - - #region Public Constructors - - /// - /// Classe record timing - /// - public TimeRec() - { - codCall = ""; - numCall = 0; - totMsec = new TimeSpan(0); - } - - /// - /// Classe record timing - /// - /// - /// - /// - public TimeRec(string caller, string codice, long nTicks) - { - classCall = caller; - codCall = codice; - numCall = 1; - totMsec = new TimeSpan(nTicks); - } - - #endregion Public Constructors - - #region Public Properties - - /// - /// Tempo medio chiamata - /// - public double avgMsec - { - get - { - return totMsec.TotalMilliseconds / numCall; - } - } - - #endregion Public Properties - } - - /// - /// Configurazione per Variabili Casuali - /// - public class VCData - { - #region Public Fields - - /// - /// Array dati per calcolo - /// - public List dataArray; - - /// - /// DataOra inizio periodo di elaborazione - /// - public DateTime DTStart; - - #endregion Public Fields - - #region Public Properties - - /// - /// Tipologia di funzione da applicare - /// - public VC_func Funzione { get; set; } = VC_func.POINT; - - /// - /// Periodo di riferimento - /// - public int Period { get; set; } = 60; - - /// - /// UM parametro, impiegato anche x conversione (es epoch --> datetime) - /// - public string UM { get; set; } = ""; - - #endregion Public Properties - } - - /// - /// Generico evento log - /// - public class GenLogRow - { - public DateTime dtRif { get; set; } = DateTime.Now; - - public string valString { get; set; } = ""; - } - - - /// - /// Informazioni generiche su batch produzione rilevati - /// - public class ProdBatchData - { - public DateTime dtStart { get; set; } = DateTime.Now; - public DateTime? dtEnd { get; set; } = null; - - public string codArt { get; set; } = ""; - public int numPz { get; set; } = 0; - } -} \ No newline at end of file diff --git a/IOB-UT-NEXT/Objects/CachedInt.cs b/IOB-UT-NEXT/Objects/CachedInt.cs new file mode 100644 index 00000000..3226847d --- /dev/null +++ b/IOB-UT-NEXT/Objects/CachedInt.cs @@ -0,0 +1,17 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Cache a tempo valori INT + /// + public class CachedInt + { + #region Public Properties + + public DateTime ValidUntil { get; set; } = DateTime.Now; + public int Value { get; set; } = 0; + + #endregion Public Properties + } +} diff --git a/IOB-UT-NEXT/Objects/CachedString.cs b/IOB-UT-NEXT/Objects/CachedString.cs new file mode 100644 index 00000000..944834b9 --- /dev/null +++ b/IOB-UT-NEXT/Objects/CachedString.cs @@ -0,0 +1,18 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Cache a tempo valori String + /// + public class CachedString + { + #region Public Properties + + public DateTime ValidUntil { get; set; } = DateTime.Now; + public string Value { get; set; } = ""; + + #endregion Public Properties + } + +} diff --git a/IOB-UT-NEXT/Objects/DynDataItem.cs b/IOB-UT-NEXT/Objects/DynDataItem.cs new file mode 100644 index 00000000..724f3d75 --- /dev/null +++ b/IOB-UT-NEXT/Objects/DynDataItem.cs @@ -0,0 +1,37 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Classe conf x item DynData + /// + public class DynDataItem + { + #region Public Fields + + /// + /// DataOra scadenza invio forzato + /// + public DateTime DTScad = DateTime.Now; + + #endregion Public Fields + + #region Public Properties + + /// + /// Valore effettivo da salvare + /// + public string actVal { get; set; } = ""; + + public string func { get; set; } = ""; + public string key { get; set; } = ""; + public int maxVal { get; set; } + public int minVal { get; set; } + public string name { get; set; } = ""; + public int sPeriod { get; set; } = 60; + public string unit { get; set; } = ""; + public string val { get; set; } = ""; + + #endregion Public Properties + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Objects/EVData.cs b/IOB-UT-NEXT/Objects/EVData.cs new file mode 100644 index 00000000..92a0b7af --- /dev/null +++ b/IOB-UT-NEXT/Objects/EVData.cs @@ -0,0 +1,33 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Configurazione per Eventi/Variabili + /// + public class EVData + { + #region Public Fields + + /// + /// DataOra scadenza invio forzato + /// + public DateTime DTScad = DateTime.Now; + + #endregion Public Fields + + #region Public Properties + + /// + /// Unità di misura + /// + public string UM { get; set; } = "num"; + + /// + /// Valore salvato + /// + public string Val { get; set; } = ""; + + #endregion Public Properties + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Objects/Endian.cs b/IOB-UT-NEXT/Objects/Endian.cs new file mode 100644 index 00000000..4fe43678 --- /dev/null +++ b/IOB-UT-NEXT/Objects/Endian.cs @@ -0,0 +1,38 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Gestione Endianness + /// + public static class Endian + { + #region Public Methods + + /// + /// Scambia MSB/LSB per 16bit + /// + /// + /// + public static UInt16 SwapUInt16(UInt16 inValue) + { + return (UInt16)(((inValue & 0xff00) >> 8) | + ((inValue & 0x00ff) << 8)); + } + + /// + /// Scambia MSB/LSB per 32bit + /// + /// + /// + public static UInt32 SwapUInt32(UInt32 inValue) + { + return ((inValue & 0xff000000) >> 24) | + ((inValue & 0x00ff0000) >> 8) | + ((inValue & 0x0000ff00) << 8) | + ((inValue & 0x000000ff) << 24); + } + + #endregion Public Methods + } +} diff --git a/IOB-UT-NEXT/Objects/FtpTaskList.cs b/IOB-UT-NEXT/Objects/FtpTaskList.cs new file mode 100644 index 00000000..27522c59 --- /dev/null +++ b/IOB-UT-NEXT/Objects/FtpTaskList.cs @@ -0,0 +1,13 @@ +using IOB_UT_NEXT.Config.Special; +using System.Collections.Generic; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Elenco task di tipo FTP + /// + public class FtpTaskList + { + public List ListTask { get; set; } = new List(); + } +} diff --git a/IOB-UT-NEXT/Objects/GenLogRow.cs b/IOB-UT-NEXT/Objects/GenLogRow.cs new file mode 100644 index 00000000..0635cb0f --- /dev/null +++ b/IOB-UT-NEXT/Objects/GenLogRow.cs @@ -0,0 +1,15 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Generico evento log + /// + public class GenLogRow + { + public DateTime dtRif { get; set; } = DateTime.Now; + + public string valString { get; set; } = ""; + } + +} diff --git a/IOB-UT-NEXT/Objects/GenTaskList.cs b/IOB-UT-NEXT/Objects/GenTaskList.cs new file mode 100644 index 00000000..37739f36 --- /dev/null +++ b/IOB-UT-NEXT/Objects/GenTaskList.cs @@ -0,0 +1,13 @@ +using IOB_UT_NEXT.Config; +using System.Collections.Generic; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Elenco task generici + /// + public class GenTaskList + { + public List ListTask { get; set; } = new List(); + } +} diff --git a/IOB-UT-NEXT/Objects/MonitoredItemsConf.cs b/IOB-UT-NEXT/Objects/MonitoredItemsConf.cs new file mode 100644 index 00000000..8cfd7717 --- /dev/null +++ b/IOB-UT-NEXT/Objects/MonitoredItemsConf.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Elenco oggetti del monitoraggio (DynData, Status) per WPS + /// + public class MonitoredItemsConf + { + #region Public Properties + + public List DynData { get; set; } + public srvData SrvData { get; set; } + public List Status { get; set; } + + #endregion Public Properties + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Objects/ProdBatchData.cs b/IOB-UT-NEXT/Objects/ProdBatchData.cs new file mode 100644 index 00000000..a888b7c9 --- /dev/null +++ b/IOB-UT-NEXT/Objects/ProdBatchData.cs @@ -0,0 +1,16 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Informazioni generiche su batch produzione rilevati + /// + public class ProdBatchData + { + public DateTime dtStart { get; set; } = DateTime.Now; + public DateTime? dtEnd { get; set; } = null; + + public string codArt { get; set; } = ""; + public int numPz { get; set; } = 0; + } +} diff --git a/IOB-UT-NEXT/Objects/ServerMpStatus.cs b/IOB-UT-NEXT/Objects/ServerMpStatus.cs new file mode 100644 index 00000000..0c32d47e --- /dev/null +++ b/IOB-UT-NEXT/Objects/ServerMpStatus.cs @@ -0,0 +1,29 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Classe x descrivere status server MP + /// + public class ServerMpStatus + { + #region Public Properties + + /// + /// IP server + /// + public string IP { get; set; } + + /// + /// DataOra ultima comunicazione OUT (con MP Server) + /// + public DateTime lastUpdate { get; set; } = DateTime.Now.AddDays(-1); + + /// + /// Status del server + /// + public bool online { get; set; } = false; + + #endregion Public Properties + } +} diff --git a/IOB-UT-NEXT/Objects/StatusItem.cs b/IOB-UT-NEXT/Objects/StatusItem.cs new file mode 100644 index 00000000..05227535 --- /dev/null +++ b/IOB-UT-NEXT/Objects/StatusItem.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Classe conf x decodifica status + /// + public class StatusItem : DynDataItem + { + #region Public Fields + + public Dictionary codeMapping; + + #endregion Public Fields + } + +} diff --git a/IOB-UT-NEXT/Objects/TimeRec.cs b/IOB-UT-NEXT/Objects/TimeRec.cs new file mode 100644 index 00000000..b736111d --- /dev/null +++ b/IOB-UT-NEXT/Objects/TimeRec.cs @@ -0,0 +1,78 @@ +using System; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Oggetto timing x archiviazione dati perfomances + /// + public class TimeRec + { + #region Public Fields + + /// + /// Classe chiamante della funzione (es codice univoco IOB) + /// + public string classCall; + + /// + /// Codice univoco chiamata: tipo R4 (read 4 byte), W2 (write 2 Byte) + /// + public string codCall; + + /// + /// Num chiamate totale + /// + public int numCall; + + /// + /// Totale Msec accumulati + /// + public TimeSpan totMsec; + + #endregion Public Fields + + #region Public Constructors + + /// + /// Classe record timing + /// + public TimeRec() + { + codCall = ""; + numCall = 0; + totMsec = new TimeSpan(0); + } + + /// + /// Classe record timing + /// + /// + /// + /// + public TimeRec(string caller, string codice, long nTicks) + { + classCall = caller; + codCall = codice; + numCall = 1; + totMsec = new TimeSpan(nTicks); + } + + #endregion Public Constructors + + #region Public Properties + + /// + /// Tempo medio chiamata + /// + public double avgMsec + { + get + { + return totMsec.TotalMilliseconds / numCall; + } + } + + #endregion Public Properties + } + +} diff --git a/IOB-UT-NEXT/Objects/TimingData.cs b/IOB-UT-NEXT/Objects/TimingData.cs new file mode 100644 index 00000000..ac8c612b --- /dev/null +++ b/IOB-UT-NEXT/Objects/TimingData.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Gestione dati di timing + /// + public static class TimingData + { + #region Public Fields + + public static List results = new List(); + + #endregion Public Fields + + #region Public Methods + + /// + /// aggiorno vettore aggiungendo risultato + /// + /// Codice chiamante + /// Codice da registrare (univoco con chiamante) + /// Tempo esecuzione in ticks + public static void addResult(string caller, string codice, long ticks) + { + if (results.Count == 0) + { + results.Add(new TimeRec(caller, codice, ticks)); + } + int indice = -1; + for (int i = 0; i < results.Count; i++) + { + // se il codice è quello cercato... + if (results[i].codCall == codice && results[i].classCall == caller) + { + indice = i; + } + } + // se c'è aggiorno... + if (indice >= 0) + { + results[indice].numCall++; + results[indice].totMsec = results[indice].totMsec.Add(new TimeSpan(ticks)); + } + // altrimenti aggiungo... + else + { + results.Add(new TimeRec(caller, codice, ticks)); + } + } + + /// + /// Resetta i dati registrati (ad avvio adapter...) + /// + public static void resetData() + { + results = new List(); + } + + #endregion Public Methods + } +} diff --git a/IOB-UT-NEXT/Objects/VCData.cs b/IOB-UT-NEXT/Objects/VCData.cs new file mode 100644 index 00000000..1ef149a8 --- /dev/null +++ b/IOB-UT-NEXT/Objects/VCData.cs @@ -0,0 +1,45 @@ +using MapoSDK; +using System; +using System.Collections.Generic; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Configurazione per Variabili Casuali + /// + public class VCData + { + #region Public Fields + + /// + /// Array dati per calcolo + /// + public List dataArray; + + /// + /// DataOra inizio periodo di elaborazione + /// + public DateTime DTStart; + + #endregion Public Fields + + #region Public Properties + + /// + /// Tipologia di funzione da applicare + /// + public VC_func Funzione { get; set; } = VC_func.POINT; + + /// + /// Periodo di riferimento + /// + public int Period { get; set; } = 60; + + /// + /// UM parametro, impiegato anche x conversione (es epoch --> datetime) + /// + public string UM { get; set; } = ""; + + #endregion Public Properties + } +} diff --git a/IOB-UT-NEXT/Objects/newDisplayData.cs b/IOB-UT-NEXT/Objects/newDisplayData.cs new file mode 100644 index 00000000..92abd646 --- /dev/null +++ b/IOB-UT-NEXT/Objects/newDisplayData.cs @@ -0,0 +1,76 @@ +using MapoSDK; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Classe che contiene tutte le NUOVE informazioni da aggiornare sulla form + /// + public class newDisplayData + { + #region Public Properties + + /// + /// Oggetto COUTNER generico (pezzi, portata...) + /// + public int counter { get; set; } = -9999; + + /// + /// Bitmap attuale segnali letti + /// + public string currBitmap { get; set; } = ""; + + /// + /// Verifica se contenga valori (NON default/empty) + /// + public bool hasData + { + get + { + bool answ = false; + // true se qualcosa NON E' come default + if (!string.IsNullOrWhiteSpace(newInData) || !string.IsNullOrWhiteSpace(newSignalData) || !string.IsNullOrWhiteSpace(newFLogData) || !string.IsNullOrWhiteSpace(newUrlCallData) || !string.IsNullOrWhiteSpace(newLiveLogData) || counter > -9999 || !string.IsNullOrWhiteSpace(currBitmap) || semIn != Semaforo.ND || semOut != Semaforo.ND) + { + answ = true; + } + return answ; + } + } + + /// + /// Dati tipo FluxLog + /// + public string newFLogData { get; set; } = ""; + + /// + /// Dati tipo IN (RAW) + /// + public string newInData { get; set; } = ""; + + /// + /// Dati tipo LiveLog + /// + public string newLiveLogData { get; set; } = ""; + + /// + /// Dati tipo Signal + /// + public string newSignalData { get; set; } = ""; + + /// + /// Dati tipo UrlCall + /// + public string newUrlCallData { get; set; } = ""; + + /// + /// Stato semaforo IN verso PLC + /// + public Semaforo semIn { get; set; } = Semaforo.ND; + + /// + /// Stato semaforo OUT verso MES + /// + public Semaforo semOut { get; set; } = Semaforo.ND; + + #endregion Public Properties + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/Objects/otherData.cs b/IOB-UT-NEXT/Objects/otherData.cs new file mode 100644 index 00000000..cbd21e13 --- /dev/null +++ b/IOB-UT-NEXT/Objects/otherData.cs @@ -0,0 +1,37 @@ +namespace IOB_UT_NEXT.Objects +{ + /// + /// Dato generico (per decodifica) + /// + public class otherData + { + #region Public Fields + + public string codNum; + public string dataType; + public string memAddr; + public string varName; + + #endregion Public Fields + + #region Public Constructors + + public otherData() + { + codNum = ""; + memAddr = ""; + varName = ""; + dataType = ""; + } + + public otherData(string _codNum, string _memAddr, string _varName, string _dataType) + { + codNum = _codNum; + memAddr = _memAddr; + varName = _varName; + dataType = _dataType; + } + + #endregion Public Constructors + } +} diff --git a/IOB-UT-NEXT/Objects/prodData.cs b/IOB-UT-NEXT/Objects/prodData.cs new file mode 100644 index 00000000..12923ac5 --- /dev/null +++ b/IOB-UT-NEXT/Objects/prodData.cs @@ -0,0 +1,22 @@ +namespace IOB_UT_NEXT.Objects +{ + /// + /// informazioni di produzione + /// + public struct prodData + { + #region Public Fields + + public int AccTime; + public bool EmrStop; + public string FuncMode; + public string MessageCode; + public string MessageText; + public string Operator; + + public int Power; + public bool Status; + + #endregion Public Fields + } +} diff --git a/IOB-UT-NEXT/Objects/sampleVect.cs b/IOB-UT-NEXT/Objects/sampleVect.cs new file mode 100644 index 00000000..f5924b54 --- /dev/null +++ b/IOB-UT-NEXT/Objects/sampleVect.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace IOB_UT_NEXT.Objects +{ + /// + /// Classe gestione valori campionati su periodo + /// + public class sampleVect + { + #region Public Constructors + + /// + /// Inizializzo l'oggetto + /// + public sampleVect() + { + // init valori default... + windSize = baseUtils.CRI("countWindSize") > 0 ? baseUtils.CRI("countWindSize") : 60; + lTime = new List(); + lVal = new List(); + } + + #endregion Public Constructors + + #region Public Properties + + /// + /// Calcola il valore mediano... + /// + public double vcMedian + { + get + { + double answ = 0; + // restituisce la mediana SE valida, altrimenti null... + if (numElem > 2 && flWindSize > windSize) + { + try + { + // calcolo mediana! + //answ = Statistics.Median(lVal.ToArray()); + + // rif: https://blogs.msmvps.com/deborahk/linq-mean-median-and-mode/ + var sortedNumbers = lVal.OrderBy(n => n); + int numCount = lVal.Count; + int indice50 = lVal.Count / 2; + if ((numCount % 2) == 0) + { + answ = ((sortedNumbers.ElementAt(indice50) + sortedNumbers.ElementAt(indice50 - 1)) / 2); + } + else + { + answ = sortedNumbers.ElementAt(indice50); + } + } + catch + { } + } + return answ; + } + } + + /// + /// Verifica se la vc sia valida (ovvero almeno 2 valori e intervallo > window richiesta) + /// + public bool vcValid + { + get + { + return (flWindSize > windSize && numElem > 1); + } + } + + #endregion Public Properties + + #region Public Methods + + /// + /// Aggiunge un valore alla serie ed eventualmente elimina i valori superflui a garantirne + /// una finestra temporale valida + /// + /// + /// + public void addValue(DateTime tempo, int valore) + { + lTime.Add(tempo); + lVal.Add(valore); + // verifico se siano da accorciare le serie... ovvero i 2 intervalli ENTRAMBI sono + // superiori al periodo minimo (in tal caso riduco.. + while (flWindSize > windSize && slWindSize > windSize) + { + // elimino i 2 valori + vecchi + lTime.RemoveAt(0); + lVal.RemoveAt(0); + // ora ricontrollo... + } + } + + #endregion Public Methods + + #region Protected Fields + + /// + /// vettore valori temporali della serie + /// + protected List lTime; + + /// + /// vettore valori puntuali della serie + /// + protected List lVal; + + /// + /// Dimensione finestra di campionamento (secondi) + /// + protected int windSize; + + #endregion Protected Fields + + #region Protected Properties + + /// + /// Verifica ampiezza finestra valori First-Last + /// + protected double flWindSize + { + get + { + double answ = 0; + if (numElem > 1) + { + answ = lTime.Last().Subtract(lTime[0]).TotalSeconds; + } + return answ; + } + } + + /// + /// Conteggio elementi + /// + protected int numElem + { + get + { + int answ = 0; + try + { + answ = lTime.Count; + } + catch + { } + return answ; + } + } + + /// + /// Verifica ampiezza finestra valori Second-Last + /// + protected double slWindSize + { + get + { + double answ = 0; + if (numElem > 2) // altrimenti SE non ne ho almeno 3 NON posso avere secondo/ultimo... + { + answ = lTime.Last().Subtract(lTime[1]).TotalSeconds; + } + return answ; + } + } + + #endregion Protected Properties + } + +} diff --git a/IOB-UT-NEXT/Objects/srvData.cs b/IOB-UT-NEXT/Objects/srvData.cs new file mode 100644 index 00000000..01c417fe --- /dev/null +++ b/IOB-UT-NEXT/Objects/srvData.cs @@ -0,0 +1,16 @@ +namespace IOB_UT_NEXT.Objects +{ + /// + /// Classe conf server html + /// + public class srvData + { + #region Public Properties + + public string baseUri { get; set; } = ""; + public string driverName { get; set; } = ""; + + #endregion Public Properties + } + +} diff --git a/IOB-UT-NEXT/RedisIobCache.cs b/IOB-UT-NEXT/Services/Cache/RedisIobCache.cs similarity index 99% rename from IOB-UT-NEXT/RedisIobCache.cs rename to IOB-UT-NEXT/Services/Cache/RedisIobCache.cs index 884d02f0..f0abbb2d 100644 --- a/IOB-UT-NEXT/RedisIobCache.cs +++ b/IOB-UT-NEXT/Services/Cache/RedisIobCache.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; +using IOB_UT_NEXT.Objects; +using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Collections.Generic; @@ -6,7 +7,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Cache { public class RedisIobCache { diff --git a/IOB-UT-NEXT/BinaryUtils.cs b/IOB-UT-NEXT/Services/Core/BinaryUtils.cs similarity index 98% rename from IOB-UT-NEXT/BinaryUtils.cs rename to IOB-UT-NEXT/Services/Core/BinaryUtils.cs index d7edbc87..6a55bca0 100644 --- a/IOB-UT-NEXT/BinaryUtils.cs +++ b/IOB-UT-NEXT/Services/Core/BinaryUtils.cs @@ -3,7 +3,7 @@ using System.Globalization; using System.Linq; using System.Numerics; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Core { public class BinaryUtils : IFormatProvider, ICustomFormatter { diff --git a/IOB-UT-NEXT/BitConditionCheck.cs b/IOB-UT-NEXT/Services/Core/BitConditionCheck.cs similarity index 98% rename from IOB-UT-NEXT/BitConditionCheck.cs rename to IOB-UT-NEXT/Services/Core/BitConditionCheck.cs index 07224b3f..688e34f8 100644 --- a/IOB-UT-NEXT/BitConditionCheck.cs +++ b/IOB-UT-NEXT/Services/Core/BitConditionCheck.cs @@ -1,4 +1,4 @@ -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Core { public class BitConditionCheck { diff --git a/IOB-UT-NEXT/ByteDataConverter.cs b/IOB-UT-NEXT/Services/Core/ByteDataConverter.cs similarity index 97% rename from IOB-UT-NEXT/ByteDataConverter.cs rename to IOB-UT-NEXT/Services/Core/ByteDataConverter.cs index 047dff32..dc13295f 100644 --- a/IOB-UT-NEXT/ByteDataConverter.cs +++ b/IOB-UT-NEXT/Services/Core/ByteDataConverter.cs @@ -1,4 +1,5 @@ -namespace IOB_UT_NEXT + +namespace IOB_UT_NEXT.Services.Core { public class ByteDataConverter { diff --git a/IOB-UT-NEXT/JobTask2Exe.cs b/IOB-UT-NEXT/Services/Core/JobTask2Exe.cs similarity index 90% rename from IOB-UT-NEXT/JobTask2Exe.cs rename to IOB-UT-NEXT/Services/Core/JobTask2Exe.cs index c43adffc..e9343c44 100644 --- a/IOB-UT-NEXT/JobTask2Exe.cs +++ b/IOB-UT-NEXT/Services/Core/JobTask2Exe.cs @@ -1,12 +1,7 @@ using Newtonsoft.Json; -using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Core { /// /// Classe per gestione Job Task2Exe x una macchina diff --git a/IOB-UT-NEXT/Services/Core/SingleThreadTaskScheduler.cs b/IOB-UT-NEXT/Services/Core/SingleThreadTaskScheduler.cs new file mode 100644 index 00000000..ac4b7528 --- /dev/null +++ b/IOB-UT-NEXT/Services/Core/SingleThreadTaskScheduler.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Collections.Concurrent; +using System.Threading; +using System.Threading.Tasks; + +namespace IOB_UT_NEXT.Services.Core +{ + public class SingleThreadTaskScheduler : TaskScheduler, IDisposable + { + #region Public Constructors + + public SingleThreadTaskScheduler(string threadName) + { + var tcs = new TaskCompletionSource(); + _thread = new Thread(() => + { + // Creiamo il contesto di sincronizzazione personalizzato + SyncContext = new SingleThreadSynchronizationContext(this); + SynchronizationContext.SetSynchronizationContext(SyncContext); + tcs.SetResult(true); + + foreach (var task in _tasks.GetConsumingEnumerable()) + { + base.TryExecuteTask(task); + } + }) + { IsBackground = true, Name = threadName }; + _thread.Start(); + tcs.Task.Wait(); // Aspetta che il thread sia pronto col suo contesto + } + + #endregion Public Constructors + + #region Public Properties + + public override int MaximumConcurrencyLevel => 1; + public SynchronizationContext SyncContext { get; private set; } + + #endregion Public Properties + + #region Public Methods + + public void Dispose() => _tasks.CompleteAdding(); + + #endregion Public Methods + + #region Protected Methods + + protected override IEnumerable GetScheduledTasks() => _tasks; + + protected override void QueueTask(Task task) => _tasks.Add(task); + + protected override bool TryExecuteTaskInline(Task task, bool prev) + => Thread.CurrentThread == _thread && base.TryExecuteTask(task); + + #endregion Protected Methods + + #region Private Fields + + private readonly BlockingCollection _tasks = new BlockingCollection(); + private readonly Thread _thread; + + #endregion Private Fields + + #region Private Classes + + private class SingleThreadSynchronizationContext : SynchronizationContext + { + #region Public Constructors + + public SingleThreadSynchronizationContext(SingleThreadTaskScheduler sch) => _sch = sch; + + #endregion Public Constructors + + #region Public Methods + + public override void Post(SendOrPostCallback d, object state) + => Task.Factory.StartNew(() => d(state), CancellationToken.None, TaskCreationOptions.None, _sch); + + #endregion Public Methods + + #region Private Fields + + private readonly SingleThreadTaskScheduler _sch; + + #endregion Private Fields + } + + #endregion Private Classes + } +} \ No newline at end of file diff --git a/IOB-UT-NEXT/TCMan.cs b/IOB-UT-NEXT/Services/Core/TCMan.cs similarity index 99% rename from IOB-UT-NEXT/TCMan.cs rename to IOB-UT-NEXT/Services/Core/TCMan.cs index f7af3916..86c6ee48 100644 --- a/IOB-UT-NEXT/TCMan.cs +++ b/IOB-UT-NEXT/Services/Core/TCMan.cs @@ -1,6 +1,6 @@ using System; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Core { /// /// TCiclo management class diff --git a/IOB-UT-NEXT/TimerMan.cs b/IOB-UT-NEXT/Services/Core/TimerMan.cs similarity index 94% rename from IOB-UT-NEXT/TimerMan.cs rename to IOB-UT-NEXT/Services/Core/TimerMan.cs index d03f3244..813d72e7 100644 --- a/IOB-UT-NEXT/TimerMan.cs +++ b/IOB-UT-NEXT/Services/Core/TimerMan.cs @@ -1,10 +1,7 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Core { /// /// Classe di gestione info Timer per esecuzione ordinata processi secondo priorità diff --git a/IOB-UT-NEXT/DataExport.cs b/IOB-UT-NEXT/Services/Data/DataExport.cs similarity index 99% rename from IOB-UT-NEXT/DataExport.cs rename to IOB-UT-NEXT/Services/Data/DataExport.cs index c422549b..951b4060 100644 --- a/IOB-UT-NEXT/DataExport.cs +++ b/IOB-UT-NEXT/Services/Data/DataExport.cs @@ -5,7 +5,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Data { public class DataExport { diff --git a/IOB-UT-NEXT/DataQueue.cs b/IOB-UT-NEXT/Services/Data/DataQueue.cs similarity index 97% rename from IOB-UT-NEXT/DataQueue.cs rename to IOB-UT-NEXT/Services/Data/DataQueue.cs index 4b8ecd32..02db92cb 100644 --- a/IOB-UT-NEXT/DataQueue.cs +++ b/IOB-UT-NEXT/Services/Data/DataQueue.cs @@ -1,10 +1,11 @@ -using StackExchange.Redis; +using IOB_UT_NEXT.Services.Cache; +using StackExchange.Redis; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Data { /// /// Classe gestione code, a seconda della conf come LIST redis o come concurrent queue in memoria diff --git a/IOB-UT-NEXT/Iob/Services/DataSerializer.cs b/IOB-UT-NEXT/Services/Data/DataSerializer.cs similarity index 78% rename from IOB-UT-NEXT/Iob/Services/DataSerializer.cs rename to IOB-UT-NEXT/Services/Data/DataSerializer.cs index d0bdad59..ea32800b 100644 --- a/IOB-UT-NEXT/Iob/Services/DataSerializer.cs +++ b/IOB-UT-NEXT/Services/Data/DataSerializer.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; -namespace IOB_UT_NEXT.Iob.Services +namespace IOB_UT_NEXT.Services.Data { /// /// Gestisce tutte le operazioni di serializzazione e deserializzazione dei dati. @@ -23,6 +23,17 @@ namespace IOB_UT_NEXT.Iob.Services }); } + /// + /// Serializza un oggetto in una stringa JSON utilizzando la cultura invariante. + /// + public static string Serialize(T obj, Formatting reqFormat) + { + if (obj == null) return null; + // Utilizzo di CultureInfo.InvariantCulture per garantire la coerenza dei formati (es. decimali) + return JsonConvert.SerializeObject(obj, reqFormat); + } + + /// /// Deserializza una stringa JSON in un oggetto del tipo specificato. /// diff --git a/IOB-UT-NEXT/Iob/Services/XmlDataSerializer.cs b/IOB-UT-NEXT/Services/Data/XmlDataSerializer.cs similarity index 98% rename from IOB-UT-NEXT/Iob/Services/XmlDataSerializer.cs rename to IOB-UT-NEXT/Services/Data/XmlDataSerializer.cs index e05e339c..edb84ff9 100644 --- a/IOB-UT-NEXT/Iob/Services/XmlDataSerializer.cs +++ b/IOB-UT-NEXT/Services/Data/XmlDataSerializer.cs @@ -2,7 +2,7 @@ using System; using System.IO; using System.Xml.Serialization; -namespace IOB_UT_NEXT.Iob.Services +namespace IOB_UT_NEXT.Services.Data { /// /// Gestisce le operazioni di serializzazione e deserializzazione in formato XML. diff --git a/IOB-UT-NEXT/fileMover.cs b/IOB-UT-NEXT/Services/Files/FileMover.cs similarity index 99% rename from IOB-UT-NEXT/fileMover.cs rename to IOB-UT-NEXT/Services/Files/FileMover.cs index 0506555c..a453f66d 100644 --- a/IOB-UT-NEXT/fileMover.cs +++ b/IOB-UT-NEXT/Services/Files/FileMover.cs @@ -6,19 +6,19 @@ using System.Linq; using System.Net; using System.Reflection; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Files { /// /// Accesso in lettura e scrittura al filesystem per gestione files upload e download /// - public class fileMover + public class FileMover { #region Public Fields /// - /// versione statica (singleton) del'oggetto fileMover + /// versione statica (singleton) del'oggetto FileMover /// - public static fileMover obj = new fileMover(); + public static FileMover obj = new FileMover(); /// /// oggetto WebClient @@ -34,7 +34,7 @@ namespace IOB_UT_NEXT /// /// /// non serve +... x retrocompatibilit�... - public fileMover(string _path, string _log) + public FileMover(string _path, string _log) { setDirs(_path); WebCli = new WebClient(); @@ -43,7 +43,7 @@ namespace IOB_UT_NEXT /// /// metodo di avvio empty /// - public fileMover() + public FileMover() { WebCli = new WebClient(); } diff --git a/IOB-UT-NEXT/FileProcMan.cs b/IOB-UT-NEXT/Services/Files/FileProcMan.cs similarity index 99% rename from IOB-UT-NEXT/FileProcMan.cs rename to IOB-UT-NEXT/Services/Files/FileProcMan.cs index cc6bd0f2..c4a73ac7 100644 --- a/IOB-UT-NEXT/FileProcMan.cs +++ b/IOB-UT-NEXT/Services/Files/FileProcMan.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; using System.IO; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Files { public class FileProcMan { diff --git a/IOB-UT-NEXT/utils.cs b/IOB-UT-NEXT/Services/Files/utils.cs similarity index 69% rename from IOB-UT-NEXT/utils.cs rename to IOB-UT-NEXT/Services/Files/utils.cs index cc7bd526..ed5756ad 100644 --- a/IOB-UT-NEXT/utils.cs +++ b/IOB-UT-NEXT/Services/Files/utils.cs @@ -1,9 +1,9 @@ -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Networking; using System; using System.IO; using System.Linq; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Files { public class utils : IOB_UT_NEXT.baseUtils { @@ -12,50 +12,32 @@ namespace IOB_UT_NEXT /// /// folder archiviazione dati configurazione (DATA\CONF) /// - public static string confDir - { - get => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("dataConfPath")); - } + public static string confDir => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("dataConfPath")); /// /// folder archiviazione dati storici giornalieri (DATA\DAT) /// - public static string dataDatDir - { - get => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("dataDatPath")); - } + public static string dataDatDir => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("dataDatPath")); /// /// folder archiviazione dati (DATA) /// - public static string dataDir - { - get => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("dataPath")); - } + public static string dataDir => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("dataPath")); /// /// File icona default /// - public static string defIconFilePath - { - get => Path.Combine(utils.resxDir, "SteamWare.ico"); - } + public static string defIconFilePath => Path.Combine(utils.resxDir, "SteamWare.ico"); /// /// File configurazione default x MAIN /// - public static string mainConfFilePath - { - get=> Path.Combine(utils.confDir, utils.CRS("mainConfFile")); - } + public static string mainConfFilePath => Path.Combine(utils.confDir, utils.CRS("mainConfFile")); /// /// folder archiviazione dati configurazione (DATA\CONF) /// - public static string resxDir - { - get => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("resxPath")); - } + public static string resxDir => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CRS("resxPath")); #endregion Public Properties diff --git a/IOB-UT-NEXT/CallMetricsCollector.cs b/IOB-UT-NEXT/Services/Monitoring/CallMetricsCollector.cs similarity index 99% rename from IOB-UT-NEXT/CallMetricsCollector.cs rename to IOB-UT-NEXT/Services/Monitoring/CallMetricsCollector.cs index 6b5891e1..e161cf5f 100644 --- a/IOB-UT-NEXT/CallMetricsCollector.cs +++ b/IOB-UT-NEXT/Services/Monitoring/CallMetricsCollector.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Monitoring { public static class CallMetricsCollector { diff --git a/IOB-UT-NEXT/Iob/Services/HttpService.cs b/IOB-UT-NEXT/Services/Networking/HttpService.cs similarity index 99% rename from IOB-UT-NEXT/Iob/Services/HttpService.cs rename to IOB-UT-NEXT/Services/Networking/HttpService.cs index 9a2e5ab0..91a2e01a 100644 --- a/IOB-UT-NEXT/Iob/Services/HttpService.cs +++ b/IOB-UT-NEXT/Services/Networking/HttpService.cs @@ -7,7 +7,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -namespace IOB_UT_NEXT.Iob.Services +namespace IOB_UT_NEXT.Services.Networking { /// /// Servizio dedicato alla gestione delle chiamate HTTP. diff --git a/IOB-UT-NEXT/Iob/Services/NetService.cs b/IOB-UT-NEXT/Services/Networking/NetService.cs similarity index 98% rename from IOB-UT-NEXT/Iob/Services/NetService.cs rename to IOB-UT-NEXT/Services/Networking/NetService.cs index 3ef5415c..dc2c71b7 100644 --- a/IOB-UT-NEXT/Iob/Services/NetService.cs +++ b/IOB-UT-NEXT/Services/Networking/NetService.cs @@ -6,7 +6,7 @@ using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; -namespace IOB_UT_NEXT.Iob.Services +namespace IOB_UT_NEXT.Services.Networking { public class NetService { diff --git a/IOB-UT-NEXT/Eurom63.cs b/IOB-UT-NEXT/Services/Protocols/Eurom63.cs similarity index 98% rename from IOB-UT-NEXT/Eurom63.cs rename to IOB-UT-NEXT/Services/Protocols/Eurom63.cs index 77a276c4..abe7e751 100644 --- a/IOB-UT-NEXT/Eurom63.cs +++ b/IOB-UT-NEXT/Services/Protocols/Eurom63.cs @@ -1,7 +1,8 @@ -using System; +using IOB_UT_NEXT.Objects; +using System; using System.Collections.Generic; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Protocols { /// /// Classe di helper per metodi Euromap63 tramite File Exchange diff --git a/IOB-UT-NEXT/BitUtils.cs b/IOB-UT-NEXT/Services/Utility/BitUtils.cs similarity index 80% rename from IOB-UT-NEXT/BitUtils.cs rename to IOB-UT-NEXT/Services/Utility/BitUtils.cs index 3193bdd5..ccb7ef7f 100644 --- a/IOB-UT-NEXT/BitUtils.cs +++ b/IOB-UT-NEXT/Services/Utility/BitUtils.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Utility { public class BitUtils { diff --git a/IOB-UT-NEXT/IntConditionCheck.cs b/IOB-UT-NEXT/Services/Utility/IntConditionCheck.cs similarity index 98% rename from IOB-UT-NEXT/IntConditionCheck.cs rename to IOB-UT-NEXT/Services/Utility/IntConditionCheck.cs index 3d305482..8f400fe0 100644 --- a/IOB-UT-NEXT/IntConditionCheck.cs +++ b/IOB-UT-NEXT/Services/Utility/IntConditionCheck.cs @@ -1,4 +1,4 @@ -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Utility { public class IntConditionCheck { diff --git a/IOB-UT-NEXT/MeasureUtils.cs b/IOB-UT-NEXT/Services/Utility/MeasureUtils.cs similarity index 93% rename from IOB-UT-NEXT/MeasureUtils.cs rename to IOB-UT-NEXT/Services/Utility/MeasureUtils.cs index bd7bf830..951302f3 100644 --- a/IOB-UT-NEXT/MeasureUtils.cs +++ b/IOB-UT-NEXT/Services/Utility/MeasureUtils.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Utility { public class MeasureUtils { diff --git a/IOB-UT-NEXT/TimeUtils.cs b/IOB-UT-NEXT/Services/Utility/TimeUtils.cs similarity index 90% rename from IOB-UT-NEXT/TimeUtils.cs rename to IOB-UT-NEXT/Services/Utility/TimeUtils.cs index c46e0744..509706f3 100644 --- a/IOB-UT-NEXT/TimeUtils.cs +++ b/IOB-UT-NEXT/Services/Utility/TimeUtils.cs @@ -1,6 +1,6 @@ using System; -namespace IOB_UT_NEXT +namespace IOB_UT_NEXT.Services.Utility { public class TimeUtils { diff --git a/IOB-UT-NEXT/SingleThreadTaskScheduler.cs b/IOB-UT-NEXT/SingleThreadTaskScheduler.cs deleted file mode 100644 index 7c70f915..00000000 --- a/IOB-UT-NEXT/SingleThreadTaskScheduler.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; - -public class SingleThreadTaskScheduler : TaskScheduler, IDisposable -{ - private readonly BlockingCollection _tasks = new BlockingCollection(); - private readonly Thread _thread; - public SynchronizationContext SyncContext { get; private set; } - - public SingleThreadTaskScheduler(string threadName) - { - var tcs = new TaskCompletionSource(); - _thread = new Thread(() => - { - // Creiamo il contesto di sincronizzazione personalizzato - SyncContext = new SingleThreadSynchronizationContext(this); - SynchronizationContext.SetSynchronizationContext(SyncContext); - tcs.SetResult(true); - - foreach (var task in _tasks.GetConsumingEnumerable()) - { - base.TryExecuteTask(task); - } - }) - { IsBackground = true, Name = threadName }; - _thread.Start(); - tcs.Task.Wait(); // Aspetta che il thread sia pronto col suo contesto - } - - private class SingleThreadSynchronizationContext : SynchronizationContext - { - private readonly SingleThreadTaskScheduler _sch; - public SingleThreadSynchronizationContext(SingleThreadTaskScheduler sch) => _sch = sch; - public override void Post(SendOrPostCallback d, object state) - => Task.Factory.StartNew(() => d(state), CancellationToken.None, TaskCreationOptions.None, _sch); - } - - protected override void QueueTask(Task task) => _tasks.Add(task); - protected override bool TryExecuteTaskInline(Task task, bool prev) - => Thread.CurrentThread == _thread && base.TryExecuteTask(task); - protected override IEnumerable GetScheduledTasks() => _tasks; - public override int MaximumConcurrencyLevel => 1; - public void Dispose() => _tasks.CompleteAdding(); -} \ No newline at end of file diff --git a/IOB-UT-NEXT/baseUtils.cs b/IOB-UT-NEXT/baseUtils.cs index aab1b465..eec5c16c 100644 --- a/IOB-UT-NEXT/baseUtils.cs +++ b/IOB-UT-NEXT/baseUtils.cs @@ -1,3 +1,6 @@ +using IOB_UT_NEXT.Services.Core; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Monitoring; using NLog; using RestSharp; using System; @@ -412,12 +415,12 @@ namespace IOB_UT_NEXT public static void shrinkDir(string dirPath) { // obj filemover... - fileMover.obj.setDirectory(dirPath); - float dirSizeMb = fileMover.obj.totalMb(); + FileMover.obj.setDirectory(dirPath); + float dirSizeMb = FileMover.obj.totalMb(); lg.Info("Inizio shrinkDir LOG folder: {0} Mb", dirSizeMb); // ottengo elenco files *.txt - FileInfo[] _fis = fileMover.obj.elencoFiles_FI("*.log"); + FileInfo[] _fis = FileMover.obj.elencoFiles_FI("*.log"); int numDdMax = 2; try { @@ -429,17 +432,17 @@ namespace IOB_UT_NEXT { if (_file.LastWriteTime < DateTime.Now.AddDays(-1)) // zippo files + vecchi di 2 gg... { - fileMover.obj.zippaSingoloFile(_file); + FileMover.obj.zippaSingoloFile(_file); // cancello l'originale... - fileMover.obj.eliminaFile(_file); + FileMover.obj.eliminaFile(_file); } } // inizio con eliminare file + vecchi della data indicata... int maxLogDays = CRI("maxLogDays"); - fileMover.obj.deleteOlderThan(maxLogDays); + FileMover.obj.deleteOlderThan(maxLogDays); // ora controllo SE sia superata la dim max della directory --> in tal caso cancello dal // + vecchio... - dirSizeMb = fileMover.obj.totalMb(); + dirSizeMb = FileMover.obj.totalMb(); int maxLogDirSize = CRI("maxLogDirSize"); int maxTry = 100; // controllo se serva eliminare... @@ -448,11 +451,11 @@ namespace IOB_UT_NEXT lg.Info("Continuo shrinkDir LOG folder: {0} Mb --> ELIMINAZIONE FILES", dirSizeMb); while (dirSizeMb > maxLogDirSize) { - fileMover.obj.deleteOldest(); + FileMover.obj.deleteOldest(); maxTry--; if (maxTry > 0) { - dirSizeMb = fileMover.obj.totalMb(); + dirSizeMb = FileMover.obj.totalMb(); } else { @@ -460,7 +463,7 @@ namespace IOB_UT_NEXT dirSizeMb = maxLogDirSize - 1; } } - dirSizeMb = fileMover.obj.totalMb(); + dirSizeMb = FileMover.obj.totalMb(); lg.Info("Completata shrinkDir LOG folder: {0} Mb", dirSizeMb); } } diff --git a/IOB-UT-NEXT/iobRefreshedEventArgs.cs b/IOB-UT-NEXT/iobRefreshedEventArgs.cs index 7b7b9d4a..abd513f5 100644 --- a/IOB-UT-NEXT/iobRefreshedEventArgs.cs +++ b/IOB-UT-NEXT/iobRefreshedEventArgs.cs @@ -1,4 +1,5 @@ -using System; +using IOB_UT_NEXT.Objects; +using System; namespace IOB_UT_NEXT { diff --git a/IOB-UT/baseUtils.cs b/IOB-UT/baseUtils.cs index de3206f3..3a973eef 100644 --- a/IOB-UT/baseUtils.cs +++ b/IOB-UT/baseUtils.cs @@ -53,17 +53,17 @@ namespace IOB_UT /// /// Indicazione VETO PING a server sino alla data-ora indicata /// - public static DateTime dtVetoPing = DateTime.Now; + public static DateTime DtHelp.dtVetoPing = DateTime.Now; #if false { get { - return redisMan.servStatus.dtVetoPing; + return redisMan.servStatus.DtHelp.dtVetoPing; } set { var currData = redisMan.servStatus; - currData.dtVetoPing = value; + currData.DtHelp.dtVetoPing = value; redisMan.servStatus = currData; } } diff --git a/IOB-WIN-BECKHOFF/AdapterFormNext.cs b/IOB-WIN-BECKHOFF/AdapterFormNext.cs index d3365b26..05afee65 100644 --- a/IOB-WIN-BECKHOFF/AdapterFormNext.cs +++ b/IOB-WIN-BECKHOFF/AdapterFormNext.cs @@ -21,7 +21,7 @@ namespace IOB_WIN_BECKHOFF /// /// carica IOB richiesto /// - protected override void loadIobType() + protected override async Task loadIobType() { if (IOBConfFull != null) { @@ -40,16 +40,11 @@ namespace IOB_WIN_BECKHOFF btnStart.Enabled = false; break; } - lblCncText = $"CNC: {IOBConfFull.General.IobType} [{IOBConfFull.Device.Connect.IpAddr}:{IOBConfFull.Device.Connect.Port}]"; - lblSrvUrlText = $"SRV: {IOBConfFull.MapoMesConf.IpAddr} | URL: {IOBConfFull.MapoMesConf.ApiUrl("")}"; - - // aggancio evento refresh - iobObj.eh_refreshed += IobObj_eh_refreshed; - - // carico i default values su interfaccia - setDefaults(); - - displayTaskAndLog($"Caricata conf per adapter {tipoScelto}"); + if (!await iobInitAsync()) + { + return; + } + UpdateDisplTypeIobSel(); } } } diff --git a/IOB-WIN-BECKHOFF/App.config b/IOB-WIN-BECKHOFF/App.config index d6fcfea3..f66d9734 100644 --- a/IOB-WIN-BECKHOFF/App.config +++ b/IOB-WIN-BECKHOFF/App.config @@ -1,178 +1,186 @@ - + -
+
- + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - + + + + + + + + - - - - - - - + + + + + + + - - + + - - - - + + + + - + - - - + + + - - - + + + - + - - - + + + - - + + - - - - - - - - - - + + + + + + + + + + - - - - - - + + + + + + - - - - + + + + - - - - - - - - + + + + + + + + - - + + - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + + + + + + + + + - + - + - \ No newline at end of file + diff --git a/IOB-WIN-BECKHOFF/IOB-WIN-BECKHOFF.csproj b/IOB-WIN-BECKHOFF/IOB-WIN-BECKHOFF.csproj index 31bb9319..267ec3a9 100644 --- a/IOB-WIN-BECKHOFF/IOB-WIN-BECKHOFF.csproj +++ b/IOB-WIN-BECKHOFF/IOB-WIN-BECKHOFF.csproj @@ -8,10 +8,11 @@ WinExe IOB_WIN_BECKHOFF IOB-WIN-BECKHOFF - v4.6.2 + v4.7.2 512 true true + AnyCPU @@ -33,8 +34,8 @@ 4 - - ..\packages\MapoSDK.6.14.2505.2916\lib\MapoSDK.dll + + ..\packages\MapoSDK.6.14.2509.1018\lib\MapoSDK.dll @@ -81,6 +82,7 @@ True Resources.resx + True App.config diff --git a/IOB-WIN-BECKHOFF/IobBeckhoff/Beckhoff.cs b/IOB-WIN-BECKHOFF/IobBeckhoff/Beckhoff.cs index 48a3cc61..24a19f10 100644 --- a/IOB-WIN-BECKHOFF/IobBeckhoff/Beckhoff.cs +++ b/IOB-WIN-BECKHOFF/IobBeckhoff/Beckhoff.cs @@ -1,5 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Services.Files; using System; using System.Collections.Generic; @@ -27,8 +28,8 @@ namespace IOB_WIN_BECKHOFF.IobBeckhoff // init datetime counters DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; vetoCheckStatus = adesso; // ora leggo il file di conf specifico.... diff --git a/IOB-WIN-BECKHOFF/IobBeckhoff/BeckhoffCpa.cs b/IOB-WIN-BECKHOFF/IobBeckhoff/BeckhoffCpa.cs index ecfa6750..27984431 100644 --- a/IOB-WIN-BECKHOFF/IobBeckhoff/BeckhoffCpa.cs +++ b/IOB-WIN-BECKHOFF/IobBeckhoff/BeckhoffCpa.cs @@ -1,5 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; diff --git a/IOB-WIN-BECKHOFF/Properties/Resources.Designer.cs b/IOB-WIN-BECKHOFF/Properties/Resources.Designer.cs index 0b54d965..8e53eb9b 100644 --- a/IOB-WIN-BECKHOFF/Properties/Resources.Designer.cs +++ b/IOB-WIN-BECKHOFF/Properties/Resources.Designer.cs @@ -8,10 +8,10 @@ // //------------------------------------------------------------------------------ -namespace IOB_WIN_BECKHOFF.Properties -{ - - +namespace IOB_WIN_BECKHOFF.Properties { + using System; + + /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -19,51 +19,43 @@ namespace IOB_WIN_BECKHOFF.Properties // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - + internal class Resources { + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { + internal Resources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("IOB_WIN_BECKHOFF.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { + internal static global::System.Globalization.CultureInfo Culture { + get { return resourceCulture; } - set - { + set { resourceCulture = value; } } diff --git a/IOB-WIN-BECKHOFF/Properties/Settings.Designer.cs b/IOB-WIN-BECKHOFF/Properties/Settings.Designer.cs index cad87ef8..0474e04a 100644 --- a/IOB-WIN-BECKHOFF/Properties/Settings.Designer.cs +++ b/IOB-WIN-BECKHOFF/Properties/Settings.Designer.cs @@ -8,21 +8,17 @@ // //------------------------------------------------------------------------------ -namespace IOB_WIN_BECKHOFF.Properties -{ - - +namespace IOB_WIN_BECKHOFF.Properties { + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.14.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { + + public static Settings Default { + get { return defaultInstance; } } diff --git a/IOB-WIN-BECKHOFF/packages.config b/IOB-WIN-BECKHOFF/packages.config index b435bc4f..2dcb60a9 100644 --- a/IOB-WIN-BECKHOFF/packages.config +++ b/IOB-WIN-BECKHOFF/packages.config @@ -1,14 +1,14 @@  - + - + - - + + diff --git a/IOB-WIN-FANUC/Iob/Fanuc.cs b/IOB-WIN-FANUC/Iob/Fanuc.cs index 0e1d71ed..88a488dd 100644 --- a/IOB-WIN-FANUC/Iob/Fanuc.cs +++ b/IOB-WIN-FANUC/Iob/Fanuc.cs @@ -2,7 +2,9 @@ using EgwProxy.MultiCncLib.CNC; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using NLog; using System; @@ -33,8 +35,8 @@ namespace IOB_WIN_FANUC.Iob // gestione invio ritardato contapezzi - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; int gSize = 0; int rSize = 8; int xSize = 8; @@ -1525,14 +1527,14 @@ namespace IOB_WIN_FANUC.Iob if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("FANUC: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // ora PING!!! Ping pingSender = new Ping(); IPAddress address = IPAddress.Loopback; @@ -1579,7 +1581,7 @@ namespace IOB_WIN_FANUC.Iob if (connectionOk) { checkVetoQueueIn(); - dtAvvioAdp = DateTime.Now; + DtHelp.AvvioAdp = DateTime.Now; if (adpRunning) { lgInfo("Connessione OK"); @@ -2585,10 +2587,10 @@ namespace IOB_WIN_FANUC.Iob } catch (Exception exc) { - if (DateTime.Now.Subtract(lastWarnODL).TotalSeconds > 15) + if (DateTime.Now.Subtract(DtHelp.lastWarnODL).TotalSeconds > 15) { lgError(exc, "Errore in fase di chiamata URL x ODL corrente | URL chiamato: {0}", urlGetCurrODL); - lastWarnODL = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; } } } @@ -2603,9 +2605,8 @@ namespace IOB_WIN_FANUC.Iob } // verifico NON sia vietato gestione contapezzi if (!plcPzCountValid) - //if (!plcPzCountValid || !rawInputRead) { - lgInfo($"Veto check contapezzi e ODL fino alle {dtVetoReadPzCount}"); + lgInfo($"Veto check contapezzi e ODL fino alle {DtHelp.dtVetoReadPzCount}"); } else { @@ -2614,7 +2615,7 @@ namespace IOB_WIN_FANUC.Iob { // controllo se è passato intervallo minimo tra 2 // controlli/elaborazioni x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... if (contapezziPLC != contapezziIOB) @@ -2648,17 +2649,17 @@ namespace IOB_WIN_FANUC.Iob pzCntReload(true); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC FANUC: {contapezziPLC} | contapezziIOB {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } diff --git a/IOB-WIN-FILE/IobFile/FileEurom63.cs b/IOB-WIN-FILE/IobFile/FileEurom63.cs index 283a00db..8dda8c5b 100644 --- a/IOB-WIN-FILE/IobFile/FileEurom63.cs +++ b/IOB-WIN-FILE/IobFile/FileEurom63.cs @@ -1,5 +1,8 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Protocols; using MapoSDK; using Newtonsoft.Json; using System; diff --git a/IOB-WIN-FILE/IobFile/FileGen.cs b/IOB-WIN-FILE/IobFile/FileGen.cs index 3cc15258..56ff29cf 100644 --- a/IOB-WIN-FILE/IobFile/FileGen.cs +++ b/IOB-WIN-FILE/IobFile/FileGen.cs @@ -1,5 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; using MapoSDK; using System; using System.Collections.Generic; @@ -110,41 +111,6 @@ namespace IOB_WIN_FILE.IobFile // ciclo! try { -#if false - // controllo SE il driver SIA attivo... - if (driver != null) - { - string cKey = ""; - string cVal = ""; - // IPOTESI: un UNICO oggetto decodifica status - if (monitoredItems.Status.Count == 1) - { - var item = monitoredItems.Status[0]; - // cerco elemento indicato - element = driver.FindElement(By.Id(item.val)); - cKey = element.Text; - // verifico se mancasse il mapping... - if (!item.codeMapping.ContainsKey(cKey)) - { - processUnknStatus(cKey); - } - else - { - // ora decodifico da variabile status a valore secondo impostazione "codeMapping" - cVal = item.codeMapping[cKey]; - B_input = int.Parse(cVal, System.Globalization.NumberStyles.HexNumber); - if (currDispData != null) - { - currDispData.semIn = Semaforo.SV; - } - } - } - } - else - { - lgError("Errore: driver non pronto (null)"); - } -#endif // riporto bitmap... reportRawInput(ref currDispData); } diff --git a/IOB-WIN-FILE/IobFile/IobFileSoitaab.cs b/IOB-WIN-FILE/IobFile/IobFileSoitaab.cs index 87ecc819..656bd435 100644 --- a/IOB-WIN-FILE/IobFile/IobFileSoitaab.cs +++ b/IOB-WIN-FILE/IobFile/IobFileSoitaab.cs @@ -3,6 +3,8 @@ using EgwProxy.SqlDb.DbModels; #endif using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; @@ -70,7 +72,7 @@ namespace IOB_WIN_FILE.IobFile lgError($"Eccezione in IobFileSoitaab{Environment.NewLine}{exc}"); } - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); } #endregion Public Constructors @@ -87,7 +89,7 @@ namespace IOB_WIN_FILE.IobFile DateTime adesso = DateTime.Now; // NON fa nulla... anche se non dovrebbe richiamarlo Dictionary taskDone = new Dictionary(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return taskDone; } @@ -101,7 +103,7 @@ namespace IOB_WIN_FILE.IobFile Dictionary outVal = new Dictionary(); // processo ed accodo! processFluxLogTable(adesso); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -115,10 +117,10 @@ namespace IOB_WIN_FILE.IobFile if (connectionOk) { // controllo veto checkDB - if (adesso > vetoDataRead) + if (adesso > DtHelp.vetoDataRead) { // predispongo prox veto... - vetoDataRead = adesso.AddSeconds(vetoReadFileSec); + DtHelp.vetoDataRead = adesso.AddSeconds(vetoReadFileSec); // semaforo currDispData.semIn = Semaforo.SV; // verifico SignLog e processo @@ -143,14 +145,14 @@ namespace IOB_WIN_FILE.IobFile if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("FileSoitaab: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -173,7 +175,7 @@ namespace IOB_WIN_FILE.IobFile if (adpRunning) { lgInfo($"Connessione OK alla folder {logDirPath}"); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } else @@ -452,7 +454,7 @@ namespace IOB_WIN_FILE.IobFile if (queueInEnabCurr) { // --> accodo (valore già formattato)! - QueueIN.Enqueue(currVal); + QHelp.QueueIN.Enqueue(currVal); // loggo! lgTrace(string.Format("[QUEUE-IN] {0}", currVal)); counterSigIN++; diff --git a/IOB-WIN-FORM/AdapterForm.cs b/IOB-WIN-FORM/AdapterForm.cs index 613b9706..a8a89858 100644 --- a/IOB-WIN-FORM/AdapterForm.cs +++ b/IOB-WIN-FORM/AdapterForm.cs @@ -1,7 +1,11 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; using IOB_UT_NEXT.Config.Base; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Core; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Monitoring; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using NLog; @@ -781,7 +785,7 @@ namespace IOB_WIN_FORM if (sendStartFLog) { // segnalo reboot (programma)... - iobObj.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB Adapter Started")); + iobObj.QHelp.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB Adapter Started")); } } catch (Exception exc) @@ -1744,7 +1748,7 @@ namespace IOB_WIN_FORM } else { - lgTrace($"VETO DoExecMachineTasks.queueInEnabCurr | veto attivo | {adesso:yyyy.MM.dd HH:mm:ss}"); + lgTrace($"VETO DoExecMachineTasks.QueueINEnabCurr | veto attivo | {adesso:yyyy.MM.dd HH:mm:ss}"); iobObj.checkVetoQueueIn(); } } @@ -1805,7 +1809,7 @@ namespace IOB_WIN_FORM } else { - lgTrace($"VETO DoExecServerTasksAsync.queueInEnabCurr | veto attivo | {adesso:yyyy.MM.dd HH:mm:ss}"); + lgTrace($"VETO DoExecServerTasksAsync.QueueINEnabCurr | veto attivo | {adesso:yyyy.MM.dd HH:mm:ss}"); iobObj.checkVetoQueueIn(); } } @@ -1963,7 +1967,7 @@ namespace IOB_WIN_FORM // out di cosa faccio... displayTaskAndLog($"[STARTUP] Loading ConfFile: {iniConfFile}"); var appVers = Assembly.GetExecutingAssembly().GetName().Version; - string path = fileMover.GetExecutingDirectoryName(); // Directory.GetCurrentDirectory(); + string path = FileMover.GetExecutingDirectoryName(); // Directory.GetCurrentDirectory(); string fileName = Path.GetFileName(iniConfFile).Replace(".ini", ".iob"); string dirPath = Path.Combine(path, "DATA", "CONF_RUN"); // verifica directory @@ -2137,19 +2141,19 @@ namespace IOB_WIN_FORM private void refreshFormData() { // aggiorno visualizzazioni varie in form... - alQueueLen = iobObj.QueueAlarm.Count; - evQueueLen = iobObj.QueueIN.Count; - flQueueLen = iobObj.QueueFLog.Count; - msQueueLen = iobObj.QueueMessages.Count; - rtrQueueLen = iobObj.QueueRawTransf.Count; - ulQueueLen = iobObj.QueueULog.Count; + alQueueLen = iobObj.QHelp.QueueAlarm.Count; + evQueueLen = iobObj.QHelp.QueueIN.Count; + flQueueLen = iobObj.QHelp.QueueFLog.Count; + msQueueLen = iobObj.QHelp.QueueMessages.Count; + rtrQueueLen = iobObj.QHelp.QueueRawTransf.Count; + ulQueueLen = iobObj.QHelp.QueueULog.Count; // aggiorno labels counters... counterIob = $"pz MES {iobObj.contapezziIOB}"; counterMac = $"pz PLC {iobObj.contapezziPLC}"; Dictionary setPar = new Dictionary(); setPar.Add("IP", iobObj.IOBConfFull.Device.Connect.IpAddr); setPar.Add("PORT", iobObj.IOBConfFull.Device.Connect.Port); - string note = $"{iobObj.IOBConfFull.General.FilenameIOB} | DT ultimo avvio: {iobObj.dtAvvioAdp}"; + string note = $"{iobObj.IOBConfFull.General.FilenameIOB} | DT ultimo avvio: {iobObj.DtHelp.AvvioAdp}"; // verifico IOB status IobWinStatus currIobStatus = new IobWinStatus() { @@ -2163,10 +2167,10 @@ namespace IOB_WIN_FORM queueUlLen = ulQueueLen, counterIOB = iobObj.contapezziIOB, counterMAC = iobObj.contapezziPLC, - lastUpdate = lastIobStatus.lastUpdate > iobObj.lastWatchDog ? lastIobStatus.lastUpdate : iobObj.lastWatchDog, + lastUpdate = lastIobStatus.lastUpdate > iobObj.DtHelp.lastWatchDog ? lastIobStatus.lastUpdate : iobObj.DtHelp.lastWatchDog, online = utils.IOB_Online, - lastDataIn = iobObj.lastReadPLC, - lastDataOut = iobObj.lastIobOnline, + lastDataIn = iobObj.DtHelp.lastReadPLC, + lastDataOut = iobObj.DtHelp.lastIobOnline, setupParams = setPar, freeNotes = note }; diff --git a/IOB-WIN-FORM/IOB-WIN-FORM.csproj b/IOB-WIN-FORM/IOB-WIN-FORM.csproj index ca506eea..288b827c 100644 --- a/IOB-WIN-FORM/IOB-WIN-FORM.csproj +++ b/IOB-WIN-FORM/IOB-WIN-FORM.csproj @@ -14,6 +14,7 @@ + true true @@ -91,6 +92,9 @@ ..\packages\System.Numerics.Vectors.4.6.1\lib\net462\System.Numerics.Vectors.dll + + ..\packages\System.Resources.Extensions.4.7.1\lib\net461\System.Resources.Extensions.dll + ..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll diff --git a/IOB-WIN-FORM/Iob/BaseObj.cs b/IOB-WIN-FORM/Iob/BaseObj.cs index 938c072e..a0fb40f8 100644 --- a/IOB-WIN-FORM/Iob/BaseObj.cs +++ b/IOB-WIN-FORM/Iob/BaseObj.cs @@ -1,12 +1,6 @@ -using IOB_UT_NEXT; +using IOB_UT_NEXT.Objects; using NLog; using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Net.NetworkInformation; -using System.Threading; -using static IOB_UT_NEXT.BaseAlarmConf; namespace IOB_WIN_FORM.Iob { @@ -245,13 +239,13 @@ namespace IOB_WIN_FORM.Iob { lg.Factory.Configuration.Variables["codIOB"] = IOBConfFull.General.FilenameIOB; DateTime adesso = DateTime.Now; - if (adesso.Subtract(lastLogStartup).TotalMinutes > vetoLogStartupDuration) + if (adesso.Subtract(DtHelp.lastLogStartup).TotalMinutes > vetoLogStartupDuration) { lg.Info(message); // se supera di 5 minutis cadenza -_> reimposto veto... - if (adesso.Subtract(lastLogStartup).TotalMinutes > vetoLogStartupDuration + 5) + if (adesso.Subtract(DtHelp.lastLogStartup).TotalMinutes > vetoLogStartupDuration + 5) { - lastLogStartup = adesso; + DtHelp.lastLogStartup = adesso; } } if (sendToForm) @@ -274,13 +268,13 @@ namespace IOB_WIN_FORM.Iob { lg.Factory.Configuration.Variables["codIOB"] = IOBConfFull.General.FilenameIOB; DateTime adesso = DateTime.Now; - if (adesso.Subtract(lastLogStartup).TotalMinutes > vetoLogStartupDuration) + if (adesso.Subtract(DtHelp.lastLogStartup).TotalMinutes > vetoLogStartupDuration) { lg.Info(message, args); // se supera di 5 minutis cadenza -_> reimposto veto... - if (adesso.Subtract(lastLogStartup).TotalMinutes > vetoLogStartupDuration + 5) + if (adesso.Subtract(DtHelp.lastLogStartup).TotalMinutes > vetoLogStartupDuration + 5) { - lastLogStartup = adesso; + DtHelp.lastLogStartup = adesso; } } sendToLogWatch("INFO", message, args); diff --git a/IOB-WIN-FORM/Iob/Generic.cs b/IOB-WIN-FORM/Iob/Generic.cs index da8cc0ef..7eccfbdd 100644 --- a/IOB-WIN-FORM/Iob/Generic.cs +++ b/IOB-WIN-FORM/Iob/Generic.cs @@ -1,13 +1,21 @@ using EgwProxy.Ftp; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Config.Mem; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Cache; +using IOB_UT_NEXT.Services.Core; +using IOB_UT_NEXT.Services.Data; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Machine; +using IOB_UT_NEXT.Services.Monitoring; +using IOB_UT_NEXT.Services.Networking; +using IOB_UT_NEXT.Services.Utility; using MapoSDK; using MathNet.Numerics.Statistics; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NLog; -using NLog.Targets; using System; using System.Collections; using System.Collections.Generic; @@ -19,15 +27,12 @@ using System.Net; using System.Net.NetworkInformation; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; -using System.Security.AccessControl; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; -using YamlDotNet.Core.Tokens; -using static IOB_UT_NEXT.BaseAlarmConf; +using static IOB_UT_NEXT.Config.BaseAlarmConf; using static IOB_UT_NEXT.CustomObj; using static IOB_UT_NEXT.DataModel.Fimat; using static MapoSDK.WharehouseData; @@ -61,16 +66,21 @@ namespace IOB_WIN_FORM.Iob // init oggetto redis... redisMan = new RedisIobCache(IobConfNew.MapoMes.IpAddr, IobConfNew.General.FilenameIOB, $"{IobConfNew.General.IobType}", IobConfNew.General.MinDeltaSec); + // init oggetto TCMan + var tcMan = new TCMan(IobConfNew.TCDataConf.Lambda, IobConfNew.TCDataConf.MaxDelayFactor, IobConfNew.TCDataConf.MaxIncrPz); + + // init communication services + commService = new CommunicationService(IobConfNew, redisMan); + machineCommService = new MachineCommunicationService(IobConfNew, tcMan, memMap); + // init code SetupQueue(); - // initi oggetto TCMan - tcMan = new TCMan(IobConfNew.TCDataConf.Lambda, IobConfNew.TCDataConf.MaxDelayFactor, IobConfNew.TCDataConf.MaxIncrPz); - lastConnectTry = DateTime.Now; + DtHelp.lastConnectTry = DateTime.Now; lgInfo("Avvio preliminare AdapterGeneric"); - lastLogStartup = DateTime.Now; + DtHelp.lastLogStartup = DateTime.Now; // setup currProdData & last prod data currProdData = redisMan.redGetHashDict(rKeyCurrProdData); @@ -86,8 +96,8 @@ namespace IOB_WIN_FORM.Iob checkShrinkDir(); // imposto veto invio per i prossimi sec - dtVetoQueueIN = DateTime.Now.AddSeconds(vetoQueueIn); - string msgVeto = $"Impostato veto QUEUE-IN a {vetoQueueIn}s | fino alle {dtVetoQueueIN:yyyy.MM.dd HH:mm:ss}"; + utils.dtVetoQueueIN = DateTime.Now.AddSeconds(vetoQueueIn); + string msgVeto = $"Impostato veto QUEUE-IN a {vetoQueueIn}s | fino alle {utils.dtVetoQueueIN:yyyy.MM.dd HH:mm:ss}"; lgInfoStartup(msgVeto); lgInfo(msgVeto); @@ -127,44 +137,8 @@ namespace IOB_WIN_FORM.Iob /// public virtual bool connectionOk { - get - { - return _connOk || DemoIn; - } - set - { - _connOk = value; - } - } - - /// - /// Contapezzi attuale - /// - public Int32 contapezziIOB - { - get - { - return tcMan.pzCountIOB; - } - set - { - tcMan.pzCountIOB = value; - } - } - - /// - /// Ultima lettura variabile contapezzi da CNC - /// - public Int32 contapezziPLC - { - get - { - return tcMan.pzCountPLC; - } - set - { - tcMan.pzCountPLC = value; - } + get => _connOk || DemoIn; + set => _connOk = value; } /// @@ -172,6 +146,7 @@ namespace IOB_WIN_FORM.Iob /// public int counterFLog { get; set; } + /// /// Contatore x invio dati RawTransf /// @@ -287,10 +262,7 @@ namespace IOB_WIN_FORM.Iob /// Valore massimo accettato x incremento pezzi letti dal PLC (valore moltiplicato per /// 100... 200% --> 200) ///
- public int maxPzDeltaPerc - { - get => IOBConfFull.Counters.MaxIncrPzCountPerc; - } + public int maxPzDeltaPerc => IOBConfFull.Counters.MaxIncrPzCountPerc; /// /// Verifica SE si debba fare log periodico (ogni "verboseLogTOut" sec...) @@ -300,46 +272,45 @@ namespace IOB_WIN_FORM.Iob get { bool answ = false; - answ = (DateTime.Now.Subtract(lastPeriodicLog).TotalSeconds > utils.CRI("verboseLogTOut")); + answ = (DateTime.Now.Subtract(DtHelp.lastPeriodicLog).TotalSeconds > utils.CRI("verboseLogTOut")); if (answ) { - lastPeriodicLog = DateTime.Now; + DtHelp.lastPeriodicLog = DateTime.Now; } return answ; } } + /// + /// Contapezzi attuale + /// + public Int32 contapezziIOB + { + get => machineCommService.ContapezziIOB; + set => machineCommService.ContapezziIOB = value; + } + /// + /// Ultima lettura variabile contapezzi da CNC + /// + public Int32 contapezziPLC + { + get => machineCommService.ContapezziPLC; + set => machineCommService.ContapezziPLC = value; + } /// /// Valore medio del TC rilevato x verifica derive sul delta variazione contapezzi /// - public double plcAvgTc - { - get - { - double answ = tcMan.avgTC > 0 ? tcMan.avgTC : 1; - return answ; - } - } - + public double plcAvgTc => machineCommService.GetAverageTc(); /// /// DataOra dell'ultima lettura variabile contapezzi da CNC /// - public DateTime plcLastPzRead - { - get - { - return tcMan.lastObservedData; - } - } - + public DateTime plcLastPzRead => machineCommService.GetLastObservedData(); /// /// Determina se il contapezzi plc sia valido (lo è se data avvio adapter è prima di ultimo dato registrato in contapezzi) /// - public bool plcPzCountValid - { - get => tcMan.lastObservedData > dtAvvioAdp; - } + public bool plcPzCountValid => machineCommService.GetLastObservedData() > DtHelp.AvvioAdp; + /// /// Abilitazione coda segnali ingresso @@ -367,18 +338,12 @@ namespace IOB_WIN_FORM.Iob /// /// URL per segnalazione reboot... /// - public string urlReboot - { - get => $@"{urlCommandIobFile("sendReboot")}?mac={GetMACAddress()}"; - } + public string urlReboot => $@"{urlCommandIobFile("sendReboot")}?mac={NetService.GetMACAddress()}"; /// /// URL per salvataggio dati conf YAML completi IOB... /// - public string urlSaveConfYaml - { - get => $@"{urlCommandIobFile("saveConfYaml")}"; - } + public string urlSaveConfYaml => $@"{urlCommandIobFile("saveConfYaml")}"; /// /// Verifica SE si debba fare log verboso (verboso + ogni tot letture IN) @@ -404,13 +369,13 @@ namespace IOB_WIN_FORM.Iob #region Public Methods /// - /// Esegue conversione in un dizionario di tipo string/string serializzando e deserializzando + /// Conversione in un dizionario di tipo string/string serializzando e deserializzando /// /// /// public static Dictionary ConvertToStringDict(Dictionary input) { - return DataSerializer.ToDictionary(input); + return IOB_UT_NEXT.Services.Data.DataSerializer.ToDictionary(input); } /// @@ -423,7 +388,7 @@ namespace IOB_WIN_FORM.Iob // mostro dati variati letti... displayOtherData(val); // accodo IN PRIMIS al FluxLog --> accodo (valore già formattato)! - QueueFLog.Enqueue(encodedVal); + QHelp.QueueFLog.Enqueue(encodedVal); // accodo ANCHE alla coda allarmi che trasmetterò SOLO SE a scadenza impostata (10 sec?) // ho allarmi perdurati... @@ -461,18 +426,18 @@ namespace IOB_WIN_FORM.Iob // mostro dati variati letti... displayOtherData(val); // --> accodo (valore già formattato)! - QueueFLog.Enqueue(encodedVal); + QHelp.QueueFLog.Enqueue(encodedVal); // se abilitato controllo coda FLog (superiore a 0...) if (maxQueueFLog > 0) { // se ho una coda superiore a max ammesso - if (QueueFLog.Count > maxQueueFLog) + if (QHelp.QueueFLog.Count > maxQueueFLog) { // elimino valori iniziali fino a tornare al max ammesso... - while (QueueFLog.Count > maxQueueFLog) + while (QHelp.QueueFLog.Count > maxQueueFLog) { string currVal = ""; - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); lgInfo($"Eliminazione da coda FLog per superamento maxLengh: {currVal}"); } } @@ -544,20 +509,20 @@ namespace IOB_WIN_FORM.Iob } BaseRawTransf newVal = new BaseRawTransf(DateTime.Now, njObj, mesType); - string encodedVal = DataSerializer.Serialize(newVal); + string encodedVal = JsonSerialize(newVal); // --> accodo (valore già formattato)! - QueueRawTransf.Enqueue(encodedVal); + QHelp.QueueRawTransf.Enqueue(encodedVal); // se abilitato controllo coda Max (superiore a 0...) if (maxQueueRawTransf > 0) { // se ho una coda superiore a max ammesso - if (QueueRawTransf.Count > maxQueueRawTransf) + if (QHelp.QueueRawTransf.Count > maxQueueRawTransf) { // elimino valori iniziali fino a tornare al max ammesso... - while (QueueRawTransf.Count > maxQueueRawTransf) + while (QHelp.QueueRawTransf.Count > maxQueueRawTransf) { string currVal = ""; - QueueRawTransf.TryDequeue(out currVal); + QHelp.QueueRawTransf.TryDequeue(out currVal); lgInfo($"Eliminazione da coda RawTransf per superamento maxLengh: {currVal}"); } } @@ -592,7 +557,7 @@ namespace IOB_WIN_FORM.Iob if (queueInEnabCurr) { // --> accodo (valore già formattato)! - QueueIN.Enqueue(qEncodeIN); + QHelp.QueueIN.Enqueue(qEncodeIN); // loggo! lgDebug($"[QUEUE-IN] {qEncodeIN}"); } @@ -614,7 +579,7 @@ namespace IOB_WIN_FORM.Iob counterSigIN = 0; } } - lgDebug($"accodaSigIN 02 | nReadFilt: {nReadFilt} | counterSigIN: {counterSigIN} | QueueIN len: {QueueIN.Count}"); + lgDebug($"accodaSigIN 02 | nReadFilt: {nReadFilt} | counterSigIN: {counterSigIN} | QHelp.QueueIN len: {QHelp.QueueIN.Count}"); } /// @@ -627,7 +592,7 @@ namespace IOB_WIN_FORM.Iob // mostro dati variati letti... displayOtherData(val); // accodo IN PRIMIS al FluxLog --> accodo (valore già formattato)! - QueueULog.Enqueue(encodedVal); + QHelp.QueueULog.Enqueue(encodedVal); // loggo! lgInfo(string.Format("[QUEUE-USER-LOG] {0}", encodedVal)); @@ -644,14 +609,14 @@ namespace IOB_WIN_FORM.Iob public async Task CheckIobEnabled() { // 1. Controllo Veto (Sincrono) - if (dtVetoCheckIOB >= DateTime.Now) + if (DtHelp.VetoCheckIOB >= DateTime.Now) return IobOnline; bool currentAnsw = false; if (DemoOut) { - currentAnsw = (QueueIN.Count + QueueFLog.Count >= nMaxSend); + currentAnsw = (QHelp.QueueIN.Count + QHelp.QueueFLog.Count >= nMaxSend); } else { @@ -683,7 +648,7 @@ namespace IOB_WIN_FORM.Iob public bool CheckServerAlive() // Rimosso async, restituisce bool { // 1. Controllo Veto (Sincrono) - if (dtVetoPing >= DateTime.Now) return MPOnline; + if (utils.dtVetoPing >= DateTime.Now) return MPOnline; if (DemoOut) return true; // 2. Eseguo la parte asincrona forzando l'attesa @@ -705,7 +670,7 @@ namespace IOB_WIN_FORM.Iob public async Task CheckServerAliveAsync() { // 1. Controllo Veto (Sincrono) - if (dtVetoPing >= DateTime.Now) return MPOnline; + if (utils.dtVetoPing >= DateTime.Now) return MPOnline; if (DemoOut) return true; bool isAlive = await ExecuteApiCheckWithRetryAsync(maxRetries: 7); @@ -717,11 +682,11 @@ namespace IOB_WIN_FORM.Iob } /// - /// Verifica veto coda QueueIN ed aggiorna abilitazione su variabile + /// Verifica veto coda QHelp.QueueIN ed aggiorna abilitazione su variabile /// public void checkVetoQueueIn() { - queueInEnabCurr = dtVetoQueueIN < DateTime.Now; + queueInEnabCurr = utils.dtVetoQueueIN < DateTime.Now; } /// @@ -769,13 +734,13 @@ namespace IOB_WIN_FORM.Iob { // imposto flag adapter running.. adpCommAct = true; - adpStartRun = DateTime.Now; + DtHelp.adpStartRun = DateTime.Now; } catch (Exception exc) { string errore = $"Adapter NOT STARTED!!!{Environment.NewLine}{exc}"; adpCommAct = false; - adpStartRun = DateTime.Now; + DtHelp.adpStartRun = DateTime.Now; currDispData.newLiveLogData = errore; } if (adpCommAct) @@ -855,11 +820,11 @@ namespace IOB_WIN_FORM.Iob // log ADP running lgInfo("Non eseguo chiamata: ADP ancora in running"); // se è bloccato da oltre maxSec lo sblocco... - if (DateTime.Now.Subtract(adpStartRun).TotalSeconds > utils.CRI("maxAdapterLockSec")) + if (DateTime.Now.Subtract(DtHelp.adpStartRun).TotalSeconds > utils.CRI("maxAdapterLockSec")) { // tolgo flag running adpCommAct = false; - adpStartRun = DateTime.Now; + DtHelp.adpStartRun = DateTime.Now; } } } @@ -875,11 +840,11 @@ namespace IOB_WIN_FORM.Iob { waitRecMSec = IOBConfFull.General.WaitRecMsec; } - DateTime dtVeto = lastConnectTry.AddMilliseconds(waitRecMSec); + DateTime dtVeto = DtHelp.lastConnectTry.AddMilliseconds(waitRecMSec); if (DateTime.Now > dtVeto) { - lgInfo($"Veto Time Elapsed | lastConnectTry: {lastConnectTry} | waitRecMSec {waitRecMSec} ms) | NOW tryConnect"); - lastConnectTry = DateTime.Now; + lgInfo($"Veto Time Elapsed | DtHelp.lastConnectTry: {DtHelp.lastConnectTry} | waitRecMSec {waitRecMSec} ms) | NOW tryConnect"); + DtHelp.lastConnectTry = DateTime.Now; tryConnect(); } } @@ -1006,28 +971,6 @@ namespace IOB_WIN_FORM.Iob { processRecipeSyncArch(); } - - //// provo a riconnettere SE abilitato tryRestart... - //if (adpTryRestart && !connectionOk) - //{ - // // controllo se sia scaduto periodi di veto al tryConnect... - // int waitRecMSec = utils.CRI("waitRecMSec"); - // // cerco se ci sia un valore in ovverride x il singolo IOB... - // if (IOBConfFull.General.WaitRecMsec > 0) - // { - // waitRecMSec = IOBConfFull.General.WaitRecMsec; - // } - // DateTime dtVeto = lastConnectTry.AddMilliseconds(waitRecMSec); - // if (DateTime.Now > dtVeto) - // { - // lgInfo($"Veto Time Elapsed | lastConnectTry: {lastConnectTry} | waitRecMSec {waitRecMSec} ms) | NOW tryConnect"); - // lastConnectTry = DateTime.Now; - // tryConnect(); - // } - //} - //currDispData.semIn = Semaforo.SR; - //processDisconnectedTask(); - //processMemoryDiscon(); } raiseRefresh(currDispData); } @@ -1035,32 +978,32 @@ namespace IOB_WIN_FORM.Iob public void ExecServerRequests() { // verifica se ci siano richieste da eseguire - if (QueueSrvReq.Count > 0) + if (QHelp.QueueSrvReq.Count > 0) { if (MPOnline) { if (IobOnline) { // prendo elenco - List listaValori = QueueSrvReq.ToList(); + List listaValori = QHelp.QueueSrvReq.ToList(); foreach (var rawJob in listaValori) { // deserializzo... - JobTaskData jobTaskReq = JsonConvert.DeserializeObject(rawJob); + JobTaskData jobTaskReq = JsonDeserialize(rawJob); // processo! var reqDict = JobTaskData.TaskDict(jobTaskReq.RawData); if (reqDict.Count > 0) { var taskDone = ProcessTask(JobTaskData.TaskDict(jobTaskReq.RawData), jobTaskReq.CodTav); // accodo task eseguiti... - string serVal = JsonConvert.SerializeObject(taskDone); + string serVal = JsonSerialize(taskDone); accodaServResp(jobTaskReq.CodTav, serVal); } } // svuoto! - QueueSrvReq = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueServResp", IOBConfFull.General.EnabRedisQue, redisMan); + QHelp.QueueSrvReq = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueServResp", IOBConfFull.General.EnabRedisQue, redisMan); } } } @@ -1111,24 +1054,13 @@ namespace IOB_WIN_FORM.Iob case taskType.setProg: case taskType.setPzComm: // recupero dati da memMap... - if (memMap != null && memMap.mMapWrite != null) + if (machineCommService.WriteToMemMap(iKey, item.Value)) { - if (memMap.mMapWrite.ContainsKey(iKey)) - { - dataConf currMem = memMap.mMapWrite[iKey]; - string addr = currMem.memAddr; - taskVal = $"SET task: {iKey} --> {item.Value} | mem: {currMem.memAddr} - {currMem.size} byte"; - // salvo il nuovo valore nella memoria... così prox invio lo trasmetterà - memMap.mMapWrite[iKey].value = item.Value; - } - else - { - taskVal = $"NO DATA MEM, SET task: {iKey} --> {item.Value}"; - } + taskVal = $"SET task: {iKey} --> {item.Value} | mem: [Updated via MachineComm]"; } else { - taskVal = $"NO BankConf found, SET task: {iKey} --> {item.Value}"; + taskVal = $"NO DATA MEM, SET task: {iKey} --> {item.Value}"; } // salvo in currProd.. upsertKey(iKey, item.Value); @@ -1155,7 +1087,7 @@ namespace IOB_WIN_FORM.Iob string addr = currMem.memAddr; taskVal = $"SET task: {iKey} --> {item.Value} | mem: {currMem.memAddr} - {currMem.size} byte"; // salvo il nuovo valore nella memoria... così prox invio lo trasmetterà - memMap.mMapWrite[iKey].value = item.Value; + machineCommService.WriteToMemMap(iKey, item.Value); taskOk = true; } else @@ -1163,8 +1095,8 @@ namespace IOB_WIN_FORM.Iob taskVal = $"NO DATA MEM, SET task: {iKey} --> {item.Value}"; } // imposto reset gestione pzcount da parametri - vetoQueuePzCount = DateTime.Now.AddMinutes(IOBConfFull.General.DelayReadPzCountSetup); - dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); + DtHelp.vetoQueuePzCount = DateTime.Now.AddMinutes(IOBConfFull.General.DelayReadPzCountSetup); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); } else { @@ -1178,26 +1110,16 @@ namespace IOB_WIN_FORM.Iob case taskType.forceSetPzCount: // recupero dati da memMap... - if (memMap != null && memMap.mMapWrite != null) + if (machineCommService.WriteToMemMap(iKey, item.Value)) { - if (memMap.mMapWrite.ContainsKey(iKey)) - { - dataConf currMem = memMap.mMapWrite[iKey]; - string addr = currMem.memAddr; - taskVal = $"SET task: {iKey} --> {item.Value} | mem: {currMem.memAddr} - {currMem.size} byte"; - // salvo il nuovo valore nella memoria... così prox invio lo trasmetterà - memMap.mMapWrite[iKey].value = item.Value; - } - else - { - taskVal = $"NO DATA MEM, SET task: {iKey} --> {item.Value}"; - } + taskVal = $"SET task: {iKey} --> {item.Value} | mem: [Updated via MachineComm]"; } else { - taskVal = $"NO BankConf found, SET task: {iKey} --> {item.Value}"; + taskVal = $"NO DATA MEM, SET task: {iKey} --> {item.Value}"; } + lgInfo($"Chiamata forceSetPzCount: taskVal: {taskVal}"); break; @@ -1212,26 +1134,16 @@ namespace IOB_WIN_FORM.Iob newVal = getNumArt(item.Value); // procedo come il resto cercando mappatura in memMap: recupero dati // da memMap... - if (memMap != null && memMap.mMapWrite != null) + if (machineCommService.WriteToMemMap(iKey, newVal)) { - if (memMap.mMapWrite.ContainsKey(iKey)) - { - dataConf currMem = memMap.mMapWrite[iKey]; - string addr = currMem.memAddr; - taskVal = $"SET task: {iKey} --> {newVal} | mem: {currMem.memAddr} - {currMem.size} byte"; - // salvo il nuovo valore nella memoria... così prox invio lo trasmetterà - memMap.mMapWrite[iKey].value = newVal; - } - else - { - taskVal = $"NO DATA MEM, SET task: {iKey} --> {newVal} ({item.Value})"; - } + taskVal = $"SET task: {iKey} --> {newVal} | mem: [Updated via MachineComm]"; } else { - taskVal = $"NO BankConf found, SET task: {iKey} --> {newVal} ({item.Value})"; + taskVal = $"NO DATA MEM, SET task: {iKey} --> {newVal} ({item.Value})"; } + // salvo in currProd.. upsertKey(iKey, newVal); break; @@ -1241,26 +1153,16 @@ namespace IOB_WIN_FORM.Iob newVal = getNumComm(item.Value); // procedo come il resto cercando mappatura in memMap: recupero dati // da memMap... - if (memMap != null && memMap.mMapWrite != null) + if (machineCommService.WriteToMemMap(iKey, newVal)) { - if (memMap.mMapWrite.ContainsKey(iKey)) - { - dataConf currMem = memMap.mMapWrite[iKey]; - string addr = currMem.memAddr; - taskVal = $"SET task: {iKey} --> {newVal} | mem: {currMem.memAddr} - {currMem.size} byte"; - // salvo il nuovo valore nella memoria... così prox invio lo trasmetterà - memMap.mMapWrite[iKey].value = newVal; - } - else - { - taskVal = $"NO DATA MEM, SET task: {iKey} --> {newVal} ({item.Value})"; - } + taskVal = $"SET task: {iKey} --> {newVal} | mem: [Updated via MachineComm]"; } else { - taskVal = $"NO BankConf found, SET task: {iKey} --> {newVal} ({item.Value})"; + taskVal = $"NO DATA MEM, SET task: {iKey} --> {newVal} ({item.Value})"; } + // salvo in currProd.. upsertKey(iKey, newVal); break; @@ -1271,8 +1173,8 @@ namespace IOB_WIN_FORM.Iob { lgDebug($"Generic.executeTasks {tName} | resetContapezziPLC"); taskOk = resetContapezziPLC(codTav); - vetoQueuePzCount = DateTime.Now.AddMinutes(IOBConfFull.General.DelayReadPzCountSetup); - dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); + DtHelp.vetoQueuePzCount = DateTime.Now.AddMinutes(IOBConfFull.General.DelayReadPzCountSetup); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); } taskVal = taskOk ? "startSetup | RESET: SETUP START" : "startSetup | PZ RESET DISABLED | NO EXEC"; lgInfo($"Chiamata startSetup: taskOk: {taskOk} | taskVal: {taskVal}"); @@ -1387,11 +1289,11 @@ namespace IOB_WIN_FORM.Iob public async Task forceSplitOdl() { bool fatto = false; - if (vetoSplit < DateTime.Now) + if (DtHelp.vetoSplit < DateTime.Now) { lgInfo("Richiesto forceSplitOdl"); // imposto veto x 1 minuto ad altre chiamate... - vetoSplit = DateTime.Now.AddMinutes(1); + DtHelp.vetoSplit = DateTime.Now.AddMinutes(1); // eseguo SOLO SE sono online... if (MPOnline && IobOnline) { @@ -1820,7 +1722,7 @@ namespace IOB_WIN_FORM.Iob // conversione finale try { - answ = JsonConvert.SerializeObject(fullFlObj); + answ = JsonSerialize(fullFlObj); } catch (Exception exc) { @@ -1851,7 +1753,7 @@ namespace IOB_WIN_FORM.Iob // conversione finale try { - answ = JsonConvert.SerializeObject(fullEvObj); + answ = JsonSerialize(fullEvObj); } catch (Exception exc) { @@ -1910,7 +1812,7 @@ namespace IOB_WIN_FORM.Iob // conversione finale try { - answ = JsonConvert.SerializeObject(fullUlObj); + answ = JsonSerialize(fullUlObj); } catch (Exception exc) { @@ -1937,11 +1839,11 @@ namespace IOB_WIN_FORM.Iob string rawVal = redisMan.redGetHashField(lastSendKey, keyReq); if (!string.IsNullOrEmpty(rawVal)) { - lastSend = DataSerializer.Deserialize(rawVal); + lastSend = JsonDeserialize(rawVal); } else { - rawVal = DataSerializer.Serialize(lastSend); + rawVal = JsonSerialize(lastSend); KeyValuePair[] hashFields = new KeyValuePair[1]; hashFields[0] = new KeyValuePair(keyReq, rawVal); redisMan.redSaveHash(lastSendKey, hashFields); @@ -1957,7 +1859,7 @@ namespace IOB_WIN_FORM.Iob public bool LastSendSet(string keyReq, DateTime dtRif) { string lastSendKey = GetStatusField("LastSend"); - string rawVal = DataSerializer.Serialize(dtRif); + string rawVal = JsonSerialize(dtRif); KeyValuePair[] hashFields = new KeyValuePair[1]; hashFields[0] = new KeyValuePair(keyReq, rawVal); bool fatto = redisMan.redSaveHash(lastSendKey, hashFields); @@ -1997,16 +1899,16 @@ namespace IOB_WIN_FORM.Iob // loggo SOLO se del mio IOB corrente... if (item.classCall == IOBConfFull.General.FilenameIOB) { - lgInfo("{4}|Chiamate {0}: effettuate {1}, tempo medio {2:N2} msec | impegno canale {3:P3}", item.codCall, item.numCall, item.avgMsec, item.totMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds, IOBConfFull.General.CodIOB); + lgInfo("{4}|Chiamate {0}: effettuate {1}, tempo medio {2:N2} msec | impegno canale {3:P3}", item.codCall, item.numCall, item.avgMsec, item.totMsec.TotalSeconds / DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalSeconds, IOBConfFull.General.CodIOB); globNumCall += item.numCall; globAvgMsec += item.totMsec; } } // riporto conteggio medio al secondo... - lgInfo("{4}|Chiamate GLOBALI: {0}, periodo: {1:N2} minuti.cent, tempo medio {2:N2} msec | impegno canale {3:P3}", globNumCall, DateTime.Now.Subtract(dtAvvioAdp).TotalMinutes, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds, IOBConfFull.General.CodIOB); + lgInfo("{4}|Chiamate GLOBALI: {0}, periodo: {1:N2} minuti.cent, tempo medio {2:N2} msec | impegno canale {3:P3}", globNumCall, DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalMinutes, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalSeconds, IOBConfFull.General.CodIOB); lgInfo("{0}--------------- STOP TIMING DATA ---------------{0}", Environment.NewLine); // mostro in form statistiche globali! - parentForm.updateComStats(string.Format("Periodo: {0:N2}min | {1} x {2:N2}ms | canale {3:P3}", DateTime.Now.Subtract(dtAvvioAdp).TotalMinutes, globNumCall, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds)); + parentForm.updateComStats(string.Format("Periodo: {0:N2}min | {1} x {2:N2}ms | canale {3:P3}", DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalMinutes, globNumCall, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalSeconds)); } } @@ -2056,9 +1958,9 @@ namespace IOB_WIN_FORM.Iob if (IOBConfFull.FluxLog.AutoSnapshotDossier) { DateTime adesso = DateTime.Now; - if (adesso > dtVetoAutoDossier) + if (adesso > DtHelp.dtVetoAutoDossier) { - dtVetoAutoDossier = adesso.AddMinutes(30); + DtHelp.dtVetoAutoDossier = adesso.AddMinutes(30); lgTrace("Richiesta ProcessAutoDossier"); lgTrace("AutoSnapshotDossier abilitato"); @@ -2106,7 +2008,7 @@ namespace IOB_WIN_FORM.Iob { lgTrace("ProcessAutoOdlAsync | AutoChangeOdl abilitato"); // imposto il veto lettura contapezzi a 1 minuto x iniziare... - dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); string fullUrl = ""; DateTime adesso = DateTime.Now; DateTime inizioOdl = adesso; @@ -2566,7 +2468,7 @@ namespace IOB_WIN_FORM.Iob newDisplayData currDispData = new newDisplayData(); // controllo contatore invio "keepalive"... invio solo a scadenza int disconnMaxSec = utils.CRI("disconMaxSec"); - if (DateTime.Now.Subtract(lastDisconnCheck).TotalSeconds > disconnMaxSec) + if (DateTime.Now.Subtract(DtHelp.lastDisconnCheck).TotalSeconds > disconnMaxSec) { // resetto tutti i valori BYTE IN/PREV/OUT... così invio macchina spenta... B_input = 0; @@ -2574,7 +2476,7 @@ namespace IOB_WIN_FORM.Iob B_previous = -1; accodaSigIN(ref currDispData); // update controllo - lastDisconnCheck = DateTime.Now; + DtHelp.lastDisconnCheck = DateTime.Now; lgInfo($"Send 00 | disconMaxSec: {disconnMaxSec}"); } raiseRefresh(currDispData); @@ -2937,7 +2839,7 @@ namespace IOB_WIN_FORM.Iob /// public virtual void readSemafori(ref newDisplayData currDispData) { - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } /// @@ -3212,7 +3114,7 @@ namespace IOB_WIN_FORM.Iob } } - string rawData = JsonConvert.SerializeObject(ActiveAlarmList); + string rawData = JsonSerialize(ActiveAlarmList); string resp = HttpService.CallUrlPost(lastUrl, rawData); //string resp = HttpService.CallUrlAsync(lastUrl, rawData); if (resp != null) @@ -3268,12 +3170,12 @@ namespace IOB_WIN_FORM.Iob fatto = true; currDispData.semOut = Semaforo.SV; // se oltre 1 min NON era online --> check pezzi! - if (DateTime.Now.Subtract(lastIobOnline).TotalMinutes > 1 && !isMulti) + if (DateTime.Now.Subtract(DtHelp.lastIobOnline).TotalMinutes > 1 && !isMulti) { - lgInfo($"sendDataBlock --> offline timeout ({lastIobOnline}) --> pzCntReload(true)"); + lgInfo($"sendDataBlock --> offline timeout ({DtHelp.lastIobOnline}) --> pzCntReload(true)"); pzCntReload(true); } - lastIobOnline = DateTime.Now; + DtHelp.lastIobOnline = DateTime.Now; } else { @@ -3295,7 +3197,7 @@ namespace IOB_WIN_FORM.Iob // riporto cosa inviato currDispData.newUrlCallData = lastUrl; // aggiorno data ultimo watchdog... - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } catch { @@ -3350,9 +3252,9 @@ namespace IOB_WIN_FORM.Iob // loggo! lgDebug(string.Format("[SEND] {0} -> {1}", queueVal, answ)); // se oltre 1 min NON era online --> check pezzi! - if (DateTime.Now.Subtract(lastIobOnline).TotalMinutes > 1 && !isMulti) + if (DateTime.Now.Subtract(DtHelp.lastIobOnline).TotalMinutes > 1 && !isMulti) { - lgInfo($"sendToMoonPro --> offline timeout ({lastIobOnline}) --> pzCntReload(true)"); + lgInfo($"sendToMoonPro --> offline timeout ({DtHelp.lastIobOnline}) --> pzCntReload(true)"); pzCntReload(true); } // se richiesto effettuo refresh contapezzi @@ -3361,7 +3263,7 @@ namespace IOB_WIN_FORM.Iob pzCntReload(true); needRefreshPzCount = false; } - lastIobOnline = DateTime.Now; + DtHelp.lastIobOnline = DateTime.Now; // se "OK" verde, altrimenti errore --> ROSSO if (answ == "OK") { @@ -3386,7 +3288,7 @@ namespace IOB_WIN_FORM.Iob nSendOut++; currDispData.newUrlCallData = lastUrl; // aggiorno data ultimo watchdog... - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } catch { @@ -3458,21 +3360,21 @@ namespace IOB_WIN_FORM.Iob maxJsonDataEv = utils.CRI("maxJsonDataEv"); parentForm.commPlcActive = false; adpRunning = true; - dtAvvioAdp = adesso; - lastWatchDog = scaduto; - lastPING = scaduto; - lastReadPLC = scaduto; - lastDisconnCheck = scaduto; + DtHelp.AvvioAdp = adesso; + DtHelp.lastWatchDog = scaduto; + DtHelp.lastPING = scaduto; + DtHelp.lastReadPLC = scaduto; + DtHelp.lastDisconnCheck = scaduto; TimingData.resetData(); // aggiungo altri defaults setDefaults(resetQueue); adpTryRestart = true; // sistemo altri check avvio - dtVetoQueueIN = DateTime.Now.AddSeconds(vetoQueueIn); + utils.dtVetoQueueIN = DateTime.Now.AddSeconds(vetoQueueIn); queueInEnabCurr = false; - string msgVeto = $"Impostato veto QUEUE-IN a {vetoQueueIn}s | fino alle {dtVetoQueueIN:yyyy.MM.dd HH:mm:ss}"; + string msgVeto = $"Impostato veto QUEUE-IN a {vetoQueueIn}s | fino alle {utils.dtVetoQueueIN:yyyy.MM.dd HH:mm:ss}"; lgInfoStartup(msgVeto); - lgDebug($"startAdapter completed | veto queueIn impostato per {vetoQueueIn}s fino alle {dtVetoQueueIN:yyyy.MM.dd HH:mm:ss}"); + lgDebug($"startAdapter completed | veto QHelp.QueueIN impostato per {vetoQueueIn}s fino alle {utils.dtVetoQueueIN:yyyy.MM.dd HH:mm:ss}"); } /// @@ -3490,28 +3392,28 @@ namespace IOB_WIN_FORM.Iob { // svuoto le code dei valori letti e non ancora trasmessi... parentForm.displayTaskAndLog("[CLOSING] Svuotamento FORZATO coda segnali...", true); - while (QueueIN.Count > 0) + while (QHelp.QueueIN.Count > 0) { // INVIO COMUNQUE...!!! string valore = ""; - QueueIN.TryDequeue(out valore); + QHelp.QueueIN.TryDequeue(out valore); await sendToMoonPro(urlType.SignIN, valore); } parentForm.displayTaskAndLog("[CLOSING] Svuotamento FORZATO coda FluxLOG...", true); // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueFLog.Count > minJsonData) + if (QHelp.QueueFLog.Count > minJsonData) { - while (QueueFLog.Count > 0) + while (QHelp.QueueFLog.Count > 0) { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueFLog.Count > maxJsonData) + if (QHelp.QueueFLog.Count > maxJsonData) { string currVal = ""; // prendoi primi maxJsonDataValori for (int i = 0; i < maxJsonData; i++) { - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); listaValori.Add(currVal); } await sendDataBlock(urlType.FLog, listaValori); @@ -3519,12 +3421,12 @@ namespace IOB_WIN_FORM.Iob else { // invio in blocco - listaValori = QueueFLog.ToList(); + listaValori = QHelp.QueueFLog.ToList(); // invio await sendDataBlock(urlType.FLog, listaValori); // svuoto! NO REDIS - QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueFLog", false, redisMan); - //QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueFLog", IOBConfFull.General.EnabRedisQue, redisMan); + QHelp.QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueFLog", false, redisMan); + //QHelp.QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueFLog", IOBConfFull.General.EnabRedisQue, redisMan); } } // HO FINITO invio di FLog... @@ -3532,26 +3434,26 @@ namespace IOB_WIN_FORM.Iob else { string currVal = ""; - while (QueueFLog.Count > 0) + while (QHelp.QueueFLog.Count > 0) { // INVIO COMUNQUE...!!! - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); await sendToMoonPro(urlType.FLog, currVal); } } // svuoto coda ULog - while (QueueULog.Count > 0) + while (QHelp.QueueULog.Count > 0) { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueULog.Count > maxJsonData) + if (QHelp.QueueULog.Count > maxJsonData) { string currVal = ""; // prendoi primi maxJsonDataValori for (int i = 0; i < maxJsonData; i++) { - QueueULog.TryDequeue(out currVal); + QHelp.QueueULog.TryDequeue(out currVal); listaValori.Add(currVal); } await sendDataBlock(urlType.ULog, listaValori); @@ -3559,11 +3461,11 @@ namespace IOB_WIN_FORM.Iob else { // invio in blocco - listaValori = QueueULog.ToList(); + listaValori = QHelp.QueueULog.ToList(); // invio await sendDataBlock(urlType.ULog, listaValori); // svuoto! - QueueULog = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueULog", false, redisMan); + QHelp.QueueULog = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueULog", false, redisMan); } } } @@ -3578,14 +3480,14 @@ namespace IOB_WIN_FORM.Iob // chiudo la connessione all'adapter... tryDisconnect(); - dtStopAdp = DateTime.Now; + DtHelp.StopAdp = DateTime.Now; adpTryRestart = tryRestart; adpRunning = false; // chiudo! parentForm.displayTaskAndLog("Adapter Stopped.", true); DateTime adesso = DateTime.Now; - lastReadPLC = adesso; - lastPING = adesso; + DtHelp.lastReadPLC = adesso; + DtHelp.lastPING = adesso; parentForm.commPlcActive = false; } @@ -3595,12 +3497,12 @@ namespace IOB_WIN_FORM.Iob public async Task svuotaCodaSignInAsync() { // verifico SE la coda abbia dei valori... - if (QueueIN.Count > 0) + if (QHelp.QueueIN.Count > 0) { // invio pacchetto di dati (max da conf) for (int i = 0; i < nMaxSend; i++) { - if (QueueIN.Count > 0) + if (QHelp.QueueIN.Count > 0) { string currVal = ""; // se online provo @@ -3609,16 +3511,16 @@ namespace IOB_WIN_FORM.Iob if (IobOnline) { // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueIN.Count > 1) + if (QHelp.QueueIN.Count > 1) { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueIN.Count > maxJsonDataEv) + if (QHelp.QueueIN.Count > maxJsonDataEv) { // prendoi primi maxJsonDataValori for (int j = 0; j < maxJsonDataEv; j++) { - QueueIN.TryDequeue(out currVal); + QHelp.QueueIN.TryDequeue(out currVal); listaValori.Add(currVal); } await sendDataBlock(urlType.SignIN, listaValori); @@ -3626,17 +3528,17 @@ namespace IOB_WIN_FORM.Iob else { // invio in blocco - listaValori = QueueIN.ToList(); + listaValori = QHelp.QueueIN.ToList(); // invio await sendDataBlock(urlType.SignIN, listaValori); // svuoto! - QueueIN = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueIN", IOBConfFull.General.EnabRedisQue, redisMan); + QHelp.QueueIN = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueIN", IOBConfFull.General.EnabRedisQue, redisMan); } } else { // INVIO SINGOLO...!!! - QueueIN.TryDequeue(out currVal); + QHelp.QueueIN.TryDequeue(out currVal); await sendToMoonPro(urlType.SignIN, currVal); } // salvo come last signal in il currVal ultimo... SE !="" @@ -3668,7 +3570,7 @@ namespace IOB_WIN_FORM.Iob /// public virtual void tryConnect() { - dtAvvioAdp = DateTime.Now; + DtHelp.AvvioAdp = DateTime.Now; queueInEnabCurr = true; } @@ -3895,380 +3797,29 @@ namespace IOB_WIN_FORM.Iob if (currentAlive) { lgInfo("SERVER ONLINE"); - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 10); + utils.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 10); } else { lgError("SERVER OFFLINE"); // Veto standard per server offline - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 20); - utils.dtVetoSend = dtVetoPing; + utils.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 20); + utils.dtVetoSend = utils.dtVetoPing; } } else { // Se lo stato è invariato (es. era online e resta online), allunghiamo il prossimo controllo - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 30); + utils.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 30); } } #endregion Private Methods + #region Protected Fields - /// - /// Variabile numero errori vari (in lettura) --> se supera soglia maxErroriCheck --> disconnette - /// - protected static int numErroriCheck = 0; - - protected bool _connOk = false; - - /// - /// valore booleano di check se sia in fase di COMUNICAZIONE ATTIVA con il PLC/NC - /// - protected bool adpCommAct; - - /// - /// porta x adapter (x restart) - /// - protected int adpPortNum; - - /// - /// DataOra ultimo avvio adapter x watchdog - /// - protected DateTime adpStartRun; - - /// - /// Vettore 32 BIT valori in ingresso al filtro - /// - protected int B_input; - - /// - /// Vettore 32 BIT valori in uscita dal filtro - /// - protected int B_output; - - /// - /// Vettore 32 BIT valori precedenti - /// - protected int B_previous = -1; - - /// - /// Cod grupo IOB x creazione PODL al volo - /// - protected string CodGruppoIob = "ND-00"; - - /// - /// Num errori check alive - /// - protected int currAliveErrors = 0; - - /// - /// Dizionario valori impostati x produzione - /// - protected Dictionary currProdData = new Dictionary(); - - /// - /// num corrente errori read PLC - /// - protected int currReadErrors = 0; - - /// - /// num errori send - /// - protected int currSendErrors = 0; - - /// - /// Tempo di attesa in minuti x lettura contapezzi standard (da .ini / OptPar) - /// - protected double delayMinReadPzCount = 0; - - /// - /// Fattore di demoltiplicazione dei DynData x ridurre campionamento - /// - protected int demFactDynData = 1; - - /// - /// Boolean x indicare contapezzi disabilitato forzatamente da IOB - /// - protected bool disablePzCountByIob = false; - - /// - /// Veto x esecuzione task AutoDossier - /// - protected DateTime dtVetoAutoDossier = DateTime.Now; - - /// - /// Veto x esecuzione Task2Exe troppo frequenti - /// - protected DateTime dtVetoTask2Exe = DateTime.Now; - - /// - /// Veto x lettura contapezzi (in caso di autoODL con attesa reset ad esempio...) - /// - protected DateTime dtVetoReadPzCount = DateTime.Now; - - /// - /// Determina se sia prevista gestione PODL (creazione/avvio/chiusura) come Soitaab - /// - protected bool EnabelPodlManFull = false; - - /// - /// Abilita riscrittura memoria se trova differenze lettura/richiesti - /// - protected bool ENABLE_MEM_REWRITE = true; - - /// - /// Abilitazione restart (da opt par...) - /// - protected bool enableCliRestart = false; - - /// - /// Abilitazione invio dataitem - /// - protected bool enableSendDataItem = true; - protected int minVetoSendDataItem = 60; - /// - /// DataOra x veto all'invio dataItem - /// - protected DateTime dtVetoSenDataItem = DateTime.Now; - - /// - /// Boolean x indicare contapezzi abilitato a livello di conf applicazione - /// - protected bool enablePzCountByApp = true; - - /// - /// Abilitazione gestione slow data - /// - protected bool enableSlowData = false; - - /// - /// dizionario (opzionale) xz decodifica file da importare - /// - protected Dictionary FileDecod = new Dictionary(); - - /// - /// DeadBand x riduzione dati FluxLog (se 0 non gestita) - /// - protected double fluxLogRedDeadBand = 0; - - /// - /// Determina se sia gestita riduzione dati FluxLog - /// - protected bool fluxLogReduce = false; - - /// - /// Dizionario dei valori FluxLog ultimi verificati x veto - /// - protected Dictionary fluxLogReduceLast = new Dictionary(); - - /// - /// Dizionario dei valori FluxLog ultimi tipo STRING verificati x veto - /// - protected Dictionary fluxLogReduceLastString = new Dictionary(); - - /// - /// Dizionario dei veto send x ogni variabile quando non variata - /// - protected Dictionary fluxLogReduceVeto = new Dictionary(); - - /// - /// Finestra in minuti x invio dati FluxLog quando invariati - /// - protected int fluxLogResendPeriod = 60; - - /// - /// indica che è richiesto forzatamente reset contapezzi - /// - protected bool forcePzReset = false; - - /// - /// indica che è richiesto forzatamente reset contapezzi - /// - protected DateTime forcePzResetUntil = DateTime.Now.AddMinutes(-1); - - /// - /// DEADBAND globale se impostata (es x gestire variazioni minime valori FluxLog da inviare...) - /// - protected float GLOBAL_DBAND = 0; - - /// - /// Determina se siano gestite le ricette - /// - protected bool hasRecipe = false; - - /// - /// Array dei contatori x segnali blinking - /// - protected int[] i_counters; - - /// - /// Indica impianto IN SETUP (fino a quando SMETTE di esserlo...) - /// - protected bool inSetup = false; - - /// - /// ultimo tentativo connessione... - /// - protected DateTime lastConnectTry; - - /// - /// Dizionario ULTIMI valori impostati x produzione - /// - protected Dictionary lastProdData = new Dictionary(); - - /// - /// Ultimo invio contapezzi (x invio delayed) - /// - protected DateTime lastPzCountSend; - - /// - /// Dizionario ultimi valori (string) delle TSS - /// - protected Dictionary LastTSS = new Dictionary(); - - /// - /// Dizionario ultimi valori (string) delle TSS - /// - protected Dictionary LastTSSSend = new Dictionary(); - - /// - /// Dizionario ultimi valori (double) delle TSVC - /// - protected Dictionary LastTSVC = new Dictionary(); - - /// - /// Ultima registrazione warning x ODL mancante (x scrivere solo ogni 15 secondi) - /// - protected DateTime lastWarnODL; - - /// - /// ultima data-ora invio parametri write x ribadire status - /// - protected DateTime lastWriteParamsUpsert = DateTime.Now; - - /// - /// Separatore linea (tipicamente x commenti) - /// - protected string lineSep = "--------------------------"; - - /// - /// Elenco parametri calcolati da inviare alla macchina (es ricetta con traduzione, RAMA/TFT) - /// - protected List list2Write = new List(); - - /// - /// Elenco delle eventuali condizioni di veto conditions attive - /// - protected List ListVetoCond = new List(); - - /// - /// Num massimo di errori in funzionalità check alive - /// - protected int maxAliveErrors = utils.CRI("maxAliveErrors"); - - /// - /// Soglia massima errori prima della disconnessione automatica in check - /// - protected int maxErroriCheck = utils.CRI("maxErroriCheck"); - - /// - /// Quantità massima per singola ricetta (per determinare num ricette da inviare) - /// - protected int maxQtyPerFile = 0; - - /// - /// Num massimo di errori di rete read (dal PLC) - /// - protected int maxReadErrors = utils.CRI("maxReadErrors"); - - /// - /// Periodo massimo (in sec) per letture dati in mancanza di eventi di aggiornamento - /// - protected int MaxSecReload = 120; - - /// - /// Num massimodi errori di rete send al server - /// - protected int maxSendErrors = utils.CRI("maxSendErrors"); - - /// - /// Numero massimo di tentativi x test ping preliminare - /// - protected int maxTryPing = 1; - - protected string mem2trace = ""; - - /// - /// indica se serva refresh parametri e quindi PLC... - /// - protected bool needRefresh = true; - - /// - /// Indica se usare la parte numerica di un articolo come codice INT - /// - protected bool numArtCharTrim = false; - - /// - /// Timeout x ping al server - /// - protected int pingServerMsTimeout = utils.CRI("PingMsTimeout"); - - /// - /// DataOra avvio Programma x check avvio - /// - protected DateTime prgStarted = DateTime.Now; - - /// - /// Ritardo minimo x invio contapezzi - /// - protected int pzCountDelay = 2500; - - /// - /// Periodo di campionamento x refresh info - /// - protected int samplePeriod = 1000; - - /// - /// MsSample Period base x campionamenti tpo OCP-UA - /// - protected int samplePeriodBase = 600; - - /// - /// Dizionario di VC da trattare come TimeSeries (con conf decodificata + processing successivo...) - /// - protected Dictionary TSVC_Data = new Dictionary(); - - /// - /// Indica se usare archivio locale ricette vs scarico http/REST - /// - protected bool useLocalRecipe = true; - - /// - /// Dizionario di VARIABILI da trattare come eventi (da inviare quando cambiano oppure a - /// scadenza periodo...) - /// - protected Dictionary VarArray = new Dictionary(); - - /// - /// Dizionario dei divieti di invio x ogni counter gestito - /// - protected Dictionary VetoCounterSend = new Dictionary(); - - /// - /// Durata in secondi del divieto accodamento segnali IN alla fase di startup - /// - protected int vetoQueueIn = 10; - - /// - /// Periodo di veto prima di invio nuova conferma dei valori write correnti, default ogni 5 min - /// - protected double vetoSendWriteUpsert = 1; - - /// - /// Periodo wathdog di default (2 sec se non specificato) - /// - protected int watchDogPeriod = 2; + protected CommunicationService commService; + protected MachineCommunicationService machineCommService; #endregion Protected Fields @@ -4362,14 +3913,14 @@ namespace IOB_WIN_FORM.Iob var rawData = redisMan.getRSV(redKeyFLog); if (!string.IsNullOrEmpty(rawData)) { - answ = JsonConvert.DeserializeObject>(rawData); + answ = JsonDeserialize>(rawData); } return answ; } set { string redKeyFLog = redisMan.redHash($"IOB:CurrData:{IOBConfFull.General.FilenameIOB}:LogFile:FluxLog"); - string fluxLogRaw = JsonConvert.SerializeObject(value); + string fluxLogRaw = JsonSerialize(value); redisMan.setRSV(redKeyFLog, fluxLogRaw); } } @@ -4525,7 +4076,7 @@ namespace IOB_WIN_FORM.Iob { try { - answ = JsonConvert.DeserializeObject>(rawData); + answ = JsonDeserialize>(rawData); lgInfo($"Rilettura status POdlSentFileArch: trovati {answ.Count} record"); } catch (Exception exc) @@ -4537,7 +4088,7 @@ namespace IOB_WIN_FORM.Iob } set { - string rawVal = JsonConvert.SerializeObject(value); + string rawVal = JsonSerialize(value); string redKey = GetPOdlSentKey(); redisMan.setRSV(redKey, rawVal); lgDebug($"Salvataggio status POdlSentFileArch | {value.Count} record"); @@ -5017,87 +4568,7 @@ namespace IOB_WIN_FORM.Iob #region Protected Methods - /// - /// Decodifica file MAP (caso .bit) - /// - /// - /// - /// indirizzo Byte: indirizzo di partenza memoria - /// dimensione singolo slot in byte - /// indirizzo bit: numero riga x calcolo indice bit - /// - protected static otherData decodeBitData(string linea, char separator, int ByteNum, int memSize, int BitNum) - { - if (linea != null) - { - string[] valori = linea.Split(separator); - int shift = 0; - try - { - shift = Convert.ToInt32(valori[0]) - 1; - } - catch - { } - int resto = 0; - Math.DivRem(BitNum, 8, out resto); - string memAddr = string.Format("{0}.{1}", ByteNum + shift * memSize, resto); - return new otherData(valori[0], memAddr, valori[1].Trim(), valori[2].Trim()); - } - else - { - return null; - } - } - /// - /// Decodifica file MAP generico - /// - /// - /// - /// - /// - /// - /// - protected static otherData decodeOtherData(string linea, char separator, string memPre, int baseAddr, int memSize) - { - if (linea != null) - { - string[] valori = linea.Split(separator); - int shift = 0; - try - { - shift = Convert.ToInt32(valori[0]) - 1; - } - catch - { } - string memAddr = string.Format("{0}{1}", memPre, baseAddr + shift * memSize); - return new otherData(valori[0], memAddr, valori[1].Trim(), valori[2].Trim()); - } - else - { - return null; - } - } - - protected static long GetObjectSize(object genObj, bool isSerializable) - { - long result = 0; - if (isSerializable) - { - using (var stream = new MemoryStream()) - { - var formatter = new BinaryFormatter(); - formatter.Serialize(stream, genObj); - result = stream.Length; - } - } - else - { - string rawVal = System.Text.Json.JsonSerializer.Serialize(genObj, options); - result = rawVal.Length; - } - return result; - } /// /// Decodifica valore della coda IN nel formato sendEnab[0]=dtEve sendEnab[1]=valore sendEnab[2]=counter @@ -5128,10 +4599,10 @@ namespace IOB_WIN_FORM.Iob { JobTaskData jobTask = new JobTaskData(codTav, newReq); // accodo richiesta serializzata - string serVal = JsonConvert.SerializeObject(jobTask); - QueueSrvReq.Enqueue(serVal); + string serVal = JsonSerialize(jobTask); + QHelp.QueueSrvReq.Enqueue(serVal); // loggo! - lgDebug($"[QUEUE] | QueueSrvReq len: {QueueSrvReq.Count}"); + lgDebug($"[QUEUE] | QHelp.QueueSrvReq len: {QHelp.QueueSrvReq.Count}"); } /// @@ -5143,10 +4614,10 @@ namespace IOB_WIN_FORM.Iob { JobTaskData jobTask = new JobTaskData(codTav, rawData); // accodo richiesta serializzata - string serVal = JsonConvert.SerializeObject(jobTask); - QueueSrvResp.Enqueue(serVal); + string serVal = JsonSerialize(jobTask); + QHelp.QueueSrvResp.Enqueue(serVal); // loggo! - lgDebug($"[QUEUE] | QueueSrvResp len: {QueueSrvResp.Count}"); + lgDebug($"[QUEUE] | QHelp.QueueSrvResp len: {QHelp.QueueSrvResp.Count}"); } /// @@ -5596,7 +5067,8 @@ namespace IOB_WIN_FORM.Iob } var rawData = HttpService.CallUrlGet(url2call); // deserializzo e recupero KVP... - var dictArtSrv = JsonConvert.DeserializeObject>(rawData); + var dictArtSrv = JsonDeserialize>(rawData); + // se fosse una chiamata con valore vuoto --> salvo intera tabella... if (string.IsNullOrEmpty(value)) { @@ -5766,7 +5238,7 @@ namespace IOB_WIN_FORM.Iob item.updStatusVal(i, (uint)(item.alarmsMask[i] & currStatus)); // salvo in redis... string alarmHash = redisMan.redHash($"IOB:ALARM_STATUS:{IOBConfFull.General.FilenameIOB}:{item.memAddr}"); - string rawAlarms = JsonConvert.SerializeObject(item.alarmsState); + string rawAlarms = JsonSerialize(item.alarmsState); redisMan.setRSV(alarmHash, rawAlarms); } else @@ -6118,7 +5590,7 @@ namespace IOB_WIN_FORM.Iob lgInfo("loadMemConf.04"); try { - memMap = JsonConvert.DeserializeObject(jsonData); + memMap = JsonDeserialize(jsonData); } catch (Exception exc) { @@ -6185,7 +5657,7 @@ namespace IOB_WIN_FORM.Iob var rawListPODL = await HttpService.CallUrlAsync(urlGetNextPODL); if (!string.IsNullOrEmpty(rawListPODL)) { - reqPOdlList = JsonConvert.DeserializeObject>(rawListPODL) ?? new List(); + reqPOdlList = JsonDeserialize>(rawListPODL) ?? new List(); } }) .GetAwaiter() @@ -6345,7 +5817,7 @@ namespace IOB_WIN_FORM.Iob string rawData = File.ReadAllText(fileItem); if (!string.IsNullOrEmpty(rawData)) { - var convData = JsonConvert.DeserializeObject>(rawData); + var convData = JsonDeserialize>(rawData); if (convData != null) { list2Send = convData; @@ -6404,16 +5876,15 @@ namespace IOB_WIN_FORM.Iob { try { - writeList = JsonConvert.DeserializeObject>(resp); + writeList = JsonDeserialize>(resp); // se ho da fare chiamo esecuzione.. if (writeList.Count > 0) { foreach (var item in writeList) { - // scrivo in memoria - if (memMap.mMapWrite.ContainsKey(item.uid)) + // scrivo in memoria tramite servizio + if (machineCommService.WriteToMemMap(item.uid, item.reqValue)) { - memMap.mMapWrite[item.uid].value = item.reqValue; currOut = $" | Parameter {item.uid} | {item.value} --> {item.reqValue}"; // sistemo valori item.value = item.reqValue; @@ -6423,6 +5894,7 @@ namespace IOB_WIN_FORM.Iob // salvo in lista da ritrasmettere updatedPar.Add(item); } + else { currOut = $" | Error: parameter {item.uid} not found"; @@ -6434,7 +5906,7 @@ namespace IOB_WIN_FORM.Iob // richiamo scrittura parametri su PLC plcWriteParams(ref updatedPar); // invio su cloud parametri! - string rawData = JsonConvert.SerializeObject(updatedPar); + string rawData = JsonSerialize(updatedPar); HttpService.CallUrl($"{urlUpdateWriteParams}", rawData); lgInfo($"Notifica a server scrittura {updatedPar.Count} parametri"); } @@ -6585,12 +6057,12 @@ namespace IOB_WIN_FORM.Iob { DateTime adesso = DateTime.Now; // verifico veto sync ricette (x non ripetere troppo spesso) - if (adesso > dtVetoCheckSyncRecipe) + if (adesso > DtHelp.VetoCheckSyncRecipe) { // effettua sync eventuali NUOVI file ricette bool okSync = RecipeDoSyncRecipe(); // imposto veto a 1h... - dtVetoCheckSyncRecipe = adesso.AddHours(1); + DtHelp.VetoCheckSyncRecipe = adesso.AddHours(1); } } return answ; @@ -6637,7 +6109,8 @@ namespace IOB_WIN_FORM.Iob // leggo contenuto XML string rawData = File.ReadAllText(recipeFile); // deserializza file XML x recuperare righe consumo - var currRecipe = XmlDataSerializer.Deserialize(rawData); + var currRecipe = XmlDeserialize(rawData); + if (currRecipe != null) { // recupero data-ora ricetta da campo string @@ -6716,7 +6189,7 @@ namespace IOB_WIN_FORM.Iob CurrStatus = "Ricevute", ActionList = stdActList }; - string rawWeek = JsonConvert.SerializeObject(cPerInfo); + string rawWeek = JsonSerialize(cPerInfo); redHashWeek.Add(cWeek, rawWeek); } // salvo in redis... @@ -6725,7 +6198,7 @@ namespace IOB_WIN_FORM.Iob // invio ANCHE in MP-IO l'update delle info... string remUrl = urlSetHashDict; - string dictPayload = JsonConvert.SerializeObject(redHashWeek); + string dictPayload = JsonSerialize(redHashWeek); await HttpService.CallUrlAsync(remUrl, dictPayload); } } @@ -7350,7 +6823,7 @@ namespace IOB_WIN_FORM.Iob } // invio e salvo... string remUrl = urlSaveMachIobConf; - string dictPayload = JsonConvert.SerializeObject(currDict); + string dictPayload = JsonSerialize(currDict); await HttpService.CallUrlAsync(remUrl, dictPayload); lgTrace("Invio MachineConf effettuato"); } @@ -7500,7 +6973,7 @@ namespace IOB_WIN_FORM.Iob if (!string.IsNullOrEmpty(rawVal)) { // provo a convertire - var lastState = JsonConvert.DeserializeObject(rawVal); + var lastState = JsonDeserialize(rawVal); if (lastState != null && lastState.Length > 0) { item.loadPrev(lastState); @@ -7556,7 +7029,7 @@ namespace IOB_WIN_FORM.Iob lgDebug($"setupMemMap | trovati {memMap.mMapWrite.Count} parametri Write"); if (utils.CRB("verbose")) { - string rawMemConf = JsonConvert.SerializeObject(memMap, Formatting.Indented); + string rawMemConf = JsonSerialize(memMap, Formatting.Indented); lgDebug($"setupMemMap | configurazione memoria R/W:{Environment.NewLine}{rawMemConf}"); } // se ho variabili read --> genero dati TSVC... @@ -7596,7 +7069,7 @@ namespace IOB_WIN_FORM.Iob if (memMap != null) { // invio su cloud conf memoria... - string rawData = JsonConvert.SerializeObject(memMap, Formatting.Indented); + string rawData = JsonSerialize(memMap, Formatting.Indented); // controllo ping al server... if (serverOk) { @@ -7672,7 +7145,7 @@ namespace IOB_WIN_FORM.Iob } // invio su cloud parametri SE sono connesso alla macchina... in pratica reset parametri... string tipoCall = urlSaveAllParams; - rawData = JsonConvert.SerializeObject(allParam, Formatting.Indented); + rawData = JsonSerialize(allParam, Formatting.Indented); if (serverOk) { // verifica se sia un IOB "parziale" --> salva solo update ai parametri @@ -8552,11 +8025,7 @@ namespace IOB_WIN_FORM.Iob #region Private Fields - private static readonly JsonSerializerOptions options = new JsonSerializerOptions - { - ReferenceHandler = ReferenceHandler.IgnoreCycles, - WriteIndented = false // Optional: set to true for pretty-printing - }; + /// /// Oggetto logger della classe @@ -8877,7 +8346,7 @@ namespace IOB_WIN_FORM.Iob bool fatto = false; if (Directory.Exists(folderPath)) { - fatto = fileMover.zippaDirectory(folderPath, zipName); + fatto = FileMover.zippaDirectory(folderPath, zipName); // se sent elimino vecchia directory... if (fatto) { @@ -9207,20 +8676,20 @@ namespace IOB_WIN_FORM.Iob lgInfo($"Chiamata di plcWriteParams da processMem2Write: {updatedPar.Count} updatedPar"); plcWriteParams(ref updatedPar); // invio su cloud parametri! - string rawData = JsonConvert.SerializeObject(updatedPar); + string rawData = JsonSerialize(updatedPar); HttpService.CallUrlPost($"{urlUpdateWriteParams}", rawData); lgInfo($"Notificato a server scrittura {updatedPar.Count} parametri"); } else { // se scaduto tempo da ultimo invio... e ho valori - if (currWritePar.Count > 0 && (lastWriteParamsUpsert.AddMinutes(vetoSendWriteUpsert) < adesso)) + if (currWritePar.Count > 0 && (DtHelp.lastWriteParamsUpsert.AddMinutes(vetoSendWriteUpsert) < adesso)) { // invio su cloud parametri! - string rawData = JsonConvert.SerializeObject(currWritePar); + string rawData = JsonSerialize(currWritePar); var res = HttpService.CallUrlPost($"{urlUpdateWriteParams}", rawData); lgInfo($"Reinviato a server stato {updatedPar.Count} parametri WRITE"); - lastWriteParamsUpsert = adesso; + DtHelp.lastWriteParamsUpsert = adesso; } } } @@ -9343,7 +8812,7 @@ namespace IOB_WIN_FORM.Iob string rawConfFile = File.ReadAllText(confSetupPath); if (!string.IsNullOrEmpty(rawConfFile)) { - currConf = JsonConvert.DeserializeObject(rawConfFile); + currConf = JsonDeserialize(rawConfFile); if (currConf != null) { addHeader = currConf.addHeader; @@ -9505,7 +8974,7 @@ namespace IOB_WIN_FORM.Iob Dictionary currDict = redisMan.redGetHashDict(fullKey); // invio ANCHE in MP-IO l'update delle info... string remUrl = urlSetHashDict; - string dictPayload = JsonConvert.SerializeObject(currDict); + string dictPayload = JsonSerialize(currDict); await HttpService.CallUrlAsync(remUrl, dictPayload); //await callUrlWithPayloadAsync(remUrl, dictPayload, true); //await callUrlWithPayloadAsync(remUrl, dictPayload, false); @@ -9527,7 +8996,8 @@ namespace IOB_WIN_FORM.Iob foreach (var rawJob in listaValori) { // deserializzo... - JobTaskData jobTask = JsonConvert.DeserializeObject(rawJob); + JobTaskData jobTask = JsonDeserialize(rawJob); + // ora chiamo la cancellazione dei task eseguiti... var taskDict = JobTaskData.TaskDict(jobTask.RawData); foreach (var item in taskDict) @@ -9547,10 +9017,10 @@ namespace IOB_WIN_FORM.Iob { // se non ho veto task2exe DateTime adesso = DateTime.Now; - if (adesso > dtVetoTask2Exe) + if (adesso > DtHelp.dtVetoTask2Exe) { // blocco fisso a 5 sec x ora - dtVetoTask2Exe = adesso.AddSeconds(5); + DtHelp.dtVetoTask2Exe = adesso.AddSeconds(5); // recupero elenco delle cose da fare string resp = await getTask2exe(""); // se ho qualcosa --> creo obj e lo accodo... @@ -9576,13 +9046,13 @@ namespace IOB_WIN_FORM.Iob private async Task ServerPutRespAsync() { // verifico SE la coda abbia dei valori... - if (QueueSrvResp.Count > 0) + if (QHelp.QueueSrvResp.Count > 0) { // invio pacchetto di dati (max da conf) for (int i = 0; i < nMaxSend; i++) { // SE ho qualcosa in coda... - if (QueueSrvResp.Count > 0) + if (QHelp.QueueSrvResp.Count > 0) { string currVal = ""; if (MPOnline) @@ -9591,12 +9061,12 @@ namespace IOB_WIN_FORM.Iob { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueSrvResp.Count > maxJsonData) + if (QHelp.QueueSrvResp.Count > maxJsonData) { // prendoi primi maxJsonDataValori for (int j = 0; j < maxJsonData; j++) { - QueueSrvResp.TryDequeue(out currVal); + QHelp.QueueSrvResp.TryDequeue(out currVal); listaValori.Add(currVal); } await SendTaskResult(listaValori); @@ -9604,10 +9074,10 @@ namespace IOB_WIN_FORM.Iob else { // invio in blocco - listaValori = QueueSrvResp.ToList(); + listaValori = QHelp.QueueSrvResp.ToList(); await SendTaskResult(listaValori); // svuoto! - QueueSrvResp = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueServResp", IOBConfFull.General.EnabRedisQue, redisMan); + QHelp.QueueSrvResp = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueServResp", IOBConfFull.General.EnabRedisQue, redisMan); } } else @@ -9653,22 +9123,22 @@ namespace IOB_WIN_FORM.Iob { string codIob = IOBConfFull.General.FilenameIOB; bool useRedis = IOBConfFull.General.EnabRedisQue; - QueueIN.Dispose(); - QueueIN = new DataQueue(codIob, "QueueIN", useRedis, redisMan); - QueueSrvResp.Dispose(); - QueueSrvResp = new DataQueue(codIob, "QueueServResp", useRedis, redisMan); + QHelp.QueueIN.Dispose(); + QHelp.QueueIN = new DataQueue(codIob, "QueueIN", useRedis, redisMan); + QHelp.QueueSrvResp.Dispose(); + QHelp.QueueSrvResp = new DataQueue(codIob, "QueueServResp", useRedis, redisMan); // no coda redis - QueueAlarm = new DataQueue(codIob, "QueueAlarm", false, redisMan); - QueueFLog = new DataQueue(codIob, "QueueFLog", false, redisMan); - QueueMessages = new DataQueue(codIob, "QueueMessages", false, redisMan); - QueuePing = new DataQueue(codIob, "QueuePing", false, redisMan); - QueueRawTransf = new DataQueue(codIob, "QueueRawTransf", false, redisMan); - QueueSrvReq = new DataQueue(codIob, "QueueServReq", false, redisMan); - QueueULog = new DataQueue(codIob, "QueueULog", false, redisMan); + QHelp.QueueAlarm = new DataQueue(codIob, "QueueAlarm", false, redisMan); + QHelp.QueueFLog = new DataQueue(codIob, "QueueFLog", false, redisMan); + QHelp.QueueMessages = new DataQueue(codIob, "QueueMessages", false, redisMan); + QHelp.QueuePing = new DataQueue(codIob, "QueuePing", false, redisMan); + QHelp.QueueRawTransf = new DataQueue(codIob, "QueueRawTransf", false, redisMan); + QHelp.QueueSrvReq = new DataQueue(codIob, "QueueServReq", false, redisMan); + QHelp.QueueULog = new DataQueue(codIob, "QueueULog", false, redisMan); } // imposto contatori blink a zero... i_counters = new int[32]; - lastPeriodicLog = DateTime.Now; + DtHelp.lastPeriodicLog = DateTime.Now; // fix parametri generali... pzCountDelay = IOBConfFull.Device.PzCountDelay; @@ -9692,9 +9162,9 @@ namespace IOB_WIN_FORM.Iob private async Task SvuotaCodaContapezziAsync() { // verifico non sia impedita la gestione contapezzi (per evitare invio su macchine lente nel reset all'attrezzaggio) - if (DateTime.Now <= vetoQueuePzCount) + if (DateTime.Now <= DtHelp.vetoQueuePzCount) { - lgInfo($"Ciclo SvuotaCodaContapezziAsync DISABILITATO fino a {vetoQueuePzCount}"); + lgInfo($"Ciclo SvuotaCodaContapezziAsync DISABILITATO fino a {DtHelp.vetoQueuePzCount}"); } else { @@ -9750,7 +9220,7 @@ namespace IOB_WIN_FORM.Iob { bool sendOnMachineOff = false; // controllo se è passato oltre watchdog e non ho inviato nulla --> RE-INVIO (ultimo inviato)!!!! - if (DateTime.Now.Subtract(lastWatchDog).TotalSeconds > IOBConfFull.General.WatchDogSec) + if (DateTime.Now.Subtract(DtHelp.lastWatchDog).TotalSeconds > IOBConfFull.General.WatchDogSec) { string wdStatus = "elapsed"; string sVal = string.Format("[WDST]{0}", wdStatus); @@ -9764,18 +9234,18 @@ namespace IOB_WIN_FORM.Iob trackDynData("WDST", wdStatus); } } - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; sendOnMachineOff = true; lgInfo("Impostato sendOnMachineOff a true"); } // verifico SE la coda abbia dei valori... - if (QueueFLog.Count > 0) + if (QHelp.QueueFLog.Count > 0) { // invio pacchetto di dati (max da conf) for (int i = 0; i < nMaxSend; i++) { // SE ho qualcosa in coda... - if (QueueFLog.Count > 0) + if (QHelp.QueueFLog.Count > 0) { string currVal = ""; if (MPOnline) @@ -9783,39 +9253,39 @@ namespace IOB_WIN_FORM.Iob if (IobOnline || sendOnMachineOff) { // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueFLog.Count > 1) + if (QHelp.QueueFLog.Count > 1) { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueFLog.Count > maxJsonData) + if (QHelp.QueueFLog.Count > maxJsonData) { // prendoi primi maxJsonDataValori for (int j = 0; j < maxJsonData; j++) { - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); listaValori.Add(currVal); } await sendDataBlock(urlType.FLog, listaValori); - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } else { // invio in blocco - listaValori = QueueFLog.ToList(); + listaValori = QHelp.QueueFLog.ToList(); // invio await sendDataBlock(urlType.FLog, listaValori); // svuoto! NO redis - QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueFLog", false, redisMan); - //QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueFLog", IOBConfFull.General.EnabRedisQue, redisMan); - lastWatchDog = DateTime.Now; + QHelp.QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueFLog", false, redisMan); + //QHelp.QueueFLog = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueFLog", IOBConfFull.General.EnabRedisQue, redisMan); + DtHelp.lastWatchDog = DateTime.Now; } } else { // INVIO SINGOLO...!!! - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); await sendToMoonPro(urlType.FLog, currVal); - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } } else @@ -9843,13 +9313,13 @@ namespace IOB_WIN_FORM.Iob { bool fatto = false; // verifico SE la coda abbia dei valori... - if (QueueRawTransf.Count > 0) + if (QHelp.QueueRawTransf.Count > 0) { // invio pacchetto di dati (max da conf) for (int i = 0; i < nMaxSend; i++) { // SE ho qualcosa in coda... - if (QueueRawTransf.Count > 0) + if (QHelp.QueueRawTransf.Count > 0) { string currVal = ""; if (MPOnline || force) @@ -9858,12 +9328,12 @@ namespace IOB_WIN_FORM.Iob { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueRawTransf.Count > maxJsonData) + if (QHelp.QueueRawTransf.Count > maxJsonData) { // prendoi primi maxJsonDataValori for (int j = 0; j < maxJsonData; j++) { - QueueRawTransf.TryDequeue(out currVal); + QHelp.QueueRawTransf.TryDequeue(out currVal); listaValori.Add(currVal); } fatto = await sendDataBlock(urlType.RawTransf, listaValori, force); @@ -9871,13 +9341,13 @@ namespace IOB_WIN_FORM.Iob else { // invio in blocco - listaValori = QueueRawTransf.ToList(); + listaValori = QHelp.QueueRawTransf.ToList(); // invio fatto = await sendDataBlock(urlType.RawTransf, listaValori, force); if (fatto) { // svuoto se ha okReport! - QueueRawTransf = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueRawTransf", false, redisMan); + QHelp.QueueRawTransf = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueRawTransf", false, redisMan); } } } @@ -9906,13 +9376,13 @@ namespace IOB_WIN_FORM.Iob private async Task SvuotaCodaULogAsync() { // verifico SE la coda abbia dei valori... - if (QueueULog.Count > 0) + if (QHelp.QueueULog.Count > 0) { // invio pacchetto di dati (max da conf) for (int i = 0; i < nMaxSend; i++) { // SE ho qualcosa in coda... - if (QueueULog.Count > 0) + if (QHelp.QueueULog.Count > 0) { string currVal = ""; if (MPOnline) @@ -9921,12 +9391,12 @@ namespace IOB_WIN_FORM.Iob { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueULog.Count > maxJsonData) + if (QHelp.QueueULog.Count > maxJsonData) { // prendoi primi maxJsonDataValori for (int j = 0; j < maxJsonData; j++) { - QueueULog.TryDequeue(out currVal); + QHelp.QueueULog.TryDequeue(out currVal); listaValori.Add(currVal); } await sendDataBlock(urlType.ULog, listaValori); @@ -9934,11 +9404,11 @@ namespace IOB_WIN_FORM.Iob else { // invio in blocco - listaValori = QueueULog.ToList(); + listaValori = QHelp.QueueULog.ToList(); // invio await sendDataBlock(urlType.ULog, listaValori); // svuoto! - QueueULog = new DataQueue(IOBConfFull.General.FilenameIOB, "QueueULog", false, redisMan); + QHelp.QueueULog = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueueULog", false, redisMan); } } else @@ -9963,14 +9433,14 @@ namespace IOB_WIN_FORM.Iob { // Log se lo stato è cambiato DateTime adesso = DateTime.Now; - if (IobOnline != newStatus || adesso.Subtract(lastIobStatusDisplUpdate).TotalMilliseconds > (baseUtils.nextPauseSendMSec * 10)) + if (IobOnline != newStatus || adesso.Subtract(DtHelp.lastIobStatusDisplUpdate).TotalMilliseconds > (baseUtils.nextPauseSendMSec * 10)) { lgInfo(newStatus ? "IOB ONLINE for server MP/IO" : "IOB OFFLINE for server MP/IO"); IobOnline = newStatus; - lastIobStatusDisplUpdate = adesso; + DtHelp.lastIobStatusDisplUpdate = adesso; if (newStatus) { - lastIobOnline = adesso; + DtHelp.lastIobOnline = adesso; parentForm.commSrvActive = 2; // Stato Online } else @@ -9981,7 +9451,7 @@ namespace IOB_WIN_FORM.Iob // Imposto il veto per il prossimo controllo (se ConnOk + rapido sennò meno rapido) var msWait = baseUtils.nextPauseSendMSec * (connectionOk ? 12 : 150); - dtVetoCheckIOB = adesso.AddMilliseconds(msWait); + DtHelp.VetoCheckIOB = adesso.AddMilliseconds(msWait); } #endregion Private Methods diff --git a/IOB-WIN-FORM/Iob/PingWatchDog.cs b/IOB-WIN-FORM/Iob/PingWatchDog.cs index 56843e48..5b16a6a4 100644 --- a/IOB-WIN-FORM/Iob/PingWatchDog.cs +++ b/IOB-WIN-FORM/Iob/PingWatchDog.cs @@ -1,5 +1,8 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Data; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Diagnostics; @@ -28,19 +31,19 @@ namespace IOB_WIN_FORM.Iob lgInfo("NEW IobPing (WatchDog)"); // init datetime counters DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; vetoCheckStatus = adesso; // 2023.09.05 imposto anche primo ping e check disconnected... - lastPING = adesso; - lastDisconnCheck = adesso; + DtHelp.lastPING = adesso; + DtHelp.lastDisconnCheck = adesso; PoweroffTimeoutSec = IOBConfFull.Device.PoweroffTimeOutSec; // imposto i valori da inviare al controllo stato... bInOff = IOBConfFull.Special.PingConf.B_PowerOff; bInOn = IOBConfFull.Special.PingConf.B_PowerOn; vetoCheckSec = IOBConfFull.Special.PingConf.VetoCheckSec; // fix coda ping - QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QueuePing", false, redisMan); + QHelp.QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueuePing", false, redisMan); lgDebug($"L'adapter effettuera' PING di controllo all'indirizzo {IOBConfFull.Device.Connect.IpAddr} per forzare stato poweroff dopo {PoweroffTimeoutSec} sec"); } @@ -55,7 +58,7 @@ namespace IOB_WIN_FORM.Iob { // effettuo check ping! DateTime adesso = DateTime.Now; - var lastCheck = lastPING < lastReadPLC ? lastReadPLC : lastReadPLC; + var lastCheck = DtHelp.lastPING < DtHelp.lastReadPLC ? DtHelp.lastReadPLC : DtHelp.lastReadPLC; if (adesso.Subtract(lastCheck).TotalSeconds >= PoweroffTimeoutSec) { // gestione invio anche in caso di disconnessione @@ -75,8 +78,8 @@ namespace IOB_WIN_FORM.Iob { accodaSigIN(ref currDispData); // reset last ping... - lastPING = DateTime.Now; - lastReadPLC = DateTime.Now; + DtHelp.lastPING = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } } @@ -93,22 +96,22 @@ namespace IOB_WIN_FORM.Iob sw.Start(); byte[] MemBlock = new byte[2]; // faccio comunque ping se non ne ho collezionati a sufficienza... - if (QueuePing.Count < maxQueuePing) + if (QHelp.QueuePing.Count < maxQueuePing) { // in primis salvo data ping comunque... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // salvo esito ping bool pingOK = testPingMachine == IPStatus.Success; addTest(pingOK); } - if (adesso.Subtract(lastPING).TotalSeconds >= vetoCheckSec) + if (adesso.Subtract(DtHelp.lastPING).TotalSeconds >= vetoCheckSec) { try { currDispData.semIn = Semaforo.SV; // in primis salvo data ping comunque... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // salvo esito ping bool pingOK = testPingMachine == IPStatus.Success; addTest(pingOK); @@ -117,8 +120,8 @@ namespace IOB_WIN_FORM.Iob if (pingStatusOk()) { connectionOk = true; - lastReadPLC = DateTime.Now; - lastWatchDog = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } else { @@ -154,9 +157,9 @@ namespace IOB_WIN_FORM.Iob base.startAdapter(resetQueue); // 2023.09.05 imposto anche primo ping e check disconnected... DateTime adesso = DateTime.Now; - lastWatchDog = adesso; - lastReadPLC = adesso; - lastDisconnCheck = adesso; + DtHelp.lastWatchDog = adesso; + DtHelp.lastReadPLC = adesso; + DtHelp.lastDisconnCheck = adesso; // faccio un primo check POST ritardo tryConnect(); } @@ -171,7 +174,7 @@ namespace IOB_WIN_FORM.Iob if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (doLog) { @@ -179,7 +182,7 @@ namespace IOB_WIN_FORM.Iob } lgDebug("PING: tryConnect step 04"); - lgDebug("PING: Reset QueuePing"); + lgDebug("PING: Reset QHelp.QueuePing"); Stopwatch sw = new Stopwatch(); sw.Start(); @@ -192,7 +195,7 @@ namespace IOB_WIN_FORM.Iob if (pingStatusOk()) { // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; connectionOk = true; queueInEnabCurr = true; lgInfo("PING OK"); @@ -242,14 +245,14 @@ namespace IOB_WIN_FORM.Iob if (B_input == 0 && pingOk) { B_input = bInOn; - QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QueuePing", false, redisMan); - lgTrace($"QueuePing resetted on addTest"); + QHelp.QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueuePing", false, redisMan); + lgTrace($"QHelp.QueuePing resetted on addTest"); } - QueuePing.Enqueue($"{score}"); - while (QueuePing.Count > maxQueuePing) + QHelp.QueuePing.Enqueue($"{score}"); + while (QHelp.QueuePing.Count > maxQueuePing) { string res = ""; - QueuePing.TryDequeue(out res); + QHelp.QueuePing.TryDequeue(out res); } } @@ -262,10 +265,10 @@ namespace IOB_WIN_FORM.Iob protected bool pingStatusOk() { bool answ = true; - long numVal = QueuePing.Count; + long numVal = QHelp.QueuePing.Count; if (numVal > maxQueuePing / 2) { - var listaValori = QueuePing.ToList(); + var listaValori = QHelp.QueuePing.ToList(); long numOk = listaValori.Where(x => x == "1").Count(); long numKo = numVal - numOk; answ = numOk >= numKo; diff --git a/IOB-WIN-FORM/Iob/Simula.cs b/IOB-WIN-FORM/Iob/Simula.cs index 992dd3ec..5a7f0fc9 100644 --- a/IOB-WIN-FORM/Iob/Simula.cs +++ b/IOB-WIN-FORM/Iob/Simula.cs @@ -1,6 +1,8 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using System; @@ -58,27 +60,22 @@ namespace IOB_WIN_FORM.Iob #endregion Public Fields - #region Private Fields for Dirty Check - private int lastSentPzCount = -1; - private DateTime lastBitmapDecodeTime = DateTime.MinValue; - #endregion - #region Public Constructors public Simula(AdapterForm caller, IobConfTree IobConfFull) : base(caller, IobConfFull) { // jitter di avvio per disallineare le istanze nella VM Random startRnd = new Random(); - int startDelay = startRnd.Next(0, 5000); + int startDelay = startRnd.Next(0, 200); Thread.Sleep(startDelay); // gestione invio ritardato contapezzi DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; - lastEvCheck = adesso; - lastSimData = adesso; - lastRedDuration = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; + DtHelp.lastEvCheck = adesso; + DtHelp.lastSimData = adesso; + DtHelp.lastRedDuration = adesso; // abilito subito scrittura coda IN queueInEnabCurr = true; // setup allarmi simulati @@ -93,13 +90,13 @@ namespace IOB_WIN_FORM.Iob { int basePeriod = 0; int.TryParse(IOBConfFull.OptParGet("PER_BASE"), out basePeriod); - + // Applicazione Jitter sui periodi per evitare sincronizzazione tra VM Random rnd = new Random(); // Aggiungiamo un rumore del +/- 15% e un jitter extra - double noiseFactor = 0.85 + (rnd.NextDouble() * 0.30); + double noiseFactor = 0.85 + (rnd.NextDouble() * 0.30); periodoMSec = (int)(basePeriod * noiseFactor); - + // Assicuriamo un minimo di jitter per evitare che periodi simili si allineino periodoMSec += rnd.Next(1, 500); } @@ -152,28 +149,6 @@ namespace IOB_WIN_FORM.Iob // simulazione processo FTP (Cimolai) - FIXME TODO DeleteME ProcessDataSync(); } - // carica conf - try - { - // Invece di bloccare il costruttore con .GetAwaiter().GetResult(), - // avviamo il carico in modo "fire-and-forget" controllato. - // Questo evita il context switch pesante durante l'inizializzazione. - _ = Task.Run(async () => - { - try - { - await Simula_Load(adesso); - } - catch (Exception ex) - { - lgError($"Errore in Simula_Load (background): {ex.Message}"); - } - }); - } - catch (Exception ex) - { - lgError($"Errore nel lancio del task Simula_Load: {ex.Message}"); - } } #endregion Public Constructors @@ -402,7 +377,7 @@ namespace IOB_WIN_FORM.Iob // valore non presente in vers default... se gestito fare override Dictionary outVal = new Dictionary(); // verificare periodo SIM parametri... se passato li invio altrimenti NO... FIX a 20 sec - if (lastSimData.AddSeconds(waitSimPar) < DateTime.Now && memMap != null) + if (DtHelp.lastSimData.AddSeconds(waitSimPar) < DateTime.Now && memMap != null) { Random rnd = new Random(); // controllo conf memorie json (se ci sono...) @@ -484,7 +459,7 @@ namespace IOB_WIN_FORM.Iob } catch { } - lastSimData = DateTime.Now; + DtHelp.lastSimData = DateTime.Now; } return outVal; } @@ -519,8 +494,8 @@ namespace IOB_WIN_FORM.Iob public override async Task InitializeAsync() { await Simula_Load(DateTime.Now); - // attendo altri 50ms - await Task.Delay(50); + // attendo altri 10ms + await Task.Delay(10); } /// @@ -546,7 +521,7 @@ namespace IOB_WIN_FORM.Iob sendDataItemsList(demoItems); // salvo lettura - lastReadPLC = adesso; + DtHelp.lastReadPLC = adesso; lgInfo($"Completato processCustomTaskLF"); } @@ -564,7 +539,7 @@ namespace IOB_WIN_FORM.Iob var currOdl = CurrOdl(); // salvo lettura - lastReadPLC = adesso; + DtHelp.lastReadPLC = adesso; lgInfo($"Completato processCustomTaskMF"); } @@ -573,7 +548,7 @@ namespace IOB_WIN_FORM.Iob /// public override void processVHF() { - if (lastEvCheck.AddMilliseconds(periodoMSec) < DateTime.Now) + if (DtHelp.lastEvCheck.AddMilliseconds(periodoMSec) < DateTime.Now) { // decremento contatore ultimo evento if (bit2 != null) @@ -596,7 +571,7 @@ namespace IOB_WIN_FORM.Iob if (simRS != null) simRS.wait--; - lastEvCheck = DateTime.Now; + DtHelp.lastEvCheck = DateTime.Now; } } @@ -792,21 +767,6 @@ namespace IOB_WIN_FORM.Iob protected bool disableSimStatus = false; - /// - /// ultimo controllo decremento eventi - /// - protected DateTime lastEvCheck; - - /// - /// Ultimo istante in cui sono stati ridotti dati simulazione duration - /// - protected DateTime lastRedDuration; - - /// - /// Ultimo istante in cui sono stati generati dati di simulazione - /// - protected DateTime lastSimData; - /// /// Cartella logfile x test import (tipo Soitaab) /// @@ -971,9 +931,9 @@ namespace IOB_WIN_FORM.Iob item.reqValue = ""; MemBlock = new byte[byteSize]; - serObj = JsonConvert.SerializeObject(item, Formatting.Indented); + serObj = JsonSerialize(item, Formatting.Indented); lgInfo($"Inizio processing plcWriteParams per {currMem.name} | valore richiesto {currMem.value}{Environment.NewLine}---------------UPDATED PARAM---------------{Environment.NewLine}{serObj}{Environment.NewLine}---------------"); - serObj = JsonConvert.SerializeObject(currMem, Formatting.Indented); + serObj = JsonSerialize(currMem, Formatting.Indented); lgInfo($"---------------MEMORY CONTENT---------------{Environment.NewLine}{serObj}{Environment.NewLine}---------------"); lgInfo($"---------------MemBlock data---------------{Environment.NewLine}{BitConverter.ToString(MemBlock)}{Environment.NewLine}--------------- END data ---------------"); @@ -1000,12 +960,12 @@ namespace IOB_WIN_FORM.Iob { try { - // Eseguiamo il lavoro in un Task per non bloccare il thread chiamante, + // Eseguiamo il lavoro in un Task per non bloccare il thread chiamante, // ma evitiamo il .GetAwaiter().GetResult() che causerebbe un blocco sincrono pesante. // In un ambiente WinForms, questo permette al thread di polling di non restare in attesa attiva. _ = Task.Run(async () => { - try + try { // Esecuzione dei task sincroni esistenti iobWriteLocalCSV(); @@ -1049,7 +1009,7 @@ namespace IOB_WIN_FORM.Iob string autoOdlRes = HttpService.CallUrl(urlFixDailyOdl); // salvo lettura - lastReadPLC = adesso; + DtHelp.lastReadPLC = adesso; lgInfo($"Completato processSlowDataRead"); return answ; } @@ -1060,7 +1020,7 @@ namespace IOB_WIN_FORM.Iob /// protected void tryRedDuration(int bit2proc) { - if (lastRedDuration.AddMilliseconds(periodoMSec / 20) < DateTime.Now) + if (DtHelp.lastRedDuration.AddMilliseconds(periodoMSec / 20) < DateTime.Now) { switch (bit2proc) { @@ -1091,7 +1051,7 @@ namespace IOB_WIN_FORM.Iob default: break; } - lastRedDuration = DateTime.Now; + DtHelp.lastRedDuration = DateTime.Now; } } @@ -1100,9 +1060,8 @@ namespace IOB_WIN_FORM.Iob #region Private Fields private List alarmMessages = new List(); - private int currSimAlarmCode = 0; - + private DateTime lastBitmapDecodeTime = DateTime.MinValue; private Random rnd = new Random(); #endregion Private Fields @@ -1457,7 +1416,7 @@ namespace IOB_WIN_FORM.Iob } } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } // provo a fare split ODL... @@ -1473,7 +1432,7 @@ namespace IOB_WIN_FORM.Iob } } } - else if (bit5 != null && bit5.wait <= 0 || tcMan.alarmDelayTC) + else if (bit5 != null && bit5.wait <= 0 || machineCommService.AlarmDelayTC) { // segnalo BIT B_input += (1 << 5); @@ -1609,7 +1568,7 @@ namespace IOB_WIN_FORM.Iob { try { - listaArt = JsonConvert.DeserializeObject>(rawListArt); + listaArt = JsonDeserialize>(rawListArt); okArt = listaArt.Count > 0; } catch (Exception exc) @@ -1625,7 +1584,7 @@ namespace IOB_WIN_FORM.Iob { try { - listaDoss = JsonConvert.DeserializeObject>(rawListDOSS); + listaDoss = JsonDeserialize>(rawListDOSS); okDoss = listaDoss.Count > 0; } catch (Exception exc) @@ -1641,7 +1600,7 @@ namespace IOB_WIN_FORM.Iob { try { - listaPODL = JsonConvert.DeserializeObject>(rawListPODL); + listaPODL = JsonDeserialize>(rawListPODL); okPodl = listaPODL.Count > 0; } catch (Exception exc) @@ -1657,7 +1616,7 @@ namespace IOB_WIN_FORM.Iob { try { - anagLVFasi = JsonConvert.DeserializeObject>(rawLVFasi); + anagLVFasi = JsonDeserialize>(rawLVFasi); dictAF = anagLVFasi.ToDictionary(x => x.value, x => x.label); okLVFasi = listaArt.Count > 0; } @@ -1758,7 +1717,7 @@ namespace IOB_WIN_FORM.Iob { try { - listaArt = JsonConvert.DeserializeObject>(rawListArt); + listaArt = JsonDeserialize>(rawListArt); okArt = listaArt.Count > 0; } catch (Exception exc) @@ -1774,7 +1733,7 @@ namespace IOB_WIN_FORM.Iob { try { - listaDoss = JsonConvert.DeserializeObject>(rawListDOSS); + listaDoss = JsonDeserialize>(rawListDOSS); okDoss = listaDoss.Count > 0; } catch (Exception exc) @@ -1790,7 +1749,7 @@ namespace IOB_WIN_FORM.Iob { try { - listaPODL = JsonConvert.DeserializeObject>(rawListPODL); + listaPODL = JsonDeserialize>(rawListPODL); okPodl = listaPODL.Count > 0; } catch (Exception exc) @@ -1826,7 +1785,7 @@ namespace IOB_WIN_FORM.Iob if (selArt != null && selDoss != null) { // recupero il resultset dei valori FluxLog da caricare - DossierFluxLogDTO resultSet = JsonConvert.DeserializeObject(selDoss.Valore); + DossierFluxLogDTO resultSet = JsonDeserialize(selDoss.Valore); List listFluxLog = resultSet.ODL; // preparo elenco parametri da inviare... @@ -1974,7 +1933,7 @@ namespace IOB_WIN_FORM.Iob if (queueInEnabCurr) { // --> accodo (valore già formattato)! - QueueIN.Enqueue(currVal); + QHelp.QueueIN.Enqueue(currVal); // loggo! lgDebug(string.Format("[QUEUE-IN] {0}", currVal)); counterSigIN++; @@ -2165,7 +2124,7 @@ namespace IOB_WIN_FORM.Iob /// private void sendDataItemsList(List dataItems) { - string rawData = JsonConvert.SerializeObject(dataItems); + string rawData = JsonSerialize(dataItems); HttpService.CallUrlPost($"{urlSaveDataItems}", rawData); } diff --git a/IOB-WIN-FORM/MainForm.cs b/IOB-WIN-FORM/MainForm.cs index 72ec1d1d..6746702c 100644 --- a/IOB-WIN-FORM/MainForm.cs +++ b/IOB-WIN-FORM/MainForm.cs @@ -1,6 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using MathNet.Numerics.Distributions; using Newtonsoft.Json; @@ -845,7 +846,7 @@ namespace IOB_WIN_FORM // salvo! foreach (var item in objFiles.fileList) { - fileMover.obj.salvaFileString(utils.confDir, item.fileName, item.content); + FileMover.obj.salvaFileString(utils.confDir, item.fileName, item.content); } displayTaskAndLog("Download conf files aggiornati"); } diff --git a/IOB-WIN-FORM/packages.config b/IOB-WIN-FORM/packages.config index 093b0468..18b5ff20 100644 --- a/IOB-WIN-FORM/packages.config +++ b/IOB-WIN-FORM/packages.config @@ -16,6 +16,7 @@ + diff --git a/IOB-WIN-FTP/Iob/Ftp.cs b/IOB-WIN-FTP/Iob/Ftp.cs index cc0f6c71..f1e8ea27 100644 --- a/IOB-WIN-FTP/Iob/Ftp.cs +++ b/IOB-WIN-FTP/Iob/Ftp.cs @@ -1,6 +1,11 @@ using EgwProxy.Ftp; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Config.Mem; +using IOB_UT_NEXT.Config.Special; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Data; +using IOB_UT_NEXT.Services.Utility; using MapoSDK; using Newtonsoft.Json; using System; @@ -34,12 +39,12 @@ namespace IOB_WIN_FTP.Iob B_input = 0; // init datetime counters DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; vetoCheckStatus = adesso; // 2023.09.05 imposto anche primo ping e check disconnected... - lastPING = adesso; - lastDisconnCheck = adesso; + DtHelp.lastPING = adesso; + DtHelp.lastDisconnCheck = adesso; var VETO_PING_SEC = getOptPar("VETO_PING_SEC"); if (!string.IsNullOrEmpty(VETO_PING_SEC)) { @@ -324,7 +329,7 @@ namespace IOB_WIN_FTP.Iob } } } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } /// @@ -338,7 +343,7 @@ namespace IOB_WIN_FTP.Iob if (ftpClientMan.IsConfigured) { // salto se fosse attivo il veto ping... - if (lastPING.AddSeconds(vetoPingSec) < adesso) + if (DtHelp.lastPING.AddSeconds(vetoPingSec) < adesso) { // lo stato è come ping machine, x ora puntato a IP unico (WiFi?) byte[] MemBlock = new byte[2]; @@ -346,7 +351,7 @@ namespace IOB_WIN_FTP.Iob { currDispData.semIn = Semaforo.SV; // in primis salvo data ping comunque... - lastPING = adesso; + DtHelp.lastPING = adesso; // salvo esito ping bool pingOK = testPingMachine == IPStatus.Success; @@ -407,8 +412,8 @@ namespace IOB_WIN_FTP.Iob connectionOk = true; } - lastReadPLC = adesso; - lastWatchDog = adesso; + DtHelp.lastReadPLC = adesso; + DtHelp.lastWatchDog = adesso; } else { @@ -439,10 +444,10 @@ namespace IOB_WIN_FTP.Iob base.startAdapter(resetQueue); // 2023.09.05 imposto anche primo ping e check disconnected... DateTime adesso = DateTime.Now; - lastWatchDog = adesso; - //lastPING = adesso; - lastReadPLC = adesso; - lastDisconnCheck = adesso; + DtHelp.lastWatchDog = adesso; + //DtHelp.lastPING = adesso; + DtHelp.lastReadPLC = adesso; + DtHelp.lastDisconnCheck = adesso; // faccio un primo check POST ritardo tryConnect(); } @@ -456,10 +461,8 @@ namespace IOB_WIN_FTP.Iob lgDebug($"FTP: tryConnect step 01 | connectionOk: {connectionOk}"); if (!connectionOk) { - //// resetto coda... - //QueuePing = new DataQueue("000", "QueuePing", false); // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > vetoPingSec) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > vetoPingSec) { if (doLog) { @@ -476,7 +479,7 @@ namespace IOB_WIN_FTP.Iob if (pingStatusOk()) { // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; connectionOk = true; queueInEnabCurr = true; lgInfo("FTP - ping OK"); @@ -641,14 +644,14 @@ namespace IOB_WIN_FTP.Iob if (B_input == 0 && pingOk) { B_input = 1; - QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QueuePing", false, redisMan); - lgTrace($"QueuePing resetted on addTest"); + QHelp.QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueuePing", false, redisMan); + lgTrace($"QHelp.QueuePing resetted on addTest"); } - QueuePing.Enqueue($"{score}"); - while (QueuePing.Count > maxQueuePing) + QHelp.QueuePing.Enqueue($"{score}"); + while (QHelp.QueuePing.Count > maxQueuePing) { string res = ""; - QueuePing.TryDequeue(out res); + QHelp.QueuePing.TryDequeue(out res); } } @@ -938,10 +941,10 @@ namespace IOB_WIN_FTP.Iob private bool pingStatusOk() { bool answ = false; - long numVal = QueuePing.Count; + long numVal = QHelp.QueuePing.Count; if (numVal > maxQueuePing / 2) { - var listaValori = QueuePing.ToList(); + var listaValori = QHelp.QueuePing.ToList(); long numOk = listaValori.Where(x => x == "1").Count(); long numKo = numVal - numOk; answ = numOk >= numKo; diff --git a/IOB-WIN-KAWASAKI/Iob/Kawasaki.cs b/IOB-WIN-KAWASAKI/Iob/Kawasaki.cs index 876916e9..7c0e5d52 100644 --- a/IOB-WIN-KAWASAKI/Iob/Kawasaki.cs +++ b/IOB-WIN-KAWASAKI/Iob/Kawasaki.cs @@ -1,6 +1,8 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using System; using System.Collections.Generic; @@ -21,8 +23,8 @@ namespace IOB_WIN_KAWASAKI.Iob { // gestione invio ritardato contapezzi - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; // init connessione setConnection(); @@ -307,7 +309,7 @@ namespace IOB_WIN_KAWASAKI.Iob // se trova ok thread o almeno kawasaki connesso --> aggiorno ultima lettura if (threadOk || KAWASAKI_ref.IsConnected) { - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } catch @@ -324,28 +326,6 @@ namespace IOB_WIN_KAWASAKI.Iob { // impiego override metodo set... bool answ = setcontapezziPLC(0, codTav); -#if false - bool answ = false; - // ...SE abilitato da conf IOB - if (cIobConf.optPar.Count > 0 && getOptPar("ENABLE_PZ_RESET") == "TRUE") - { - // scrivo valore 0 x il contapezzi - try - { - pzCounter = 0; - } - catch (Exception exc) - { - lgError(exc, "Errore in RESET contapezzi KAWASAKI"); - connectionOk = false; - } - answ = true; - } - else - { - lgError("Impossibile effettuare RESET contapezzi KAWASAKI, mancanza parametro OPT:ENABLE_PZ_RESET"); - } -#endif return answ; } @@ -386,14 +366,14 @@ namespace IOB_WIN_KAWASAKI.Iob if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("KAWASAKI: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -887,10 +867,10 @@ namespace IOB_WIN_KAWASAKI.Iob } catch (Exception exc) { - if (DateTime.Now.Subtract(lastWarnODL).TotalSeconds > 15) + if (DateTime.Now.Subtract(DtHelp.lastWarnODL).TotalSeconds > 15) { lgError(exc, "Errore in fase di chiamata URL x ODL corrente | URL chiamato: {0}", urlGetCurrODL); - lastWarnODL = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; } } } @@ -909,7 +889,7 @@ namespace IOB_WIN_KAWASAKI.Iob { // ora processo il contapezzi... controllo se è passato intervallo minimo tra 2 // controlli/elaborazioni x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... if (contapezziPLC != contapezziIOB) @@ -944,7 +924,7 @@ namespace IOB_WIN_KAWASAKI.Iob pzCntReload(true); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } else @@ -954,11 +934,11 @@ namespace IOB_WIN_KAWASAKI.Iob } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgError($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC KAWASAKI {contapezziPLC} | contapezziIOB {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } diff --git a/IOB-WIN-MBUS/IobModbustTCP/ModbusTCP.cs b/IOB-WIN-MBUS/IobModbustTCP/ModbusTCP.cs index 1ecd3227..053bc129 100644 --- a/IOB-WIN-MBUS/IobModbustTCP/ModbusTCP.cs +++ b/IOB-WIN-MBUS/IobModbustTCP/ModbusTCP.cs @@ -1,6 +1,11 @@ using EasyModbus; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Config.Mem; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Core; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Utility; using MapoSDK; using Newtonsoft.Json; using System; @@ -41,8 +46,8 @@ namespace IOB_WIN_MBUS.IobModbusTCP { // gestione invio ritardato contapezzi - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; // inizializzo parametri... parametri = new ModBusTcpParamConf(); #if false @@ -291,7 +296,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP } else { - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } else @@ -507,7 +512,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP lgInfo("ModBus TCP: tryConnect step 03"); // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (doLog) { @@ -516,7 +521,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP lgInfo("ModBus TCP: tryConnect step 04"); // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -533,7 +538,6 @@ namespace IOB_WIN_MBUS.IobModbusTCP // refresh stato allarmi!!! if (connectionOk) { - //queueInEnabCurr = true; lgInfo($"Connessione OK: {connectionOk}"); if (adpRunning) { @@ -595,7 +599,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP connectionOk = false; queueInEnabCurr = false; // resetto last ping... - lastPING = DateTime.Now.AddMinutes(-1); + DtHelp.lastPING = DateTime.Now.AddMinutes(-1); } /// @@ -673,10 +677,6 @@ namespace IOB_WIN_MBUS.IobModbusTCP /// protected Dictionary InputRegisterLUT = new Dictionary(); - /// - /// Ultimo controllo ping x evitare ping flood... - /// - protected DateTime lastPingConn = DateTime.Now.AddMinutes(-10); /// /// Esito ultimo ping @@ -1177,7 +1177,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP if (!connectionOk) { // ora tento avvio PLC... SE PING OK... - lastPING = adesso; + DtHelp.lastPING = adesso; IPStatus esitoPing = testPingMachine; if (esitoPing == IPStatus.Success) { @@ -1374,7 +1374,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP { // riduco i controlli ping.. li faccio solo ogni 5 ping period se precedente positivo... DateTime adesso = DateTime.Now; - if (lastPingOk && adesso.Subtract(lastPingConn).TotalMilliseconds < 5 * parametri.pingMsTimeout) + if (lastPingOk && adesso.Subtract(DtHelp.lastPingConn).TotalMilliseconds < 5 * parametri.pingMsTimeout) { answ = lastPingOk; } @@ -1420,7 +1420,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP } } // salvo stato ping - lastPingConn = adesso; + DtHelp.lastPingConn = adesso; } lastPingOk = answ; } @@ -2006,7 +2006,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP lgTrace($"Lettura in blocco Colis | startAddr: {startAddr} | numReg {numReg} | rawData.lenght: {rawData.Length} | {sw.ElapsedMilliseconds}ms"); // salvo statistica... trackReadData(rawData.Length / 8, sw.Elapsed.TotalMilliseconds / 1000); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; // salvo in LUT i dati... if (rawData.Length > 0) { @@ -2077,7 +2077,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP lgTrace($"Lettura in blocco DiscreteInput | startAddr: {startAddr} | numReg {numReg} | rawData.lenght: {rawData.Length} | {sw.ElapsedMilliseconds}ms"); // salvo statistica... trackReadData(rawData.Length / 8, sw.Elapsed.TotalMilliseconds / 1000); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; // salvo in LUT i dati... if (rawData.Length > 0) { @@ -2149,7 +2149,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP lgTrace($"Lettura in blocco HoldingRegisters| startAddr: {startAddr} | numReg {numReg} | rawData.lenght: {rawData.Length} | {sw.Elapsed.TotalMilliseconds}ms"); // salvo statistica... trackReadData(rawData.Length * 2, sw.Elapsed.TotalMilliseconds / 1000); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; // se risposta troppo rapida (< minRespTimeMs, tipicamente 5 msse non impostato in OptPar) indico NON ok e errori... if (sw.Elapsed.TotalMilliseconds < minRespTimeMs) { @@ -2240,7 +2240,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP lgTrace($"Lettura in blocco InputRegisters| startAddr: {startAddr} | numReg {numReg} | rawData.lenght: {rawData.Length} | {sw.ElapsedMilliseconds}ms"); // salvo statistica... trackReadData(rawData.Length * 2, sw.Elapsed.TotalMilliseconds / 1000); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; // salvo in LUT la versione ESPLOSA 2 byte alla volta... if (rawData.Length > 0) { diff --git a/IOB-WIN-MBUS/IobModbustTCP/ModbusTCPFrer.cs b/IOB-WIN-MBUS/IobModbustTCP/ModbusTCPFrer.cs index 00cc7cf9..6805f1a0 100644 --- a/IOB-WIN-MBUS/IobModbustTCP/ModbusTCPFrer.cs +++ b/IOB-WIN-MBUS/IobModbustTCP/ModbusTCPFrer.cs @@ -1,5 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; using System; using System.Globalization; using System.IO; @@ -75,7 +76,7 @@ namespace IOB_WIN_MBUS.IobModbusTCP ----------------------------------------------------- */ DateTime adesso = DateTime.Now; // se ha risposto ad ultima chiamata --> ok - if (connectionOk && adesso.Subtract(lastReadPLC).TotalMinutes < 1) + if (connectionOk && adesso.Subtract(DtHelp.lastReadPLC).TotalMinutes < 1) { B_input = 3; // aggiungo NON emergenza... @@ -85,8 +86,8 @@ namespace IOB_WIN_MBUS.IobModbusTCP { B_input = 0; } - lastReadPLC = DateTime.Now; - lastWatchDog = adesso; + DtHelp.lastReadPLC = DateTime.Now; + DtHelp.lastWatchDog = adesso; } diff --git a/IOB-WIN-MITSUBISHI/Iob/Mitsubishi.cs b/IOB-WIN-MITSUBISHI/Iob/Mitsubishi.cs index 8ac4eed5..75c3866a 100644 --- a/IOB-WIN-MITSUBISHI/Iob/Mitsubishi.cs +++ b/IOB-WIN-MITSUBISHI/Iob/Mitsubishi.cs @@ -1,5 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; @@ -24,8 +26,8 @@ namespace IOB_WIN_MITSUBISHI.Iob lgInfo("Start init Mitsubishi"); // gestione invio ritardato contapezzi - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; // inizializzo correttamente aree memoria secondo CONF - da IobConfFull IOB_UT_NEXT.Config.Mem.MemAreaDto currArea = new IOB_UT_NEXT.Config.Mem.MemAreaDto(); @@ -883,14 +885,14 @@ namespace IOB_WIN_MITSUBISHI.Iob if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("MITSUBISHI: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // ora PING!!! Ping pingSender = new Ping(); IPAddress address = IPAddress.Loopback; @@ -934,7 +936,7 @@ namespace IOB_WIN_MITSUBISHI.Iob if (connectionOk) { checkVetoQueueIn(); - dtAvvioAdp = DateTime.Now; + DtHelp.AvvioAdp = DateTime.Now; if (adpRunning) { lgInfo("Connessione OK"); @@ -1641,10 +1643,10 @@ namespace IOB_WIN_MITSUBISHI.Iob } catch (Exception exc) { - if (DateTime.Now.Subtract(lastWarnODL).TotalSeconds > 15) + if (DateTime.Now.Subtract(DtHelp.lastWarnODL).TotalSeconds > 15) { lgError(exc, "Errore in fase di chiamata URL x ODL corrente | URL chiamato: {0}", urlGetCurrODL); - lastWarnODL = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; } } } @@ -1661,7 +1663,7 @@ namespace IOB_WIN_MITSUBISHI.Iob { // controllo se è passato intervallo minimo tra 2 // controlli/elaborazioni x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... if (contapezziPLC != contapezziIOB) @@ -1695,17 +1697,17 @@ namespace IOB_WIN_MITSUBISHI.Iob pzCntReload(true); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC MITSUBISHI: {contapezziPLC} | contapezziIOB {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } #endif diff --git a/IOB-WIN-MTC/Iob/MTConn.cs b/IOB-WIN-MTC/Iob/MTConn.cs index 3a3c8cd2..09a75e8d 100644 --- a/IOB-WIN-MTC/Iob/MTConn.cs +++ b/IOB-WIN-MTC/Iob/MTConn.cs @@ -1,8 +1,9 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; -using MTConnect.Assets; using MTConnect.Clients; using MTConnect.Devices; using MTConnect.Observations; @@ -10,15 +11,11 @@ using MTConnect.Streams; using Newtonsoft.Json; using System; using System.Collections.Generic; -using System.Data.SqlClient; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Threading; -using System.Threading.Tasks; using System.Windows.Forms; -using System.Xml.Linq; -using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace IOB_WIN_MTC.Iob { @@ -63,8 +60,8 @@ namespace IOB_WIN_MTC.Iob // init datetime counters DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; lastCurrent = adesso; // ora leggo il file di conf specifico.... string jsonFileName = getOptPar("MTC_PARAM_CONF"); @@ -178,7 +175,7 @@ namespace IOB_WIN_MTC.Iob public override void readSemafori(ref newDisplayData currDispData) { DateTime adesso = DateTime.Now; - lastReadPLC = adesso; + DtHelp.lastReadPLC = adesso; // verifico non sia in veto invio iniziale... if (queueInEnabCurr) { @@ -251,14 +248,14 @@ namespace IOB_WIN_MTC.Iob // disattivo eventuali sottoscrizioni DeactEvents(); // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("MTC: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -273,7 +270,6 @@ namespace IOB_WIN_MTC.Iob if (connectionOk) { checkVetoQueueIn(); - //queueInEnabCurr = true; if (adpRunning) { lgInfo("Connessione OK"); @@ -1352,8 +1348,8 @@ namespace IOB_WIN_MTC.Iob // fix tempi! DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; lastCurrent = adesso; } catch @@ -2035,12 +2031,12 @@ namespace IOB_WIN_MTC.Iob { // verifico veto ad invio (ogni 60 min...) DateTime adesso = DateTime.Now; - if (adesso > dtVetoSenDataItem) + if (adesso > DtHelp.dtVetoSenDataItem) { string rawData = JsonConvert.SerializeObject(dataItems); var resp = HttpService.CallUrlPost($"{urlSaveDataItems}", rawData); // imposto nuovo veto - dtVetoSenDataItem = adesso.AddMinutes(minVetoSendDataItem); + DtHelp.dtVetoSenDataItem = adesso.AddMinutes(minVetoSendDataItem); } } } @@ -2051,21 +2047,10 @@ namespace IOB_WIN_MTC.Iob /// private void traceObservation(IObservation observation) { +#if DEBUG // SOLO in debug... -#if false - string sMsg = $"VETO: - {observation.DataItemId} | {observation.Category}"; - if (observation.Values != null && observation.Values.Count() > 0) - { - foreach (var item in observation.Values) - { - sMsg += $" | {item.Key}: {item.Value}"; - } - } - lgTrace(sMsg); - trackExchDataRaw(sMsg.Length, 1024); -#endif - trackExchData(64, 4096); +#endif } #endregion Private Methods diff --git a/IOB-WIN-NEXT/IOB-WIN-NEXT.sln b/IOB-WIN-NEXT/IOB-WIN-NEXT.sln deleted file mode 100644 index 2e7483cd..00000000 --- a/IOB-WIN-NEXT/IOB-WIN-NEXT.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.31205.134 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IOB-WIN-NEXT", "IOB-WIN-NEXT.csproj", "{B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Debug|x86.ActiveCfg = Debug|x86 - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Debug|x86.Build.0 = Debug|x86 - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Release|Any CPU.Build.0 = Release|Any CPU - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Release|x86.ActiveCfg = Release|x86 - {B2ABB009-C046-4F9C-956C-52DCAA9FE5A9}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {5BF50E92-A90E-4117-812C-2BFC803594DB} - EndGlobalSection -EndGlobal diff --git a/IOB-WIN-NEXT/Iob/GenericNext.cs b/IOB-WIN-NEXT/Iob/GenericNext.cs index 1cabd677..33de61ef 100644 --- a/IOB-WIN-NEXT/Iob/GenericNext.cs +++ b/IOB-WIN-NEXT/Iob/GenericNext.cs @@ -1,7 +1,4 @@ -#if false -using EgwProxy.Ftp; -#endif -using EgwProxy.MultiCncLib.App.Native; +using EgwProxy.MultiCncLib.App.Native; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; using IOB_WIN_FORM; @@ -23,7 +20,6 @@ using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Serialization; -using static IOB_UT_NEXT.BaseAlarmConf; using static IOB_UT_NEXT.CustomObj; using static IOB_UT_NEXT.DataModel.Fimat; using static MapoSDK.WharehouseData; diff --git a/IOB-WIN-OMRON/Iob/Omron.cs b/IOB-WIN-OMRON/Iob/Omron.cs index 5b67ebbc..7c39c1ff 100644 --- a/IOB-WIN-OMRON/Iob/Omron.cs +++ b/IOB-WIN-OMRON/Iob/Omron.cs @@ -1,6 +1,8 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using System; using System.Collections.Generic; @@ -23,8 +25,8 @@ namespace IOB_WIN_OMRON.Iob { // gestione invio ritardato contapezzi - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; // imposto i parametri PLC setParamPlc(); @@ -61,24 +63,6 @@ namespace IOB_WIN_OMRON.Iob /// public override void processContapezzi() { - if (utils.CRB("enableContapezzi")) - { -#if false - try - { - // hard coded... !!!FARE!!! rivedere megio conf - contapezziPLC = pzCounter; - // verifico quale modalità sia richiesta: STD (6711) oppure BIT (Custom, con indicazione area) - if (cIobConf.optPar.Count > 0 && IOBConfFull.Device.PzCountMode != "") - { - } - } - catch (Exception exc) - { - lgError(exc, "Errore in contapezzi OMRON"); - } -#endif - } } /// @@ -152,27 +136,6 @@ namespace IOB_WIN_OMRON.Iob public override bool setcontapezziPLC(int newPzCount, string codTav) { bool answ = false; -#if false - // ...SE abilitato da conf IOB - if (cIobConf.optPar.Count > 0 && getOptPar("ENABLE_PZ_RESET") == "TRUE") - { - // scrivo valore 0 x il contapezzi - try - { - pzCounter = newPzCount; - } - catch (Exception exc) - { - lgError(exc, "Errore in SET contapezzi OMRON"); - connectionOk = false; - } - answ = true; - } - else - { - lgError("Impossibile effettuare SET contapezzi OMRON, mancanza parametro OPT:ENABLE_PZ_RESET"); - } -#endif return answ; } @@ -184,14 +147,14 @@ namespace IOB_WIN_OMRON.Iob if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("OMRON: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -743,10 +706,10 @@ namespace IOB_WIN_OMRON.Iob } catch (Exception exc) { - if (DateTime.Now.Subtract(lastWarnODL).TotalSeconds > 15) + if (DateTime.Now.Subtract(DtHelp.lastWarnODL).TotalSeconds > 15) { lgError(exc, "Errore in fase di chiamata URL x ODL corrente | URL chiamato: {0}", urlGetCurrODL); - lastWarnODL = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; } } } diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUa.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUa.cs index c0c8b7fb..0c9e864f 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUa.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUa.cs @@ -1,7 +1,10 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Config.Mem; using IOB_UT_NEXT.DataModel; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using NLog; @@ -16,7 +19,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; -using static IOB_UT_NEXT.ByteDataConverter; +using static IOB_UT_NEXT.Services.Core.ByteDataConverter; namespace IOB_WIN_OPC_UA.IobOpc { @@ -49,8 +52,8 @@ namespace IOB_WIN_OPC_UA.IobOpc // init datetime counters DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; lastCurrent = adesso; lgTrace($"Aggiornato IobOpcUa.lastCurrent: {lastCurrent}"); opcUaParams = IOBConfFull.Special.OpcUaConf; @@ -585,14 +588,14 @@ namespace IOB_WIN_OPC_UA.IobOpc if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("OpcUa: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success || opcUaParams.forcePingOk) { @@ -1633,9 +1636,9 @@ namespace IOB_WIN_OPC_UA.IobOpc if (opcUaParams.WatchDog.IsEnabled) { lgTrace("WatchDog 01"); - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; @@ -2655,8 +2658,8 @@ namespace IOB_WIN_OPC_UA.IobOpc // fix tempi! DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; lastCurrent = adesso; lgTrace($"Aggiornato doConnect.lastCurrent: {lastCurrent}"); } diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaEwon.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaEwon.cs index d66471a4..3b0e50ea 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaEwon.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaEwon.cs @@ -143,9 +143,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaImas.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaImas.cs index 0e202dae..0687e89f 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaImas.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaImas.cs @@ -147,9 +147,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaKpw.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaKpw.cs index 37739e83..0a5c1868 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaKpw.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaKpw.cs @@ -137,9 +137,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaKpwRama.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaKpwRama.cs index f6bb14ad..23e278db 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaKpwRama.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaKpwRama.cs @@ -1,6 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using Opc.Ua; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaMBH.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaMBH.cs index 2349a0c1..29e09d15 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaMBH.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaMBH.cs @@ -147,9 +147,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaMBHCimolai.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaMBHCimolai.cs index a54941a9..becd145e 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaMBHCimolai.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaMBHCimolai.cs @@ -1,6 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using System; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaOmron.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaOmron.cs index 47bed9d1..a1025ffe 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaOmron.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaOmron.cs @@ -144,9 +144,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemens.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemens.cs index 1203447e..4c3b7db5 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemens.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemens.cs @@ -114,7 +114,7 @@ namespace IOB_WIN_OPC_UA.IobOpc if (addResetPzCount) { // imposto reset gestione pzcount da parametri - vetoQueuePzCount = DateTime.Now.AddMinutes(IOBConfFull.General.DelayReadPzCountSetup); + DtHelp.vetoQueuePzCount = DateTime.Now.AddMinutes(IOBConfFull.General.DelayReadPzCountSetup); // se è una doppia tavola aggiungo anche tag "processOtherInfo"... if (isMulti) { @@ -161,7 +161,7 @@ namespace IOB_WIN_OPC_UA.IobOpc { lgInfo("OpcUaSiemens.resetContapezziPLC 02"); // imposto un veto in lettura cmq x evitare problemi - dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); if (opcUaParams.actResetCounter != null && opcUaParams.actResetCounter.Count > 0) { lgInfo("OpcUaSiemens.resetContapezziPLC 03"); @@ -318,7 +318,7 @@ namespace IOB_WIN_OPC_UA.IobOpc if (!isWorking && delayMinReadPzCount > 0) { // metto un veto al contapezzi... - dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); } // se ho emergenza premuta --> emergenza! @@ -335,10 +335,10 @@ namespace IOB_WIN_OPC_UA.IobOpc { // RUN = LAVORA! B_input += (1 << 1); - if (dtVetoReadPzCount >= adesso) + if (DtHelp.dtVetoReadPzCount >= adesso) { // tolgo eventuale veto al contapezzi... - dtVetoReadPzCount = DateTime.Now.AddSeconds(-1); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddSeconds(-1); } } // se ho almeno 1 allarme E NON SONO IN AUTO --> ALARM! @@ -360,9 +360,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensRama.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensRama.cs index 22c99d53..c676e972 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensRama.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensRama.cs @@ -1,6 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using Opc.Ua; @@ -95,7 +95,7 @@ namespace IOB_WIN_OPC_UA.IobOpc plcWriteParams(ref list2Write); // aggiungo 1 altro step di attesa alla lettura pezzi x sicurezza... - dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddMinutes(delayMinReadPzCount); } /// diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensSW.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensSW.cs index 99a1fd2e..3408b26b 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensSW.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaSiemensSW.cs @@ -160,9 +160,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OPC-UA/IobOpc/OpcUaUlma.cs b/IOB-WIN-OPC-UA/IobOpc/OpcUaUlma.cs index 5feb1303..df0d7a0a 100644 --- a/IOB-WIN-OPC-UA/IobOpc/OpcUaUlma.cs +++ b/IOB-WIN-OPC-UA/IobOpc/OpcUaUlma.cs @@ -146,9 +146,9 @@ namespace IOB_WIN_OPC_UA.IobOpc // se abilitato watchdog... if (opcUaParams.WatchDog.IsEnabled) { - if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + if (adesso.Subtract(DtHelp.lastWatchDogPLC).TotalSeconds > 2) { - lastWatchDogPLC = adesso; + DtHelp.lastWatchDogPLC = adesso; WatchDog++; WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; diff --git a/IOB-WIN-OSAI/Iob/OSAI.cs b/IOB-WIN-OSAI/Iob/OSAI.cs index c1e11386..d101a16a 100644 --- a/IOB-WIN-OSAI/Iob/OSAI.cs +++ b/IOB-WIN-OSAI/Iob/OSAI.cs @@ -2,7 +2,9 @@ using EgwProxy.OsaiCncLib; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using System; using System.Collections.Generic; @@ -38,8 +40,8 @@ namespace IOB_WIN_OSAI.Iob { // gestione invio ritardato contapezzi - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; if (IOBConfFull != null) { signLUT = IOBConfFull.Device.SigLUT; @@ -432,7 +434,7 @@ namespace IOB_WIN_OSAI.Iob if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { @@ -447,7 +449,7 @@ namespace IOB_WIN_OSAI.Iob if (needPing) { // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // ora PING!!! IPAddress address = IPAddress.Loopback; IPAddress.TryParse(IOBConfFull.Device.Connect.PingIpAddr, out address); @@ -489,7 +491,7 @@ namespace IOB_WIN_OSAI.Iob // refresh stato allarmi!!! if (connectionOk) { - dtAvvioAdp = DateTime.Now; + DtHelp.AvvioAdp = DateTime.Now; queueInEnabCurr = true; if (adpRunning) { @@ -688,10 +690,10 @@ namespace IOB_WIN_OSAI.Iob } catch (Exception exc) { - if (DateTime.Now.Subtract(lastWarnODL).TotalSeconds > 15) + if (DateTime.Now.Subtract(DtHelp.lastWarnODL).TotalSeconds > 15) { lgError(exc, "Errore in fase di chiamata URL x ODL corrente | URL chiamato: {0}", urlGetCurrODL); - lastWarnODL = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; } } } @@ -708,7 +710,7 @@ namespace IOB_WIN_OSAI.Iob { // controllo se è passato intervallo minimo tra 2 controlli/elaborazioni // x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... if (contapezziPLC != contapezziIOB) @@ -741,16 +743,16 @@ namespace IOB_WIN_OSAI.Iob pzCntReload(true); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC OSAI: {contapezziPLC} | contapezziIOB {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } diff --git a/IOB-WIN-SHELLY/Iob/ShellyClientGen1.cs b/IOB-WIN-SHELLY/Iob/ShellyClientGen1.cs index 68bf4da1..1a501c0d 100644 --- a/IOB-WIN-SHELLY/Iob/ShellyClientGen1.cs +++ b/IOB-WIN-SHELLY/Iob/ShellyClientGen1.cs @@ -3,6 +3,8 @@ using EgwProxy.Shelly.Clients; using EgwProxy.Shelly.Options; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Data; using MapoSDK; using Newtonsoft.Json; using System; @@ -41,12 +43,12 @@ namespace IOB_WIN_SHELLY.Iob B_input = 0; // init datetime counters DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; vetoCheckStatus = adesso; // 2023.09.05 imposto anche primo ping e check disconnected... - lastPING = adesso; - lastDisconnCheck = adesso; + DtHelp.lastPING = adesso; + DtHelp.lastDisconnCheck = adesso; var VETO_PING_SEC = getOptPar("VETO_PING_SEC"); if (!string.IsNullOrEmpty(VETO_PING_SEC)) { @@ -84,14 +86,14 @@ namespace IOB_WIN_SHELLY.Iob { Dictionary outData = new Dictionary(); // verifico che non sia una chiamata troppo frequente, ogni 10 sec minimo... - if (DateTime.Now > lastReadPLC.AddSeconds(shellyCallDelay)) + if (DateTime.Now > DtHelp.lastReadPLC.AddSeconds(shellyCallDelay)) { // chiama lettura status completo e recupera info in memRead e le passa come DynData... lastShellyResp = Task.Run(() => ((Shelly1PmClient)shellyCli).GetSwitchStatus(CancellationToken.None, 0)).Result; // NB: da verificare tipo di chiamata in base al tipo di shelly... TDB ora è cablato x Shelly1PM if (lastShellyResp.IsSuccess) { - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; // recupero da conf memMap e ciclo foreach (var item in IOBConfFull.Memory.mMapRead) { @@ -147,7 +149,7 @@ namespace IOB_WIN_SHELLY.Iob { DateTime adesso = DateTime.Now; // se ha risposto ad ultima chiamata --> ok - if (connectionOk && adesso.Subtract(lastReadPLC).TotalMinutes < 1) + if (connectionOk && adesso.Subtract(DtHelp.lastReadPLC).TotalMinutes < 1) { B_input = 3; // aggiungo NON emergenza... @@ -157,8 +159,8 @@ namespace IOB_WIN_SHELLY.Iob { B_input = 0; } - lastReadPLC = DateTime.Now; - lastWatchDog = adesso; + DtHelp.lastReadPLC = DateTime.Now; + DtHelp.lastWatchDog = adesso; } public override void startAdapter(bool resetQueue) @@ -166,10 +168,10 @@ namespace IOB_WIN_SHELLY.Iob base.startAdapter(resetQueue); // 2023.09.05 imposto anche primo ping e check disconnected... DateTime adesso = DateTime.Now; - lastWatchDog = adesso; - //lastPING = adesso; - lastReadPLC = adesso; - lastDisconnCheck = adesso; + DtHelp.lastWatchDog = adesso; + //DtHelp.lastPING = adesso; + DtHelp.lastReadPLC = adesso; + DtHelp.lastDisconnCheck = adesso; // faccio un primo check POST ritardo tryConnect(); } @@ -183,10 +185,8 @@ namespace IOB_WIN_SHELLY.Iob lgDebug($"Shelly: tryConnect step 01 | connectionOk: {connectionOk}"); if (!connectionOk) { - //// resetto coda... - //QueuePing = new DataQueue("000", "QueuePing", false); // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > vetoPingSec) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > vetoPingSec) { if (doLog) { @@ -203,7 +203,7 @@ namespace IOB_WIN_SHELLY.Iob if (pingStatusOk() || pingOK) { // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; connectionOk = true; queueInEnabCurr = true; lgInfo("Shelly - ping OK"); @@ -264,14 +264,14 @@ namespace IOB_WIN_SHELLY.Iob if (B_input == 0 && pingOk) { B_input = 1; - QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QueuePing", false, redisMan); - lgTrace($"QueuePing resetted on addTest"); + QHelp.QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueuePing", false, redisMan); + lgTrace($"QHelp.QueuePing resetted on addTest"); } - QueuePing.Enqueue($"{score}"); - while (QueuePing.Count > maxQueuePing) + QHelp.QueuePing.Enqueue($"{score}"); + while (QHelp.QueuePing.Count > maxQueuePing) { string res = ""; - QueuePing.TryDequeue(out res); + QHelp.QueuePing.TryDequeue(out res); } } @@ -284,10 +284,10 @@ namespace IOB_WIN_SHELLY.Iob private bool pingStatusOk() { bool answ = false; - long numVal = QueuePing.Count; + long numVal = QHelp.QueuePing.Count; if (numVal > maxQueuePing / 2) { - var listaValori = QueuePing.ToList(); + var listaValori = QHelp.QueuePing.ToList(); long numOk = listaValori.Where(x => x == "1").Count(); long numKo = numVal - numOk; answ = numOk >= numKo; diff --git a/IOB-WIN-SHELLY/Iob/ShellyClientGen2.cs b/IOB-WIN-SHELLY/Iob/ShellyClientGen2.cs index 2ee2301a..ac494de6 100644 --- a/IOB-WIN-SHELLY/Iob/ShellyClientGen2.cs +++ b/IOB-WIN-SHELLY/Iob/ShellyClientGen2.cs @@ -3,6 +3,8 @@ using EgwProxy.Shelly.Clients; using EgwProxy.Shelly.Options; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Data; using MapoSDK; using Newtonsoft.Json; using System; @@ -42,12 +44,12 @@ namespace IOB_WIN_SHELLY.Iob B_input = 0; // init datetime counters DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; vetoCheckStatus = adesso; // 2023.09.05 imposto anche primo ping e check disconnected... - lastPING = adesso; - lastDisconnCheck = adesso; + DtHelp.lastPING = adesso; + DtHelp.lastDisconnCheck = adesso; var VETO_PING_SEC = getOptPar("VETO_PING_SEC"); if (!string.IsNullOrEmpty(VETO_PING_SEC)) { @@ -85,7 +87,7 @@ namespace IOB_WIN_SHELLY.Iob { Dictionary outData = new Dictionary(); // verifico che non sia una chiamata troppo frequente, ogni 10 sec minimo... - if (DateTime.Now > lastReadPLC.AddSeconds(shellyCallDelay)) + if (DateTime.Now > DtHelp.lastReadPLC.AddSeconds(shellyCallDelay)) { // chiama lettura status valor RT (Potenza, Corrente...) lastShellyRespRT = Task.Run(() => ((ShellyPro3EmClient)shellyCli).GetEmStatus(CancellationToken.None, 0)).Result; @@ -94,7 +96,7 @@ namespace IOB_WIN_SHELLY.Iob // Salvo negli oggetti DynData x EnergyTotal if (lastShellyRespEnergy.IsSuccess) { - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; // recupero da conf memMap e ciclo foreach (var item in IOBConfFull.Memory.mMapRead) { @@ -135,7 +137,7 @@ namespace IOB_WIN_SHELLY.Iob // Salvo negli oggetti DynData x RT if (lastShellyRespRT.IsSuccess) { - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; // recupero da conf memMap e ciclo foreach (var item in IOBConfFull.Memory.mMapRead) { @@ -222,7 +224,7 @@ namespace IOB_WIN_SHELLY.Iob { DateTime adesso = DateTime.Now; // se ha risposto ad ultima chiamata --> ok - if (connectionOk && adesso.Subtract(lastReadPLC).TotalMinutes < 1) + if (connectionOk && adesso.Subtract(DtHelp.lastReadPLC).TotalMinutes < 1) { B_input = 3; // aggiungo NON emergenza... @@ -232,8 +234,8 @@ namespace IOB_WIN_SHELLY.Iob { B_input = 0; } - lastReadPLC = DateTime.Now; - lastWatchDog = adesso; + DtHelp.lastReadPLC = DateTime.Now; + DtHelp.lastWatchDog = adesso; } public override void startAdapter(bool resetQueue) @@ -241,10 +243,10 @@ namespace IOB_WIN_SHELLY.Iob base.startAdapter(resetQueue); // 2023.09.05 imposto anche primo ping e check disconnected... DateTime adesso = DateTime.Now; - lastWatchDog = adesso; - //lastPING = adesso; - lastReadPLC = adesso; - lastDisconnCheck = adesso; + DtHelp.lastWatchDog = adesso; + //DtHelp.lastPING = adesso; + DtHelp.lastReadPLC = adesso; + DtHelp.lastDisconnCheck = adesso; // faccio un primo check POST ritardo tryConnect(); } @@ -258,10 +260,8 @@ namespace IOB_WIN_SHELLY.Iob lgDebug($"Shelly: tryConnect step 01 | connectionOk: {connectionOk}"); if (!connectionOk) { - //// resetto coda... - //QueuePing = new DataQueue("000", "QueuePing", false); // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > vetoPingSec) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > vetoPingSec) { if (doLog) { @@ -278,7 +278,7 @@ namespace IOB_WIN_SHELLY.Iob if (pingStatusOk() || pingOK) { // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; connectionOk = true; queueInEnabCurr = true; lgInfo("Shelly - ping OK"); @@ -344,14 +344,14 @@ namespace IOB_WIN_SHELLY.Iob if (B_input == 0 && pingOk) { B_input = 1; - QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QueuePing", false, redisMan); - lgTrace($"QueuePing resetted on addTest"); + QHelp.QueuePing = new DataQueue(IOBConfFull.General.FilenameIOB, "QHelp.QueuePing", false, redisMan); + lgTrace($"QHelp.QueuePing resetted on addTest"); } - QueuePing.Enqueue($"{score}"); - while (QueuePing.Count > maxQueuePing) + QHelp.QueuePing.Enqueue($"{score}"); + while (QHelp.QueuePing.Count > maxQueuePing) { string res = ""; - QueuePing.TryDequeue(out res); + QHelp.QueuePing.TryDequeue(out res); } } @@ -364,10 +364,10 @@ namespace IOB_WIN_SHELLY.Iob private bool pingStatusOk() { bool answ = false; - long numVal = QueuePing.Count; + long numVal = QHelp.QueuePing.Count; if (numVal > maxQueuePing / 2) { - var listaValori = QueuePing.ToList(); + var listaValori = QHelp.QueuePing.ToList(); long numOk = listaValori.Where(x => x == "1").Count(); long numKo = numVal - numOk; answ = numOk >= numKo; diff --git a/IOB-WIN-SIEMENS/IobSiemens/IobSiemensTorri_legacy.cs b/IOB-WIN-SIEMENS/IobSiemens/IobSiemensTorri_legacy.cs index e83c32f3..7239f637 100644 --- a/IOB-WIN-SIEMENS/IobSiemens/IobSiemensTorri_legacy.cs +++ b/IOB-WIN-SIEMENS/IobSiemens/IobSiemensTorri_legacy.cs @@ -175,8 +175,8 @@ namespace IOB_WIN { // gestione invio ritardato contapezzi - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; // init conf _IOBConf = IOBConf; // inizializzo parametri... @@ -372,14 +372,14 @@ namespace IOB_WIN // reimporto parametri PLC se necessario... setParamPlc(); // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (doLog) { lgInfo("SIEMENS-TORRI: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPing() == IPStatus.Success) { @@ -695,17 +695,17 @@ namespace IOB_WIN } catch (Exception exc) { - if (DateTime.Now.Subtract(lastWarnODL).TotalSeconds > 15) + if (DateTime.Now.Subtract(DtHelp.lastWarnODL).TotalSeconds > 15) { lgError(exc, "Errore in fase di chiamata URL x ODL corrente | URL chiamato: {0}", urlGetCurrODL); - lastWarnODL = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; } } if (currODL != null && currODL != "" && currODL != "0") { // ora processo il contapezzi... // controllo se è passato intervallo minimo tra 2 controlli/elaborazioni x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... @@ -734,16 +734,16 @@ namespace IOB_WIN lgInfo(string.Format("Errore salvataggio Contapezzi SIEMENST-TORRI: {0} | Contapezzi interno {1} | Errore salvataggio: {2}", lastCountCNC, contapezzi, retVal)); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo(string.Format("Attenzione: mancanza ODL non procedo con gestione contapezzi. Contapezzi SIEMENST-TORRI: {0} | Contapezzi interno {1}", lastCountCNC, contapezzi)); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } diff --git a/IOB-WIN-SIEMENS/IobSiemens/Siemens.cs b/IOB-WIN-SIEMENS/IobSiemens/Siemens.cs index 571b1505..ec89d272 100644 --- a/IOB-WIN-SIEMENS/IobSiemens/Siemens.cs +++ b/IOB-WIN-SIEMENS/IobSiemens/Siemens.cs @@ -1,5 +1,8 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Config.Mem; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using Newtonsoft.Json; using S7.Net; @@ -52,8 +55,8 @@ namespace IOB_WIN_SIEMENS.IobSiemens { // gestione invio ritardato contapezzi - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; // inizializzo parametri... parametri = new connParamS7() { @@ -356,7 +359,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens if (pzCountAll >= 0) { // 2025.02.26 aggiunto controllo che non sia appena avviato IOB - bool isJustStarted = DateTime.Now.Subtract(prgStarted).TotalMinutes < 3; + bool isJustStarted = DateTime.Now.Subtract(DtHelp.prgStarted).TotalMinutes < 3; // verifico il NUOVO contapezzi PRIMA di accettare ogni incremento... int deltaPzCount = pzCountAll - contapezziPLC; double maxDelta = DateTime.Now.Subtract(plcLastPzRead).TotalMinutes / (plcAvgTc / 60); @@ -1018,7 +1021,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens lgInfoStartup("SIEMENS: tryConnect step 03"); // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (doLog) { @@ -1027,7 +1030,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens lgInfoStartup("SIEMENS: tryConnect step 04"); // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -1139,11 +1142,6 @@ namespace IOB_WIN_SIEMENS.IobSiemens /// protected Plc currPLC; - /// - /// Ultimo controllo ping x evitare ping flood... - /// - protected DateTime lastPingConn = DateTime.Now.AddMinutes(-10); - /// /// Esito ultimo ping /// @@ -1512,7 +1510,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens // procedura corrente... needRefresh = false; lgInfoStartup("SIEMENS: tryConnect"); - lastConnectTry = DateTime.Now; + DtHelp.lastConnectTry = DateTime.Now; tryConnect(); lgInfoStartup("End init Adapter SIEMENS"); if (isVerboseLog) @@ -1593,7 +1591,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens bool answ = false; // riduco i controlli ping.. li faccio solo ogni 5 ping period se precedente positivo... DateTime adesso = DateTime.Now; - if (lastPingOk && adesso.Subtract(lastPingConn).TotalMilliseconds < 5 * parametri.pingMsTimeout) + if (lastPingOk && adesso.Subtract(DtHelp.lastPingConn).TotalMilliseconds < 5 * parametri.pingMsTimeout) { answ = lastPingOk; } @@ -1643,7 +1641,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens } // salvo stato ping lastPingOk = answ; - lastPingConn = adesso; + DtHelp.lastPingConn = adesso; } return answ; diff --git a/IOB-WIN-SIEMENS/IobSiemens/SiemensAprochim.cs b/IOB-WIN-SIEMENS/IobSiemens/SiemensAprochim.cs index 7afc1b42..089890c3 100644 --- a/IOB-WIN-SIEMENS/IobSiemens/SiemensAprochim.cs +++ b/IOB-WIN-SIEMENS/IobSiemens/SiemensAprochim.cs @@ -1,5 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; diff --git a/IOB-WIN-SIEMENS/IobSiemens/SiemensFape.cs b/IOB-WIN-SIEMENS/IobSiemens/SiemensFape.cs index a1f7504d..f72d13f9 100644 --- a/IOB-WIN-SIEMENS/IobSiemens/SiemensFape.cs +++ b/IOB-WIN-SIEMENS/IobSiemens/SiemensFape.cs @@ -1,6 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Networking; using System; using System.Collections.Generic; using System.Linq; @@ -155,7 +155,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens // verifico NON sia vietato gestione contapezzi if (!plcPzCountValid || !rawInputRead) { - lgInfo($"Veto check contapezzi e ODL fino alle {dtVetoReadPzCount}"); + lgInfo($"Veto check contapezzi e ODL fino alle {DtHelp.dtVetoReadPzCount}"); } else { @@ -163,7 +163,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens { // ora processo il contapezzi... controllo se è passato intervallo minimo tra 2 // controlli/elaborazioni x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... if (contapezziPLC != contapezziIOB) @@ -195,17 +195,17 @@ namespace IOB_WIN_SIEMENS.IobSiemens pzCntReload(true); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC SIEMENS {contapezziPLC} | contapezziIOB {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } diff --git a/IOB-WIN-SIEMENS/IobSiemens/SiemensFapeV2.cs b/IOB-WIN-SIEMENS/IobSiemens/SiemensFapeV2.cs index 11d18196..65aa4a7a 100644 --- a/IOB-WIN-SIEMENS/IobSiemens/SiemensFapeV2.cs +++ b/IOB-WIN-SIEMENS/IobSiemens/SiemensFapeV2.cs @@ -1,6 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Services.Networking; using System; using System.Collections.Generic; using System.Linq; @@ -259,7 +259,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens // verifico NON sia vietato gestione contapezzi if (!plcPzCountValid || !rawInputRead) { - lgInfo($"Veto check contapezzi e ODL fino alle {dtVetoReadPzCount}"); + lgInfo($"Veto check contapezzi e ODL fino alle {DtHelp.dtVetoReadPzCount}"); } else { @@ -267,7 +267,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens { // ora processo il contapezzi... controllo se è passato intervallo minimo tra 2 // controlli/elaborazioni x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... if (contapezziPLC != contapezziIOB) @@ -300,17 +300,17 @@ namespace IOB_WIN_SIEMENS.IobSiemens pzCntReload(true); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC SIEMENS {contapezziPLC} | contapezziIOB {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } diff --git a/IOB-WIN-SIEMENS/IobSiemens/SiemensLasco.cs b/IOB-WIN-SIEMENS/IobSiemens/SiemensLasco.cs index 9692d257..3ff09d78 100644 --- a/IOB-WIN-SIEMENS/IobSiemens/SiemensLasco.cs +++ b/IOB-WIN-SIEMENS/IobSiemens/SiemensLasco.cs @@ -1,5 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; @@ -194,7 +196,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens // reset type counter valore += 4; // controlla se resettare il pz reset... - forcePzReset = forcePzResetUntil >= DateTime.Now; + forcePzReset = DtHelp.forcePzResetUntil >= DateTime.Now; } valore += (byte)(counterMes2Plc << 7); MemBlock[0] = (byte)valore; @@ -204,7 +206,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens case taskType.forceResetPzCount: // forzo reset contapezzi forcePzReset = true; - forcePzResetUntil = DateTime.Now.AddSeconds(3); + DtHelp.forcePzResetUntil = DateTime.Now.AddSeconds(3); break; case taskType.setParameter: @@ -233,7 +235,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens lgInfo("!!! Richiesta startSetup - BLOCCO contapezzi LASCO !!!"); // forzo reset contapezzi forcePzReset = true; - forcePzResetUntil = DateTime.Now.AddSeconds(3); + DtHelp.forcePzResetUntil = DateTime.Now.AddSeconds(3); break; case taskType.stopSetup: @@ -242,7 +244,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens lgInfo("!!! Richiesta stopSetup - SBLOCCO contapezzi LASCO!!!"); // forzo reset contapezzi forcePzReset = true; - forcePzResetUntil = DateTime.Now.AddSeconds(3); + DtHelp.forcePzResetUntil = DateTime.Now.AddSeconds(3); break; case taskType.fixStopSetup: diff --git a/IOB-WIN-SIEMENS/IobSiemens/SiemensTorri.cs b/IOB-WIN-SIEMENS/IobSiemens/SiemensTorri.cs index 3beefdde..40ab6823 100644 --- a/IOB-WIN-SIEMENS/IobSiemens/SiemensTorri.cs +++ b/IOB-WIN-SIEMENS/IobSiemens/SiemensTorri.cs @@ -1,5 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; @@ -36,7 +37,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens } // provo ad aggiungere un piccolo delay lettura pzCount - dtVetoReadPzCount = DateTime.Now.AddSeconds(10); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddSeconds(10); lgInfo("NEW IOB SIEMENS versione TORRI avviato | vers 2024"); } @@ -376,7 +377,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens // verifico NON sia vietato gestione contapezzi if (!plcPzCountValid || !rawInputRead) { - lgInfo($"Veto check contapezzi e ODL fino alle {dtVetoReadPzCount}"); + lgInfo($"Veto check contapezzi e ODL fino alle {DtHelp.dtVetoReadPzCount}"); } else { @@ -384,7 +385,7 @@ namespace IOB_WIN_SIEMENS.IobSiemens { // controllo se è passato intervallo minimo tra 2 controlli/elaborazioni x // distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // semplifico: se ho differenza invio in blocco if (contapezziPLC > contapezziIOB) @@ -409,15 +410,15 @@ namespace IOB_WIN_SIEMENS.IobSiemens } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC SIEMENST-TORRI: {contapezziPLC} | contapezziIOB: {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } // metto cmq 1 sec a veto verifica contapezzi - dtVetoReadPzCount = DateTime.Now.AddSeconds(1); + DtHelp.dtVetoReadPzCount = DateTime.Now.AddSeconds(1); } // log opzionale! if (verboseLog) diff --git a/IOB-WIN-SQL/Iob/IobFileSoitaab.cs b/IOB-WIN-SQL/Iob/IobFileSoitaab.cs index b18b422d..45a93973 100644 --- a/IOB-WIN-SQL/Iob/IobFileSoitaab.cs +++ b/IOB-WIN-SQL/Iob/IobFileSoitaab.cs @@ -3,6 +3,8 @@ using EgwProxy.SqlDb.DbModels; #endif using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; @@ -70,7 +72,7 @@ namespace IOB_WIN_SQL.IobFile lgError($"Eccezione in IobFileSoitaab{Environment.NewLine}{exc}"); } - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); } #endregion Public Constructors @@ -87,7 +89,7 @@ namespace IOB_WIN_SQL.IobFile DateTime adesso = DateTime.Now; // NON fa nulla... anche se non dovrebbe richiamarlo Dictionary taskDone = new Dictionary(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return taskDone; } @@ -101,7 +103,7 @@ namespace IOB_WIN_SQL.IobFile Dictionary outVal = new Dictionary(); // processo ed accodo! processFluxLogTable(adesso); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -115,10 +117,10 @@ namespace IOB_WIN_SQL.IobFile if (connectionOk) { // controllo veto checkDB - if (adesso > vetoDataRead) + if (adesso > DtHelp.vetoDataRead) { // predispongo prox veto... - vetoDataRead = adesso.AddSeconds(vetoReadFileSec); + DtHelp.vetoDataRead = adesso.AddSeconds(vetoReadFileSec); // semaforo currDispData.semIn = Semaforo.SV; // verifico SignLog e processo @@ -143,14 +145,14 @@ namespace IOB_WIN_SQL.IobFile if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("FileSoitaab: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -173,7 +175,7 @@ namespace IOB_WIN_SQL.IobFile if (adpRunning) { lgInfo($"Connessione OK alla folder {logDirPath}"); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } else @@ -452,7 +454,7 @@ namespace IOB_WIN_SQL.IobFile if (queueInEnabCurr) { // --> accodo (valore già formattato)! - QueueIN.Enqueue(currVal); + QHelp.QueueIN.Enqueue(currVal); // loggo! lgTrace(string.Format("[QUEUE-IN] {0}", currVal)); counterSigIN++; diff --git a/IOB-WIN-SQL/IobSql/IcoelDb.cs b/IOB-WIN-SQL/IobSql/IcoelDb.cs index adac4967..db914ed8 100644 --- a/IOB-WIN-SQL/IobSql/IcoelDb.cs +++ b/IOB-WIN-SQL/IobSql/IcoelDb.cs @@ -1,6 +1,8 @@ using EgwProxy.Icoel; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; @@ -52,7 +54,7 @@ namespace IOB_WIN_SQL.IobSql // eccezione: NON TROVA EntityFramework 6.0.0 o successivo... why?!? dbProxy = new DbProxy(connSyncState); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); } #endregion Public Constructors @@ -101,7 +103,7 @@ namespace IOB_WIN_SQL.IobSql } } } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return taskDone; } @@ -129,7 +131,7 @@ namespace IOB_WIN_SQL.IobSql saveValue(ref outVal, item.Topic, (double)item.CurrVal); } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -143,7 +145,7 @@ namespace IOB_WIN_SQL.IobSql lgInfo($"Richiesto processCustomTaskLF"); // effettua sync refreshElencoStati(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } /// @@ -180,14 +182,14 @@ namespace IOB_WIN_SQL.IobSql if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("IcoelSoap: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -213,7 +215,7 @@ namespace IOB_WIN_SQL.IobSql if (adpRunning) { lgInfo("Connessione OK"); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } else @@ -273,7 +275,7 @@ namespace IOB_WIN_SQL.IobSql sw.Start(); elencoSyncState = dbProxy.DataController.SyncStateDoImportAll(); sw.Stop(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; lgInfo($"DB: esecuzione task dbProxy.DataController.SyncStateGetAll() in {sw.ElapsedMilliseconds} ms"); if (elencoSyncState != null) diff --git a/IOB-WIN-SQL/IobSql/SqlServLantek.cs b/IOB-WIN-SQL/IobSql/SqlServLantek.cs index f292a883..821347d7 100644 --- a/IOB-WIN-SQL/IobSql/SqlServLantek.cs +++ b/IOB-WIN-SQL/IobSql/SqlServLantek.cs @@ -2,7 +2,9 @@ using EgwProxy.SqlDb.DbModels; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using System; @@ -68,7 +70,7 @@ namespace IOB_WIN_SQL.IobSql // avvio DB controller dbProxy = new DbController(connSyncState); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); } #endregion Public Constructors @@ -210,7 +212,7 @@ namespace IOB_WIN_SQL.IobSql } } } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return taskDone; } @@ -224,7 +226,7 @@ namespace IOB_WIN_SQL.IobSql // dizionario vuoto / gestito da altro adapter file-based Dictionary outVal = new Dictionary(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -238,7 +240,7 @@ namespace IOB_WIN_SQL.IobSql // effettua sync execExportAll(); execImportAll(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } /// @@ -251,15 +253,15 @@ namespace IOB_WIN_SQL.IobSql if (connectionOk) { // controllo veto checkDB - if (adesso > vetoDataRead) + if (adesso > DtHelp.vetoDataRead) { // predispongo prox veto... - vetoDataRead = adesso.AddSeconds(vetoReadDbSec); - if (adesso > vetoDataSync) + DtHelp.vetoDataRead = adesso.AddSeconds(vetoReadDbSec); + if (adesso > DtHelp.vetoDataSync) { // effettua sync execImportAll(); - vetoDataSync = adesso.AddSeconds(VetoSyncDbSec); + DtHelp.vetoDataSync = adesso.AddSeconds(VetoSyncDbSec); } // semaforo @@ -285,14 +287,14 @@ namespace IOB_WIN_SQL.IobSql if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("SqlDb LANTEK: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -318,7 +320,7 @@ namespace IOB_WIN_SQL.IobSql if (adpRunning) { lgInfo("Connessione OK"); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } else @@ -391,7 +393,7 @@ namespace IOB_WIN_SQL.IobSql elencoSyncState = dbProxy.SyncStateDoExportAll(); sw.Stop(); DateTime adesso = DateTime.Now; - lastReadPLC = adesso; + DtHelp.lastReadPLC = adesso; lgInfo($"DB: esecuzione task dbProxy.SyncStateDoExportAll() in {sw.ElapsedMilliseconds} ms"); if (elencoSyncState != null) @@ -438,7 +440,7 @@ namespace IOB_WIN_SQL.IobSql sw.Start(); elencoSyncState = dbProxy.SyncStateDoImportAll(); sw.Stop(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; lgInfo($"DB: esecuzione task dbProxy.SyncStateDoImportAll() in {sw.ElapsedMilliseconds} ms"); if (elencoSyncState != null) diff --git a/IOB-WIN-SQL/IobSql/SqlServPama.cs b/IOB-WIN-SQL/IobSql/SqlServPama.cs index 5d0648c6..abd61375 100644 --- a/IOB-WIN-SQL/IobSql/SqlServPama.cs +++ b/IOB-WIN-SQL/IobSql/SqlServPama.cs @@ -2,7 +2,9 @@ using EgwProxy.SqlDb.DbModels; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; -using IOB_UT_NEXT.Iob.Services; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; +using IOB_UT_NEXT.Services.Networking; using MapoSDK; using Newtonsoft.Json; using System; @@ -66,7 +68,7 @@ namespace IOB_WIN_SQL.IobSql // eccezione: NON TROVA EntityFramework 6.0.0 o successivo... why?!? dbProxy = new DbController(connSyncState); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); } #endregion Public Constructors @@ -208,7 +210,7 @@ namespace IOB_WIN_SQL.IobSql } } } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return taskDone; } @@ -225,7 +227,7 @@ namespace IOB_WIN_SQL.IobSql // processo ed accodo! processFluxLogTable(adesso); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -238,7 +240,7 @@ namespace IOB_WIN_SQL.IobSql lgInfo($"Richiesto processCustomTaskLF"); // effettua sync execImportAll(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } /// @@ -251,15 +253,15 @@ namespace IOB_WIN_SQL.IobSql if (connectionOk) { // controllo veto checkDB - if (adesso > vetoDataRead) + if (adesso > DtHelp.vetoDataRead) { // predispongo prox veto... - vetoDataRead = adesso.AddSeconds(vetoReadDbSec); - if (adesso > vetoDataSync) + DtHelp.vetoDataRead = adesso.AddSeconds(vetoReadDbSec); + if (adesso > DtHelp.vetoDataSync) { // effettua sync execImportAll(); - vetoDataSync = adesso.AddSeconds(VetoSyncDbSec); + DtHelp.vetoDataSync = adesso.AddSeconds(VetoSyncDbSec); } // semaforo @@ -287,14 +289,14 @@ namespace IOB_WIN_SQL.IobSql if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("SqlDb PAMA: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -320,7 +322,7 @@ namespace IOB_WIN_SQL.IobSql if (adpRunning) { lgInfo("Connessione OK"); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } } else @@ -393,7 +395,7 @@ namespace IOB_WIN_SQL.IobSql elencoSyncState = dbProxy.SyncStateDoExportAll(); sw.Stop(); DateTime adesso = DateTime.Now; - lastReadPLC = adesso; + DtHelp.lastReadPLC = adesso; lgInfo($"DB: esecuzione task dbProxy.SyncStateDoExportAll() in {sw.ElapsedMilliseconds} ms"); if (elencoSyncState != null) @@ -440,7 +442,7 @@ namespace IOB_WIN_SQL.IobSql sw.Start(); elencoSyncState = dbProxy.SyncStateDoImportAll(); sw.Stop(); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; lgInfo($"DB: esecuzione task dbProxy.SyncStateDoImportAll() in {sw.ElapsedMilliseconds} ms"); if (elencoSyncState != null) @@ -680,7 +682,7 @@ namespace IOB_WIN_SQL.IobSql if (queueInEnabCurr) { // --> accodo (valore già formattato)! - QueueIN.Enqueue(currVal); + QHelp.QueueIN.Enqueue(currVal); // loggo! lgTrace(string.Format("[QUEUE-IN] {0}", currVal)); counterSigIN++; diff --git a/IOB-WIN-WPS/IobNet/WebPageScrap.cs b/IOB-WIN-WPS/IobNet/WebPageScrap.cs index 84902de4..cc9013f1 100644 --- a/IOB-WIN-WPS/IobNet/WebPageScrap.cs +++ b/IOB-WIN-WPS/IobNet/WebPageScrap.cs @@ -1,5 +1,6 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; using MapoSDK; using Newtonsoft.Json; using OpenQA.Selenium; diff --git a/IOB-WIN-WS/IobWs/Citizen.cs b/IOB-WIN-WS/IobWs/Citizen.cs index 061084e2..f67f2341 100644 --- a/IOB-WIN-WS/IobWs/Citizen.cs +++ b/IOB-WIN-WS/IobWs/Citizen.cs @@ -1,5 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using Newtonsoft.Json; using System; @@ -28,9 +30,9 @@ namespace IOB_WIN_WS.IobWs public Citizen(AdapterFormNext caller, IobConfTree IobConfFull) : base(caller, IobConfFull) { lgInfo($"Richiesto Adapter IobRest.RestCitizen con i parametri seguenti | ADDR: {IOBConfFull.Device.Connect.IpAddr} | PORT: {IOBConfFull.Device.Connect.Port}"); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); redKeyAlarm = redisMan.redHash($"IOB:Status:{IOBConfFull.General.CodIOB}:Alarm:LastRead"); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); // predispongo configurazione specifica Rest... lgInfo("Rest - 01"); if (!string.IsNullOrEmpty(getOptPar("REST_CONF"))) @@ -276,14 +278,14 @@ namespace IOB_WIN_WS.IobWs if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("Rest: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; bool checkMachine = false; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) diff --git a/IOB-WIN-WS/IobWs/EmmegiFPW.cs b/IOB-WIN-WS/IobWs/EmmegiFPW.cs index bcc1170d..c2a72ecc 100644 --- a/IOB-WIN-WS/IobWs/EmmegiFPW.cs +++ b/IOB-WIN-WS/IobWs/EmmegiFPW.cs @@ -1,15 +1,16 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Config.Special; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Globalization; -using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net.NetworkInformation; -using System.Runtime.Remoting.Contexts; using System.Threading.Tasks; using System.Xml.Serialization; using static IOB_UT_NEXT.CustomObj; @@ -32,9 +33,9 @@ namespace IOB_WIN_WS.IobWs public EmmegiFPW(AdapterFormNext caller, IobConfTree IobConfFull) : base(caller, IobConfFull) { lgInfo($"Richiesto Adapter IobRest.EmmegiFPW con i parametri seguenti | ADDR: {IOBConfFull.Device.Connect.IpAddr} | PORT: {IOBConfFull.Device.Connect.Port}"); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); redKeyAlarm = redisMan.redHash($"IOB:Status:{IOBConfFull.General.CodIOB}:Alarm:LastRead"); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); // predispongo configurazione specifica Rest... lgInfo("01 - Rest"); if (!string.IsNullOrEmpty(getOptPar("REST_CONF"))) @@ -53,7 +54,7 @@ namespace IOB_WIN_WS.IobWs if (!string.IsNullOrEmpty(FileConfPath)) { // fix exclToolDirPath - exclToolDirPath = Path.Combine(fileMover.GetExecutingDirectoryName(), "Tools"); + exclToolDirPath = Path.Combine(FileMover.GetExecutingDirectoryName(), "Tools"); string fullPath = Path.Combine(exclToolDirPath, FileConfPath); if (File.Exists(fullPath)) { @@ -220,14 +221,14 @@ namespace IOB_WIN_WS.IobWs if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("Rest: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { diff --git a/IOB-WIN-WS/IobWs/Gomba.cs b/IOB-WIN-WS/IobWs/Gomba.cs index 68547ad5..4efc4448 100644 --- a/IOB-WIN-WS/IobWs/Gomba.cs +++ b/IOB-WIN-WS/IobWs/Gomba.cs @@ -1,6 +1,8 @@ using EgwProxy.Gomba.GombaServ; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using Newtonsoft.Json; using System; @@ -29,7 +31,7 @@ namespace IOB_WIN_WS.IobWs { lgInfo($"Richiesto Adapter IobSoap.Gomba con i parametri seguenti | ADDR: {IOBConfFull.Device.Connect.IpAddr} | PORT: {IOBConfFull.Device.Connect.Port}"); redKeyPesate = redisMan.redHash($"IOB:Status:{IOBConfFull.General.CodIOB}:ListPesate"); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); // verifico se sia attiva gestione riduzione FluxLog... if (!string.IsNullOrEmpty(getOptJsonKVP("numLastWeight"))) { @@ -188,7 +190,7 @@ namespace IOB_WIN_WS.IobWs lgInfo($"getDynData | SOAP: effettuata chiamata reqWeightList in {sw.Elapsed.TotalMilliseconds}ms | {dataFrom} --> {dataTo} | {listPesateCurr.Count} rec"); } // indico esecuzione e proseguo - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -232,14 +234,14 @@ namespace IOB_WIN_WS.IobWs if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("Gomba: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { diff --git a/IOB-WIN-WS/IobWs/IcoelSoap.cs b/IOB-WIN-WS/IobWs/IcoelSoap.cs index 7c357b9c..6030121d 100644 --- a/IOB-WIN-WS/IobWs/IcoelSoap.cs +++ b/IOB-WIN-WS/IobWs/IcoelSoap.cs @@ -2,6 +2,8 @@ using EgwProxy.Icoel.SizerService; using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using System; using System.Collections.Generic; @@ -41,7 +43,7 @@ namespace IOB_WIN_WS.IobWs */ IcoelSizer = new Connector(IOBConfFull.Device.Connect.IpAddr, IOBConfFull.Device.Connect.Port); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); } #endregion Public Constructors @@ -152,7 +154,7 @@ namespace IOB_WIN_WS.IobWs saveValueString(ref outVal, item.Key, item.Value); } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -186,7 +188,7 @@ namespace IOB_WIN_WS.IobWs } } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } /// @@ -256,14 +258,14 @@ namespace IOB_WIN_WS.IobWs if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("IcoelSoap: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { @@ -393,7 +395,7 @@ namespace IOB_WIN_WS.IobWs lgTrace("SOAP: effettuata chiamata IcoelSizer.GetLayoutForVarietyList()"); } - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } #endregion Protected Methods diff --git a/IOB-WIN-WS/IobWs/RestBase.cs b/IOB-WIN-WS/IobWs/RestBase.cs index c7004071..ea646980 100644 --- a/IOB-WIN-WS/IobWs/RestBase.cs +++ b/IOB-WIN-WS/IobWs/RestBase.cs @@ -1,5 +1,7 @@ using IOB_UT_NEXT; using IOB_UT_NEXT.Config; +using IOB_UT_NEXT.Objects; +using IOB_UT_NEXT.Services.Files; using MapoSDK; using Newtonsoft.Json; using RestSharp; @@ -28,7 +30,7 @@ namespace IOB_WIN_WS.IobWs public RestBase(AdapterFormNext caller, IobConfTree IobConfFull) : base(caller, IobConfFull) { lgInfo($"Richiesto Adapter IobRest.Base con i parametri seguenti | ADDR: {IOBConfFull.Device.Connect.IpAddr} | PORT: {IOBConfFull.Device.Connect.Port}"); - lastPING = DateTime.Now.AddHours(-1); + DtHelp.lastPING = DateTime.Now.AddHours(-1); // predispongo configurazione specifica Rest... if (!string.IsNullOrEmpty(getOptPar("REST_CONF"))) { @@ -123,7 +125,7 @@ namespace IOB_WIN_WS.IobWs // valore non presente in vers default... se gestito fare override Dictionary outVal = new Dictionary(); // indico esecuzione e proseguo - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; return outVal; } @@ -134,7 +136,7 @@ namespace IOB_WIN_WS.IobWs public override void readSemafori(ref newDisplayData currDispData) { DateTime adesso = DateTime.Now; - lastReadPLC = adesso; + DtHelp.lastReadPLC = adesso; // verifico non sia in veto invio iniziale... if (queueInEnabCurr) { @@ -169,14 +171,14 @@ namespace IOB_WIN_WS.IobWs if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { lgInfo("Rest: ConnKO - tryConnect"); } // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // se passa il ping faccio il resto... if (testPingMachine == IPStatus.Success) { diff --git a/IOB-WIN.sln b/IOB-WIN.sln index 1616467b..08db1cc0 100644 --- a/IOB-WIN.sln +++ b/IOB-WIN.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 -VisualStudioVersion = 17.12.35527.113 d17.12 +VisualStudioVersion = 17.12.35527.113 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IOB-WIN", "IOB-WIN\IOB-WIN.csproj", "{ADCB8028-79C4-4896-A9A7-E3C5140FC00B}" EndProject diff --git a/IOB-WIN/AdapterForm.cs b/IOB-WIN/AdapterForm.cs index 70377d58..6786ab59 100644 --- a/IOB-WIN/AdapterForm.cs +++ b/IOB-WIN/AdapterForm.cs @@ -1235,7 +1235,7 @@ namespace IOB_WIN counterMAC = iobObj.contapezziPLC, lastUpdate = lastIobStatus.lastUpdate, online = utils.IOB_Online, - lastDataIn = iobObj.lastReadPLC + lastDataIn = iobObj.DtHelp.lastReadPLC }; // se diverso SALVO! if (lastIobStatus.online != currIobStatus.online || lastIobStatus.lastDataIn != currIobStatus.lastDataIn || lastIobStatus.counterIOB != currIobStatus.counterIOB || lastIobStatus.counterMAC != currIobStatus.counterMAC || lastIobStatus.queueEvLen != currIobStatus.queueEvLen || lastIobStatus.queueFlLen != currIobStatus.queueFlLen || lastIobStatus.queueAlLen != currIobStatus.queueAlLen || lastIobStatus.queueMsLen != currIobStatus.queueMsLen) diff --git a/IOB-WIN/IobGeneric.cs b/IOB-WIN/IobGeneric.cs index 3a248edd..62052c1b 100644 --- a/IOB-WIN/IobGeneric.cs +++ b/IOB-WIN/IobGeneric.cs @@ -43,7 +43,7 @@ namespace IOB_WIN /// /// DataOra ultimo avvio adapter x watchdog /// - protected DateTime adpStartRun; + protected DateTime DtHelp.adpStartRun; /// /// Vettore 32 BIT valori in ingresso al filtro @@ -78,12 +78,12 @@ namespace IOB_WIN /// /// ultimo tentativo connessione... /// - protected DateTime lastConnectTry; + protected DateTime DtHelp.lastConnectTry; /// /// Ultimo invio contapezzi (x invio delayed) /// - protected DateTime lastPzCountSend; + protected DateTime DtHelp.lastPzCountSend; /// /// Dizionario ultimi valori (double) delle TSVC @@ -93,7 +93,7 @@ namespace IOB_WIN /// /// Ultima registrazione warning x ODL mancante (x scrivere solo ogni 15 secondi) /// - protected DateTime lastWarnODL; + protected DateTime DtHelp.lastWarnODL; /// /// indica se serva refresh parametri e quindi PLC... @@ -192,17 +192,17 @@ namespace IOB_WIN /// /// Data/ora ultimo avvio adapter /// - public DateTime dtAvvioAdp = DateTime.Now; + public DateTime DtHelp.AvvioAdp = DateTime.Now; /// /// Data/ora ultimo spegnimento adapter /// - public DateTime dtStopAdp = DateTime.Now; + public DateTime DtHelp.StopAdp = DateTime.Now; /// /// Indicazione VETO check status IOB x evitare loop troppo stretti... /// - public DateTime dtVetoCheckIOB = DateTime.Now.AddDays(-1); + public DateTime DtHelp.VetoCheckIOB = DateTime.Now.AddDays(-1); /// /// Abilitazione lettura PrgName @@ -222,43 +222,33 @@ namespace IOB_WIN /// /// dataOra ultima verifica CNC disconnesso... /// - public DateTime lastDisconnCheck; + public DateTime DtHelp.lastDisconnCheck; /// /// Data/ora ultima volta che IOB è stato dichairato online /// - public DateTime lastIobOnline = DateTime.Now.AddHours(-1); + public DateTime DtHelp.lastIobOnline = DateTime.Now.AddHours(-1); /// /// dataOra ultimo log periodico... /// - public DateTime lastPeriodicLog; + public DateTime DtHelp.lastPeriodicLog; /// /// dataOra ultimo PING inviato verso il PLC... /// - public DateTime lastPING; + public DateTime DtHelp.lastPING; /// /// DataOra ultima lettura da PLC /// - public DateTime lastReadPLC; + public DateTime DtHelp.lastReadPLC; /// /// ULtimo valore inviato (in caso di disconnessione lo reinvia x garantire watchdog...) /// public string lastSignInVal = ""; - /// - /// DateTime Ultimo valore simulazione generato - /// - public DateTime lastSim; - - /// - /// dataOra ultimo segnale inviato... - /// - public DateTime lastWatchDog; - /// /// Massimo numero di px da inviare in blocco /// @@ -292,22 +282,22 @@ namespace IOB_WIN /// /// Coda valori ALLARMI ove gestiti... /// - public ConcurrentQueue QueueAlarm = new ConcurrentQueue(); + public ConcurrentQueue QHelp.QueueAlarm = new ConcurrentQueue(); /// /// Oggetto della coda degli elementi letti di tipo FluxLog (e non ancora trasmessi) /// - public ConcurrentQueue QueueFLog = new ConcurrentQueue(); + public ConcurrentQueue QHelp.QueueFLog = new ConcurrentQueue(); /// /// Oggetto della coda degli elementi letti (e non ancora trasmessi) /// - public ConcurrentQueue QueueIN = new ConcurrentQueue(); + public ConcurrentQueue QHelp.QueueIN = new ConcurrentQueue(); /// /// Coda valori MESSAGGI/EVENTI (da non sottocampionare come samples)... /// - public ConcurrentQueue QueueMessages = new ConcurrentQueue(); + public ConcurrentQueue QHelp.QueueMessages = new ConcurrentQueue(); /// /// alias booleano false = R @@ -342,7 +332,7 @@ namespace IOB_WIN /// /// Imposta veto chiamata split (durante chiamata, per 60 sec) /// - public DateTime vetoSplit = DateTime.Now.AddMinutes(1); + public DateTime DtHelp.vetoSplit = DateTime.Now.AddMinutes(1); /// /// alias booleano true = W @@ -373,7 +363,7 @@ namespace IOB_WIN // configurazione... cIobConf = IOBConf; - lastConnectTry = DateTime.Now; + DtHelp.lastConnectTry = DateTime.Now; // aggiungo nel logger IDX Macchina lg = LogManager.GetCurrentClassLogger(); @@ -418,11 +408,11 @@ namespace IOB_WIN { bool answ = false; // controllo se ho veto al check... - if (dtVetoCheckIOB < DateTime.Now) + if (DtHelp.VetoCheckIOB < DateTime.Now) { if (DemoOut) { - answ = (QueueIN.Count + QueueFLog.Count >= nMaxSend); + answ = (QHelp.QueueIN.Count + QHelp.QueueFLog.Count >= nMaxSend); } else { @@ -464,9 +454,9 @@ namespace IOB_WIN // se online imposto veto check a 5 x tempo reinvio... if (answ) { - lastIobOnline = DateTime.Now; + DtHelp.lastIobOnline = DateTime.Now; } - dtVetoCheckIOB = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 5); + DtHelp.VetoCheckIOB = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 5); } catch { } @@ -700,15 +690,15 @@ namespace IOB_WIN /// /// Indicazione VETO PING a server sino alla data-ora indicata /// - public static DateTime dtVetoPing + public static DateTime DtHelp.dtVetoPing { get { - return utils.dtVetoPing; + return utils.DtHelp.dtVetoPing; } set { - utils.dtVetoPing = value; + utils.DtHelp.dtVetoPing = value; } } @@ -751,7 +741,7 @@ namespace IOB_WIN { bool answ = false; // controllo se ho un VETO all'invio... - if (dtVetoPing < DateTime.Now) + if (DtHelp.dtVetoPing < DateTime.Now) { if (DemoOut) { @@ -820,7 +810,7 @@ namespace IOB_WIN { lgInfo("SERVER ONLINE in checkServerAlive"); parentForm.commSrvActive = 1; - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec); + DtHelp.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec); } else { @@ -833,7 +823,7 @@ namespace IOB_WIN else { // allungo periodo controllo... - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); + DtHelp.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); } } else @@ -841,8 +831,8 @@ namespace IOB_WIN lgInfo($"SERVER NOT RESPONDING (PING at {cIobConf.serverData.MPIP})"); MPOnline = false; // imposto veto a 10 volte reinvio dati standard... - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); - utils.dtVetoSend = dtVetoPing; + DtHelp.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); + utils.dtVetoSend = DtHelp.dtVetoPing; } } } @@ -1044,10 +1034,10 @@ namespace IOB_WIN get { bool answ = false; - answ = (DateTime.Now.Subtract(lastPeriodicLog).TotalSeconds > utils.CRI("verboseLogTOut")); + answ = (DateTime.Now.Subtract(DtHelp.lastPeriodicLog).TotalSeconds > utils.CRI("verboseLogTOut")); if (answ) { - lastPeriodicLog = DateTime.Now; + DtHelp.lastPeriodicLog = DateTime.Now; } return answ; @@ -1779,14 +1769,14 @@ namespace IOB_WIN // svuoto code se richiesto if (resetQueue) { - QueueIN = new ConcurrentQueue(); - QueueFLog = new ConcurrentQueue(); - QueueAlarm = new ConcurrentQueue(); - QueueMessages = new ConcurrentQueue(); + QHelp.QueueIN = new ConcurrentQueue(); + QHelp.QueueFLog = new ConcurrentQueue(); + QHelp.QueueAlarm = new ConcurrentQueue(); + QHelp.QueueMessages = new ConcurrentQueue(); } // imposto contatori blink a zero... i_counters = new int[32]; - lastPeriodicLog = DateTime.Now; + DtHelp.lastPeriodicLog = DateTime.Now; // fix parametri generali... enablePrgName = true; } @@ -1832,22 +1822,22 @@ namespace IOB_WIN private void svuotaCodaFLog() { //controllo se è passato oltre watchdog e non ho inviato nulla --> RE-INVIO (ultimo inviato)!!!! - if (DateTime.Now.Subtract(lastWatchDog).TotalSeconds > utils.CRI("watchdogMaxSec")) + if (DateTime.Now.Subtract(DtHelp.lastWatchDog).TotalSeconds > utils.CRI("watchdogMaxSec")) { string wdStatus = "elapsed"; string sVal = string.Format("[WDST]{0}", wdStatus); // chiamo accodamento... accodaFLog(sVal, qEncodeFLog("WDST", wdStatus)); - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } // verifico SE la coda abbia dei valori... - if (QueueFLog.Count > 0) + if (QHelp.QueueFLog.Count > 0) { // invio pacchetto di dati (max da conf) for (int i = 0; i < nMaxSend; i++) { // SE ho qualcosa in coda... - if (QueueFLog.Count > 0) + if (QHelp.QueueFLog.Count > 0) { string currVal = ""; if (MPOnline) @@ -1855,16 +1845,16 @@ namespace IOB_WIN if (IobOnline) { // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueFLog.Count > 1) + if (QHelp.QueueFLog.Count > 1) { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueFLog.Count > maxJsonData) + if (QHelp.QueueFLog.Count > maxJsonData) { // prendoi primi maxJsonDataValori for (int j = 0; j < maxJsonData; j++) { - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); listaValori.Add(currVal); } sendDataBlock(urlType.FLog, listaValori); @@ -1872,17 +1862,17 @@ namespace IOB_WIN else { // invio in blocco - listaValori = QueueFLog.ToList(); + listaValori = QHelp.QueueFLog.ToList(); // invio sendDataBlock(urlType.FLog, listaValori); // svuoto! - QueueFLog = new ConcurrentQueue(); + QHelp.QueueFLog = new ConcurrentQueue(); } } else { // INVIO SINGOLO...!!! - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); sendToMoonPro(urlType.FLog, currVal); } } @@ -2173,11 +2163,11 @@ namespace IOB_WIN { lgInfo("chiamata URL " + url2call); } - answ = HttpService.CallUrlNow(url2call); + answ = utils.callUrlNow(url2call); // se vuoto faccio seconda prova... if (string.IsNullOrEmpty(answ)) { - answ = HttpService.CallUrlNow(url2call); + answ = utils.callUrlNow(url2call); } return answ; } @@ -2200,7 +2190,7 @@ namespace IOB_WIN { lgInfo("chiamata URL " + url2call); } - answ = HttpService.CallUrlNow(url2call); + answ = utils.callUrlNow(url2call); } return answ; } @@ -2462,7 +2452,7 @@ namespace IOB_WIN { // invio su cloud conf memoria... string rawData = JsonConvert.SerializeObject(memMap); - HttpService.CallUrlNow($"{urlSaveMemMap}", rawData); + utils.callUrlNow($"{urlSaveMemMap}", rawData); // salvo ANCHE come parametri i valori... objItem currItem = new objItem(); List allParam = new List(); @@ -2490,7 +2480,7 @@ namespace IOB_WIN } // invio su cloud parametri! rawData = JsonConvert.SerializeObject(allParam); - HttpService.CallUrl($"{urlSaveAllParams}", rawData); + utils.callUrl($"{urlSaveAllParams}", rawData); } } catch (Exception exc) @@ -2565,7 +2555,7 @@ namespace IOB_WIN plcWriteParams(updatedPar); // invio su cloud parametri! string rawData = JsonConvert.SerializeObject(updatedPar); - HttpService.CallUrl($"{urlUpdateWriteParams}", rawData); + utils.callUrl($"{urlUpdateWriteParams}", rawData); } } catch (Exception exc) @@ -2608,7 +2598,7 @@ namespace IOB_WIN { string url2call = $"{urlRemTask2Exe}{taskName}"; lgInfo($"Task2Exe | {esitoTask} | chiamata URL {url2call}"); - answ = HttpService.CallUrlNow(url2call); + answ = utils.callUrlNow(url2call); } return answ; } @@ -2621,7 +2611,7 @@ namespace IOB_WIN if (checkServerAlive) { lgInfo("chiamata URL " + urlSetM2IOB); - HttpService.CallUrlNow(urlSetM2IOB); + utils.callUrlNow(urlSetM2IOB); } } @@ -2636,7 +2626,7 @@ namespace IOB_WIN { string url2call = $"{urlSetOptVal}pName={paramName}&pValue={paramValue}"; lgInfo("chiamata URL " + url2call); - HttpService.CallUrlNow(url2call); + utils.callUrlNow(url2call); } } @@ -2737,14 +2727,14 @@ namespace IOB_WIN // Chiamata ASINCRONA if (doAsync) { - //Task resp = HttpService.CallUrlAsync(URL); + //Task resp = utils.callUrlAsync(URL); //answ = resp.Result; - answ = HttpService.CallUrlAsync(URL); + answ = utils.callUrlAsync(URL); } // chiamata SOLO NORMALE SINCRONA... else { - answ = HttpService.CallUrl(URL); + answ = utils.callUrl(URL); } return answ; } @@ -2762,12 +2752,12 @@ namespace IOB_WIN // Chiamata ASINCRONA if (doAsync) { - answ = HttpService.CallUrlAsync(URL, payload); + answ = utils.callUrlAsync(URL, payload); } // chiamata SOLO NORMALE SINCRONA... else { - answ = HttpService.CallUrl(URL, payload); + answ = utils.callUrl(URL, payload); } return answ; } @@ -2817,7 +2807,7 @@ namespace IOB_WIN // mostro dati variati letti... displayOtherData(val); // accodo IN PRIMIS al FluxLog --> accodo (valore già formattato)! - QueueFLog.Enqueue(encodedVal); + QHelp.QueueFLog.Enqueue(encodedVal); // accodo ANCHE alla coda allarmi che trasmetterò SOLO SE a scadenza impostata (10 sec?) ho allarmi perdurati... // loggo! @@ -2839,18 +2829,18 @@ namespace IOB_WIN // mostro dati variati letti... displayOtherData(val); // --> accodo (valore già formattato)! - QueueFLog.Enqueue(encodedVal); + QHelp.QueueFLog.Enqueue(encodedVal); // se abilitato controllo coda FLog (superiore a 0...) if (maxQueueFLog > 0) { // se ho una coda superiore a max ammesso - if (QueueFLog.Count > maxQueueFLog) + if (QHelp.QueueFLog.Count > maxQueueFLog) { // elimino valori iniziali fino a tornare al max ammesso... - while (QueueFLog.Count > maxQueueFLog) + while (QHelp.QueueFLog.Count > maxQueueFLog) { string currVal = ""; - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); lgInfo($"Eliminazione ca coda FLog per superamento maxLengh: {currVal}"); } } @@ -2885,7 +2875,7 @@ namespace IOB_WIN // mostro dati variati letti... displayInData(ref currDispData); // --> accodo (valore già formattato)! - QueueIN.Enqueue(qEncodeIN); + QHelp.QueueIN.Enqueue(qEncodeIN); // loggo! lgInfo(string.Format("[QUEUE-IN] {0}", qEncodeIN)); // aggiorno counters ed eventuale reset @@ -3080,10 +3070,10 @@ namespace IOB_WIN public bool forceSplitOdl() { bool fatto = false; - if (vetoSplit < DateTime.Now) + if (DtHelp.vetoSplit < DateTime.Now) { // imposto veto x 1 minuto ad altre chiamate... - vetoSplit = DateTime.Now.AddMinutes(1); + DtHelp.vetoSplit = DateTime.Now.AddMinutes(1); // eseguo SOLO SE sono online... if (MPOnline && IobOnline) { @@ -3194,13 +3184,13 @@ namespace IOB_WIN { // imposto flag adapter running.. adpCommAct = true; - adpStartRun = DateTime.Now; + DtHelp.adpStartRun = DateTime.Now; } catch (Exception exc) { string errore = $"Adapter NOT STARTED!!!{Environment.NewLine}{exc}"; adpCommAct = false; - adpStartRun = DateTime.Now; + DtHelp.adpStartRun = DateTime.Now; currDispData.newLiveLogData = errore; } if (adpCommAct) @@ -3288,11 +3278,11 @@ namespace IOB_WIN // log ADP running lgError("Non eseguo chiamata: ADP ancora in running"); // se è bloccato da oltre maxSec lo sblocco... - if (DateTime.Now.Subtract(adpStartRun).TotalSeconds > utils.CRI("maxAdapterLockSec")) + if (DateTime.Now.Subtract(DtHelp.adpStartRun).TotalSeconds > utils.CRI("maxAdapterLockSec")) { // tolgo flag running adpCommAct = false; - adpStartRun = DateTime.Now; + DtHelp.adpStartRun = DateTime.Now; } } } @@ -3303,11 +3293,11 @@ namespace IOB_WIN { // controllo se sia scaduto periodi di veto al tryConnect... int waitRecMSec = utils.CRI("waitRecMSec") * 2; - DateTime dtVeto = lastConnectTry.AddMilliseconds(waitRecMSec); + DateTime dtVeto = DtHelp.lastConnectTry.AddMilliseconds(waitRecMSec); if (DateTime.Now > dtVeto) { lgInfo($"Retry Time Elapsed (waited for {waitRecMSec} ms)--> NOW tryConnect"); - lastConnectTry = DateTime.Now; + DtHelp.lastConnectTry = DateTime.Now; tryConnect(); } } @@ -3554,16 +3544,16 @@ namespace IOB_WIN // loggo SOLO se del mio IOB corrente... if (item.classCall == cIobConf.codIOB) { - lgInfo("{4}|Chiamate {0}: effettuate {1}, tempo medio {2:N2} msec | impegno canale {3:P3}", item.codCall, item.numCall, item.avgMsec, item.totMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds, cIobConf.codIOB); + lgInfo("{4}|Chiamate {0}: effettuate {1}, tempo medio {2:N2} msec | impegno canale {3:P3}", item.codCall, item.numCall, item.avgMsec, item.totMsec.TotalSeconds / DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalSeconds, cIobConf.codIOB); globNumCall += item.numCall; globAvgMsec += item.totMsec; } } // riporto conteggio medio al secondo... - lgInfo("{4}|Chiamate GLOBALI: {0}, periodo: {1:N2} minuti.cent, tempo medio {2:N2} msec | impegno canale {3:P3}", globNumCall, DateTime.Now.Subtract(dtAvvioAdp).TotalMinutes, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds, cIobConf.codIOB); + lgInfo("{4}|Chiamate GLOBALI: {0}, periodo: {1:N2} minuti.cent, tempo medio {2:N2} msec | impegno canale {3:P3}", globNumCall, DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalMinutes, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalSeconds, cIobConf.codIOB); lgInfo("{0}--------------- STOP TIMING DATA ---------------{0}", Environment.NewLine); // mostro in form statistiche globali! - parentForm.updateComStats(string.Format("Periodo: {0:N2}min | {1} x {2:N2}ms | canale {3:P3}", DateTime.Now.Subtract(dtAvvioAdp).TotalMinutes, globNumCall, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds)); + parentForm.updateComStats(string.Format("Periodo: {0:N2}min | {1} x {2:N2}ms | canale {3:P3}", DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalMinutes, globNumCall, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(DtHelp.AvvioAdp).TotalSeconds)); } } @@ -3852,7 +3842,7 @@ namespace IOB_WIN // init obj display newDisplayData currDispData = new newDisplayData(); // controllo contatore invio "keepalive"... invio solo a scadenza - if (DateTime.Now.Subtract(lastDisconnCheck).TotalSeconds > utils.CRI("disconMaxSec")) + if (DateTime.Now.Subtract(DtHelp.lastDisconnCheck).TotalSeconds > utils.CRI("disconMaxSec")) { // resetto tutti i vlaori BYTE IN/PREV/OUT... così invio macchina spenta... B_input = 0; @@ -3860,7 +3850,7 @@ namespace IOB_WIN B_previous = 0; accodaSigIN(ref currDispData); // update controllo - lastDisconnCheck = DateTime.Now; + DtHelp.lastDisconnCheck = DateTime.Now; } raiseRefresh(currDispData); } @@ -3998,19 +3988,19 @@ namespace IOB_WIN if (checkServerAlive) { // leggo PRIMA ODL .... - lastIdxODL = HttpService.CallUrl(urlGetCurrODL); + lastIdxODL = utils.callUrl(urlGetCurrODL); lgInfo("Lettura ODL dall'url {0} --> {1}", urlGetCurrODL, lastIdxODL); // se ho valori in coda da trasmettere uso dati REDIS if (forceCountRec) { // uso dati da TCiclo registrati... - currServerCount = HttpService.CallUrl(urlGetPzCountRec); + currServerCount = utils.callUrl(urlGetPzCountRec); lgInfo("Lettura contapezzi da TCiclo dall'url {0} --> num pz: {1}", urlGetPzCountRec, currServerCount); } else { // uso il contapezzi dichiarato dall'IOB stesso - currServerCount = HttpService.CallUrl(urlGetPzCount); + currServerCount = utils.callUrl(urlGetPzCount); lgInfo("Lettura contapezzi dall'url {0}", urlGetPzCount); } // controllo: SE NON HO ODL... @@ -4118,7 +4108,7 @@ namespace IOB_WIN if (connectionOk) { readSemafori(ref currDispData); - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } else { @@ -4142,7 +4132,7 @@ namespace IOB_WIN /// public virtual void readSemafori(ref newDisplayData currDispData) { - lastReadPLC = DateTime.Now; + DtHelp.lastReadPLC = DateTime.Now; } /// @@ -4268,12 +4258,12 @@ namespace IOB_WIN { currDispData.semOut = Semaforo.SV; // se oltre 1 min NON era online --> check pezzi! - if (DateTime.Now.Subtract(lastIobOnline).TotalMinutes > 1 && !isMulti) + if (DateTime.Now.Subtract(DtHelp.lastIobOnline).TotalMinutes > 1 && !isMulti) { - lgInfo($"sendDataBlock --> offline timeout ({lastIobOnline}) --> pzCntReload(true)"); + lgInfo($"sendDataBlock --> offline timeout ({DtHelp.lastIobOnline}) --> pzCntReload(true)"); pzCntReload(true); } - lastIobOnline = DateTime.Now; + DtHelp.lastIobOnline = DateTime.Now; } else { @@ -4295,7 +4285,7 @@ namespace IOB_WIN // riporto cosa inviato currDispData.newUrlCallData = lastUrl; // aggiorno data ultimo watchdog... - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } catch { @@ -4344,9 +4334,9 @@ namespace IOB_WIN // loggo! lgInfo(string.Format("[SEND] {0} -> {1}", queueVal, answ)); // se oltre 1 min NON era online --> check pezzi! - if (DateTime.Now.Subtract(lastIobOnline).TotalMinutes > 1 && !isMulti) + if (DateTime.Now.Subtract(DtHelp.lastIobOnline).TotalMinutes > 1 && !isMulti) { - lgInfo($"sendToMoonPro --> offline timeaout ({lastIobOnline}) --> pzCntReload(true)"); + lgInfo($"sendToMoonPro --> offline timeaout ({DtHelp.lastIobOnline}) --> pzCntReload(true)"); pzCntReload(true); } // se richiesto effettuo refresh contapezzi @@ -4355,7 +4345,7 @@ namespace IOB_WIN pzCntReload(true); needRefreshPzCount = false; } - lastIobOnline = DateTime.Now; + DtHelp.lastIobOnline = DateTime.Now; // se "OK" verde, altrimenti errore --> ROSSO if (answ == "OK") { @@ -4384,7 +4374,7 @@ namespace IOB_WIN #endif currDispData.newUrlCallData = lastUrl; // aggiorno data ultimo watchdog... - lastWatchDog = DateTime.Now; + DtHelp.lastWatchDog = DateTime.Now; } catch { @@ -4436,11 +4426,11 @@ namespace IOB_WIN maxJsonDataEv = utils.CRI("maxJsonDataEv"); parentForm.commPlcActive = false; adpRunning = true; - dtAvvioAdp = DateTime.Now; - lastWatchDog = dtAvvioAdp; - lastPING = dtAvvioAdp; - lastReadPLC = dtAvvioAdp.AddMinutes(-1); - lastDisconnCheck = dtAvvioAdp; + DtHelp.AvvioAdp = DateTime.Now; + DtHelp.lastWatchDog = DtHelp.AvvioAdp; + DtHelp.lastPING = DtHelp.AvvioAdp; + DtHelp.lastReadPLC = DtHelp.AvvioAdp.AddMinutes(-1); + DtHelp.lastDisconnCheck = DtHelp.AvvioAdp; TimingData.resetData(); // aggiungo altri defaults setDefaults(resetQueue); @@ -4459,28 +4449,28 @@ namespace IOB_WIN { // svuoto le code dei valori letti e non ancora trasmessi... parentForm.displayTaskAndLog("[CLOSING] Svuotamento FORZATO coda segnali..."); - while (QueueIN.Count > 0) + while (QHelp.QueueIN.Count > 0) { // INVIO COMUNQUE...!!! string valore = ""; - QueueIN.TryDequeue(out valore); + QHelp.QueueIN.TryDequeue(out valore); sendToMoonPro(urlType.SignIN, valore); } parentForm.displayTaskAndLog("[CLOSING] Svuotamento FORZATO coda FluxLOG..."); // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueFLog.Count > minJsonData) + if (QHelp.QueueFLog.Count > minJsonData) { - while (QueueFLog.Count > 0) + while (QHelp.QueueFLog.Count > 0) { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueFLog.Count > maxJsonData) + if (QHelp.QueueFLog.Count > maxJsonData) { string currVal = ""; // prendoi primi maxJsonDataValori for (int i = 0; i < maxJsonData; i++) { - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); listaValori.Add(currVal); } sendDataBlock(urlType.FLog, listaValori); @@ -4488,11 +4478,11 @@ namespace IOB_WIN else { // invio in blocco - listaValori = QueueFLog.ToList(); + listaValori = QHelp.QueueFLog.ToList(); // invio sendDataBlock(urlType.FLog, listaValori); // svuoto! - QueueFLog = new ConcurrentQueue(); + QHelp.QueueFLog = new ConcurrentQueue(); } } // HO FINITO invio di FLog... @@ -4500,10 +4490,10 @@ namespace IOB_WIN else { string currVal = ""; - while (QueueFLog.Count > 0) + while (QHelp.QueueFLog.Count > 0) { // INVIO COMUNQUE...!!! - QueueFLog.TryDequeue(out currVal); + QHelp.QueueFLog.TryDequeue(out currVal); sendToMoonPro(urlType.FLog, currVal); } } @@ -4515,7 +4505,7 @@ namespace IOB_WIN // chiudo la connessione all'adapter... tryDisconnect(); - dtStopAdp = DateTime.Now; + DtHelp.StopAdp = DateTime.Now; adpTryRestart = tryRestart; adpRunning = false; // chiudo! @@ -4529,12 +4519,12 @@ namespace IOB_WIN public void svuotaCodaSignIN() { // verifico SE la coda abbia dei valori... - if (QueueIN.Count > 0) + if (QHelp.QueueIN.Count > 0) { // invio pacchetto di dati (max da conf) for (int i = 0; i < nMaxSend; i++) { - if (QueueIN.Count > 0) + if (QHelp.QueueIN.Count > 0) { string currVal = ""; // se online provo @@ -4543,16 +4533,16 @@ namespace IOB_WIN if (IobOnline) { // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueIN.Count > 1) + if (QHelp.QueueIN.Count > 1) { List listaValori = new List(); // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueIN.Count > maxJsonDataEv) + if (QHelp.QueueIN.Count > maxJsonDataEv) { // prendoi primi maxJsonDataValori for (int j = 0; j < maxJsonDataEv; j++) { - QueueIN.TryDequeue(out currVal); + QHelp.QueueIN.TryDequeue(out currVal); listaValori.Add(currVal); } sendDataBlock(urlType.SignIN, listaValori); @@ -4560,17 +4550,17 @@ namespace IOB_WIN else { // invio in blocco - listaValori = QueueIN.ToList(); + listaValori = QHelp.QueueIN.ToList(); // invio sendDataBlock(urlType.SignIN, listaValori); // svuoto! - QueueIN = new ConcurrentQueue(); + QHelp.QueueIN = new ConcurrentQueue(); } } else { // INVIO SINGOLO...!!! - QueueIN.TryDequeue(out currVal); + QHelp.QueueIN.TryDequeue(out currVal); sendToMoonPro(urlType.SignIN, currVal); } // salvo come last signal in il currVal ultimo... SE !="" @@ -4602,7 +4592,7 @@ namespace IOB_WIN /// public virtual void tryConnect() { - dtAvvioAdp = DateTime.Now; + DtHelp.AvvioAdp = DateTime.Now; } /// @@ -4640,7 +4630,7 @@ namespace IOB_WIN numIncr = delta > maxSendPzCountBlock + minSendPzCountBlock ? maxSendPzCountBlock : delta - minSendPzCountBlock; // invio il num max di pezzi ammesso in blocco! lastUrl = $"{urlAddPzCount}{numIncr}"; - string resp = HttpService.CallUrlNow(lastUrl); + string resp = utils.callUrlNow(lastUrl); if (!string.IsNullOrEmpty(resp)) { // dalla risposta (come numero) capisco SE ha aggiunto i pezzi (e quanti) @@ -4651,7 +4641,7 @@ namespace IOB_WIN contapezziIOB += qtyAdded; lgInfo($"Inviato incremento contapezzi: send: {numIncr} | resp: {qtyAdded} | contapezziIOB: {contapezziIOB}"); // invio conferma contapezzi.. - string retVal = HttpService.CallUrl($"{urlSetPzCount}{contapezziIOB}"); + string retVal = utils.callUrl($"{urlSetPzCount}{contapezziIOB}"); // verifica se tutto OK if (retVal != contapezziIOB.ToString()) { diff --git a/IOB-WIN/IobOSAI.cs b/IOB-WIN/IobOSAI.cs index b463435f..00820361 100644 --- a/IOB-WIN/IobOSAI.cs +++ b/IOB-WIN/IobOSAI.cs @@ -59,8 +59,8 @@ namespace IOB_WIN { // gestione invio ritardato contapezzi pzCountDelay = utils.CRI("pzCountDelay"); - lastPzCountSend = DateTime.Now; - lastWarnODL = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; if (IOBConf != null) { // inizializzo correttamente aree memoria secondo CONF - iniFileName @@ -214,7 +214,7 @@ namespace IOB_WIN { try { - currODL = HttpService.CallUrl(urlGetCurrODL); + currODL = utils.callUrl(urlGetCurrODL); // solo SE HO un ODL... if (string.IsNullOrEmpty(currODL) || currODL == "0") { @@ -232,10 +232,10 @@ namespace IOB_WIN } catch (Exception exc) { - if (DateTime.Now.Subtract(lastWarnODL).TotalSeconds > 15) + if (DateTime.Now.Subtract(DtHelp.lastWarnODL).TotalSeconds > 15) { lgError(exc, "Errore in fase di chiamata URL x ODL corrente | URL chiamato: {0}", urlGetCurrODL); - lastWarnODL = DateTime.Now; + DtHelp.lastWarnODL = DateTime.Now; } } } @@ -251,7 +251,7 @@ namespace IOB_WIN if (!string.IsNullOrEmpty(currODL) && currODL != "0") { // controllo se è passato intervallo minimo tra 2 controlli/elaborazioni x distanziare invio e ridurre letture - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { // se sono differenti MOSTRO... if (contapezziPLC != contapezziIOB) @@ -272,7 +272,7 @@ namespace IOB_WIN } // invio a server contapezzi (aggiornato) - string retVal = HttpService.CallUrl(urlSetPzCount + contapezziIOB.ToString()); + string retVal = utils.callUrl(urlSetPzCount + contapezziIOB.ToString()); // verifica se tutto OK if (retVal.Trim() != $"{contapezziIOB}") { @@ -282,16 +282,16 @@ namespace IOB_WIN pzCntReload(true); } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } else { - if (DateTime.Now >= lastPzCountSend.AddMilliseconds(pzCountDelay)) + if (DateTime.Now >= DtHelp.lastPzCountSend.AddMilliseconds(pzCountDelay)) { lgInfo($"Attenzione: mancanza ODL non procedo con gestione contapezzi. contapezziPLC OSAI: {contapezziPLC} | contapezziIOB {contapezziIOB}"); // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } } @@ -632,7 +632,7 @@ namespace IOB_WIN if (!connectionOk) { // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) + if (DateTime.Now.Subtract(DtHelp.lastPING).TotalSeconds > utils.CRI("pingTestSec")) { if (verboseLog || periodicLog) { @@ -647,7 +647,7 @@ namespace IOB_WIN if (needPing) { // in primis salvo data ping... - lastPING = DateTime.Now; + DtHelp.lastPING = DateTime.Now; // ora PING!!! IPAddress address = IPAddress.Loopback; IPAddress.TryParse(cIobConf.cncIpAddr, out address); @@ -674,7 +674,7 @@ namespace IOB_WIN // refresh stato allarmi!!! if (connectionOk) { - dtAvvioAdp = DateTime.Now; + DtHelp.AvvioAdp = DateTime.Now; if (adpRunning) { lgInfo("Connessione OK"); diff --git a/IOB-WIN/IobSimula.cs b/IOB-WIN/IobSimula.cs index 4560f9aa..b09c88bd 100644 --- a/IOB-WIN/IobSimula.cs +++ b/IOB-WIN/IobSimula.cs @@ -47,12 +47,7 @@ namespace IOB_WIN /// /// ultimo controllo decremento eventi /// - protected DateTime lastEvCheck; - - /// - /// Ultimo istante in cui sono stati generati dati di simulazione - /// - protected DateTime lastSimData; + protected DateTime DtHelp.lastEvCheck; /// /// Durata minima ODL x reset quando pezzi iob > pezzi macchina... @@ -112,10 +107,10 @@ namespace IOB_WIN // gestione invio ritardato contapezzi DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; - lastEvCheck = adesso; - lastSimData = adesso; + DtHelp.lastPzCountSend = adesso; + DtHelp.lastWarnODL = adesso; + DtHelp.lastEvCheck = adesso; + DtHelp.lastSimData = adesso; // sistemo parametri x simulazione... if (cIobConf.optPar.Count > 0) { @@ -246,7 +241,7 @@ namespace IOB_WIN contapezziIOB++; needRefreshPzCount = true; // invio conferma contapezzi.. - string retVal = HttpService.CallUrl($"{urlSetPzCount}{contapezziIOB}"); + string retVal = utils.callUrl($"{urlSetPzCount}{contapezziIOB}"); // verifica salvataggio if (retVal != contapezziIOB.ToString()) { @@ -258,7 +253,7 @@ namespace IOB_WIN } else { - string retVal = HttpService.CallUrl($"{urlSetPzCount}{contapezziIOB}"); + string retVal = utils.callUrl($"{urlSetPzCount}{contapezziIOB}"); if (retVal != contapezziIOB.ToString()) { // errore salvataggio contapezzi @@ -398,7 +393,7 @@ namespace IOB_WIN if (checkServerAlive) { // invio a server contapezzi (aggiornato) - string retVal = HttpService.CallUrl(urlSetPzCount + contapezziIOB.ToString()); + string retVal = utils.callUrl(urlSetPzCount + contapezziIOB.ToString()); // verifica se tutto OK if (retVal != contapezziIOB.ToString()) { @@ -412,7 +407,7 @@ namespace IOB_WIN } } // resetto timer... - lastPzCountSend = DateTime.Now; + DtHelp.lastPzCountSend = DateTime.Now; } } // provo a fare split ODL SE NON E' multi.... @@ -642,7 +637,7 @@ namespace IOB_WIN // valore non presente in vers default... se gestito fare override Dictionary outVal = new Dictionary(); // verificare periodo SIM parametri... se passato li invio altrimenti NO... FIX a 20 sec - if (lastSimData.AddSeconds(waitSimPar) < DateTime.Now) + if (DtHelp.lastSimData.AddSeconds(waitSimPar) < DateTime.Now) { Random rnd = new Random(); // controllo conf memorie json (se ci sono...) @@ -667,7 +662,7 @@ namespace IOB_WIN } catch { } - lastSimData = DateTime.Now; + DtHelp.lastSimData = DateTime.Now; } return outVal; } @@ -706,14 +701,14 @@ namespace IOB_WIN /// public override void processVHF() { - if (lastEvCheck.AddMilliseconds(periodoMSec) < DateTime.Now) + if (DtHelp.lastEvCheck.AddMilliseconds(periodoMSec) < DateTime.Now) { // decremento contatore ultimo evento bit2.wait--; bit3.wait--; bit4.wait--; bit5.wait--; - lastEvCheck = DateTime.Now; + DtHelp.lastEvCheck = DateTime.Now; } } diff --git a/IOB-WIN/MainForm.cs b/IOB-WIN/MainForm.cs index 77a7c6a3..a01f0fc4 100644 --- a/IOB-WIN/MainForm.cs +++ b/IOB-WIN/MainForm.cs @@ -321,7 +321,7 @@ namespace IOB_WIN bool answ = false; if (!string.IsNullOrEmpty(MPIP)) { - if (utils.dtVetoPing < DateTime.Now) + if (utils.DtHelp.dtVetoPing < DateTime.Now) { IPStatus pingStatus = testPingServer; // se passa il ping faccio il resto... @@ -330,7 +330,7 @@ namespace IOB_WIN try { // chiamo URL, se restituisce "OK" è alive! - string callResp = HttpService.CallUrl(urlAlive); + string callResp = utils.callUrl(urlAlive); answ = (callResp == "OK"); } catch (Exception exc) @@ -344,7 +344,7 @@ namespace IOB_WIN if (answ) { lgInfo("SERVER ONLINE"); - utils.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec); + utils.DtHelp.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec); } else { @@ -356,7 +356,7 @@ namespace IOB_WIN else { // allungo periodo controllo... - utils.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); + utils.DtHelp.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); } } else @@ -365,8 +365,8 @@ namespace IOB_WIN utils.MPIO_Online = false; updateComStats(0, 0, false); // imposto veto a 10 volte reinvio dati standard... - utils.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 10); - utils.dtVetoSend = utils.dtVetoPing; + utils.DtHelp.dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 10); + utils.dtVetoSend = utils.DtHelp.dtVetoPing; } } else @@ -563,7 +563,7 @@ namespace IOB_WIN // invio in locale! url2call = $"{urlDownloadFile}{currIob}"; } - rawData = HttpService.CallUrlNow(url2call); + rawData = utils.callUrlNow(url2call); if (!string.IsNullOrEmpty(rawData)) { // deserializzo @@ -894,12 +894,12 @@ namespace IOB_WIN if (utils.CRB("ConfToCloud")) { // invio su cloud... - answ = HttpService.CallUrl($"{urlUploadFileCloud}{currIob}", rawData); + answ = utils.callUrl($"{urlUploadFileCloud}{currIob}", rawData); } else { // invio in locale! - answ = HttpService.CallUrl($"{urlUploadFile}{currIob}", rawData); + answ = utils.callUrl($"{urlUploadFile}{currIob}", rawData); } } catch (Exception exc) @@ -1026,7 +1026,7 @@ namespace IOB_WIN if (pingStatus == IPStatus.Success) { // segnalo reboot (programma)... - HttpService.CallUrl(urlReboot); + utils.callUrl(urlReboot); } else { diff --git a/build_all.ps1 b/build_all.ps1 new file mode 100644 index 00000000..dbbe56e7 --- /dev/null +++ b/build_all.ps1 @@ -0,0 +1,56 @@ +# Cerca ricorsivamente solo le soluzioni che iniziano con 'IOB-WIN-' +$pattern = "IOB-WIN-*.sln" +$solutions = Get-ChildItem -Path . -Filter $pattern -Recurse + +if ($solutions.Count -eq 0) { + Write-Host "⚠️ Nessuna soluzione trovata che corrisponde al pattern: $pattern" -ForegroundColor Yellow + Exit +} + +Write-Host "🚀 Trovate $($solutions.Count) soluzioni da verificare." -ForegroundColor Magenta + +# Inizializzazione variabili per il riepilogo +$successCount = 0 +$failCount = 0 +$failedSolutions = @() + +foreach ($sol in $solutions) { + Write-Host "`n--------------------------------------------------" -ForegroundColor Cyan + Write-Host "Compilazione in corso: $($sol.Name)" -ForegroundColor White + Write-Host "--------------------------------------------------" -ForegroundColor Cyan + + # Esegue la compilazione + dotnet build $sol.FullName --configuration Debug --no-incremental + + if ($LASTEXITCODE -ne 0) { + Write-Host "❌ Errore nella compilazione di $($sol.Name)" -ForegroundColor Red + $failCount++ + $failedSolutions += $sol.Name + } + else { + Write-Host "✅ $($sol.Name) compilata con successo!" -ForegroundColor Green + $successCount++ + } +} + +# Determina il colore del testo per i fallimenti in modo retrocompatibile +$failColor = "Gray" +if ($failCount -gt 0) { $failColor = "Red" } + +# --- RIEPILOGO FINALE --- +Write-Host "`n==================================================" -ForegroundColor Magenta +Write-Host " 🏁 Processo di verifica completato!" -ForegroundColor Magenta +Write-Host "==================================================" -ForegroundColor Magenta +Write-Host " Successi: $successCount" -ForegroundColor Green +Write-Host " Falliti: $failCount" -ForegroundColor $failColor + +if ($failCount -gt 0) { + Write-Host "`n❌ Elenco delle soluzioni fallite:" -ForegroundColor Red + foreach ($failed in $failedSolutions) { + Write-Host " - $failed" -ForegroundColor Red + } +} +else { + Write-Host "`n🎉 Ottimo! Tutte le soluzioni sono state compilate senza errori." -ForegroundColor Green +} +Write-Host "==================================================" -ForegroundColor Magenta \ No newline at end of file diff --git a/build_all_par.ps1 b/build_all_par.ps1 new file mode 100644 index 00000000..f98d89ae --- /dev/null +++ b/build_all_par.ps1 @@ -0,0 +1,157 @@ +# --- CONFIGURAZIONE --- +$pattern = "IOB-WIN-*.sln" +$sharedProjectPath = ".\IOB-WIN-FORM\IOB-WIN-FORM.csproj" + +# Controllo robusto del parametro --agent (cerca in tutti gli argomenti passati) +$agentMode = $args -contains "--agent" + +# Avvia il cronometro per calcolare il tempo totale +$stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + +# 1. Trova l'MSBuild ufficiale di Visual Studio 2022 +$vsPaths = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -version "[17.0,18.0)" -products * -requires Microsoft.Component.MSBuild -property installationPath +if (-not $vsPaths) { + if ($agentMode) { exit 1 } + Write-Host "❌ Impossibile trovare Visual Studio 2022!" -ForegroundColor Red + Exit +} +$msbuildPath = Join-Path $vsPaths[0] "MSBuild\Current\Bin\MSBuild.exe" + +if (-not $agentMode) { + Write-Host "🎯 Usando MSBuild di VS2022: $msbuildPath" -ForegroundColor Gray +} + +# Cerca tutte le soluzioni escludendo cartelle di build +$solutions = Get-ChildItem -Path . -Filter $pattern -Recurse | Where-Object { + $_.FullName -notmatch '\\(bin|obj|\\.git|\\.vs)\\.' +} + +if ($solutions.Count -eq 0) { + if ($agentMode) { exit 1 } + Write-Host "⚠️ Nessuna soluzione trovata che corrisponde al pattern: $pattern" -ForegroundColor Yellow + Exit +} + +if (-not $agentMode) { + Write-Host "🚀 Trovate $($solutions.Count) soluzioni univoche." -ForegroundColor Magenta +} + +# FASE 1: Compilazione preventiva del progetto comune +if (Test-Path $sharedProjectPath) { + if (-not $agentMode) { Write-Host "`n📦 Fase 1: Compilazione del progetto comune condiviso..." -ForegroundColor Cyan } + + # AGGIORNAMENTO: Se siamo in agentMode silenziamo completamente MSBuild (/v:q) e ridirigiamo l'output + if ($agentMode) { + & $msbuildPath $sharedProjectPath /p:Configuration=Release /v:q /nologo > $null 2>&1 + } + else { + & $msbuildPath $sharedProjectPath /p:Configuration=Release /v:m /nologo + } + + if ($LASTEXITCODE -ne 0) { + if (-not $agentMode) { Write-Host "❌ Errore critico: Impossibile compilare il progetto comune. Interruzione." -ForegroundColor Red } + exit 1 + } + if (-not $agentMode) { Write-Host "✅ Progetto comune pronto." -ForegroundColor Green } +} + +# FASE 2: Compilazione parallela iniziale +if (-not $agentMode) { + Write-Host "`n🛠️ Fase 2: Avvio compilazione parallela delle soluzioni (Max 4)..." -ForegroundColor Magenta + Write-Host "==================================================" -ForegroundColor Magenta +} + +$parallelResults = $solutions | ForEach-Object -Parallel { + $solName = $_.Name + $solPath = $_.FullName + $msb = $using:msbuildPath + + # Aggiunto /nologo per evitare intestazioni ripetute nei log interni + $log = & $msb $solPath /p:Configuration=Release /m:1 /p:BuildInParallel=false /v:m /nologo 2>&1 + + [PSCustomObject]@{ + Name = $solName + FullName = $solPath + Success = ($LASTEXITCODE -eq 0) + Log = $log + } +} -ThrottleLimit 4 + +# --- ANALISI PRIMO ROUND E FASE 3 (RETRY SEQUENZIALE) --- +$successSolutions = @() +$failedToRetry = @() + +foreach ($res in $parallelResults) { + if ($res.Success) { + if (-not $agentMode) { Write-Host "✅ $($res.Name) compilata con successo (in parallelo)!" -ForegroundColor Green } + $successSolutions += $res.Name + } + else { + if (-not $agentMode) { Write-Host "⚠️ $($res.Name) fallita in parallelo. Accodata per il recupero sequenziale..." -ForegroundColor Yellow } + $failedToRetry += $res + } +} + +# Se ci sono falliti, li rieseguiamo UNO ALLA VOLTA pulendo la cache +if ($failedToRetry.Count -gt 0) { + if (-not $agentMode) { + Write-Host "`n🔄 Fase 3: Riesecuzione sequenziale dei task falliti ($($failedToRetry.Count) soluzioni)..." -ForegroundColor Magenta + Write-Host "==================================================" -ForegroundColor Magenta + } + + foreach ($failedRes in $failedToRetry) { + if (-not $agentMode) { Write-Host "⏳ Ripristino e compilazione sequenziale: $($failedRes.Name)..." -ForegroundColor Cyan } + + & $msbuildPath $failedRes.FullName /t:Restore /v:q /nologo > $null 2>&1 + & $msbuildPath $failedRes.FullName /t:Clean /v:q /p:Configuration=Release /nologo > $null 2>&1 + $retryLog = & $msbuildPath $failedRes.FullName /t:Build /p:Configuration=Release /v:m /nologo 2>&1 + + if ($LASTEXITCODE -eq 0) { + if (-not $agentMode) { Write-Host "✅ FALSO ALLARME: $($failedRes.Name) compilata correttamente in sequenziale!" -ForegroundColor Green } + $successSolutions += $failedRes.Name + } + else { + if (-not $agentMode) { Write-Host "❌ ERRORE REALE: $($failedRes.Name) è fallita anche in sequenziale." -ForegroundColor Red } + $failedRes.Log = $retryLog + } + } +} + +# Ferma il cronometro e calcola il tempo trascorso +$stopwatch.Stop() +$elapsedTime = "{0:mm\:ss}" -f $stopwatch.Elapsed + +# --- ELABORAZIONE DEI RISULTATI FINALI --- +$totalCount = $solutions.Count +$successCount = $successSolutions.Count +$failCount = $totalCount - $successCount +$failColor = if ($failCount -gt 0) { "Red" } else { "Gray" } + +# --- RIEPILOGO FINALE --- +if (-not $agentMode) { + Write-Host "`n==================================================" -ForegroundColor Magenta + Write-Host "🏁 Processo di verifica completato in $elapsedTime!" -ForegroundColor Magenta + Write-Host "==================================================" -ForegroundColor Magenta + Write-Host " Soluzioni Totali: $totalCount" -ForegroundColor White + Write-Host " Successi totali: $successCount" -ForegroundColor Green + Write-Host " Errori reali: $failCount" -ForegroundColor $failColor + Write-Host " Tempo impiegato: $elapsedTime" -ForegroundColor Cyan + + if ($failCount -gt 0) { + Write-Host "`n❌ Elenco delle soluzioni con ERRORI REALI:" -ForegroundColor Red + foreach ($res in $parallelResults) { + if ($successSolutions -notcontains $res.Name) { + Write-Host " - $($res.Name)" -ForegroundColor Red + Write-Host " 👉 Ultimi dettagli errore:" -ForegroundColor DarkRed + $res.Log | Where-Object { $_ -match "error" } | Select-Object -First 3 | Write-Host -ForegroundColor Gray + } + } + } + else { + Write-Host "`n🎉 Eccellente! Tutte le soluzioni compilano senza errori." -ForegroundColor Green + } + Write-Host "==================================================" -ForegroundColor Magenta +} + +# Exit code standard per ambienti automatizzati (0 = Successo, 1 = Fallimento) +if ($failCount -gt 0) { exit 1 } else { exit 0 } \ No newline at end of file diff --git a/build_one.ps1 b/build_one.ps1 new file mode 100644 index 00000000..7c2e2555 --- /dev/null +++ b/build_one.ps1 @@ -0,0 +1,56 @@ +# --- CONFIGURAZIONE DI TEST --- +# Inserisci qui il percorso esatto del file .sln che vuoi testare +$solutionPath = "IOB-WIN-NEXT.sln" +# $solutionPath = "IOB-WIN-MITSUBISHI.sln" + + +# --- TROVA MSBUILD (Versione Corretta per installazioni multiple) --- +$vsPaths = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -version "[17.0,18.0)" -products * -requires Microsoft.Component.MSBuild -property installationPath + +if (-not $vsPaths) { + Write-Host "❌ Impossibile trovare Visual Studio 2022!" -ForegroundColor Red + Exit +} + +# Prendiamo SOLO LA PRIMA installazione trovata per evitare stringhe doppie +$firstVsPath = $vsPaths[0] +$msbuildPath = Join-Path $firstVsPath "MSBuild\Current\Bin\MSBuild.exe" + +if (-not (Test-Path $solutionPath)) { + Write-Host "❌ Il file della soluzione specificato non esiste: $solutionPath" -ForegroundColor Red + Exit +} + +Write-Host "🎯 Soluzione sotto test: $solutionPath" -ForegroundColor Cyan +Write-Host "🎯 Usando MSBuild: $msbuildPath" -ForegroundColor Gray +Write-Host "--------------------------------------------------" -ForegroundColor Gray + +# 1. NuGet Restore +Write-Host "📦 [1/3] Ripristino pacchetti NuGet in corso..." -ForegroundColor Yellow +& $msbuildPath $solutionPath /t:Restore /v:m +if ($LASTEXITCODE -ne 0) { Write-Host "❌ Fallito il ripristino NuGet!" -ForegroundColor Red; Exit } + +# 2. Clean +Write-Host "🧹 [2/3] Pulizia soluzione (Clean)..." -ForegroundColor Yellow +& $msbuildPath $solutionPath /t:Clean /v:m /p:Configuration=Debug + +# 3. Build reale +Write-Host "🚀 [3/3] Compilazione (Build)..." -ForegroundColor Yellow +Write-Host "==================================================" -ForegroundColor DarkGray + +# Eseguiamo catturando l'output +& $msbuildPath $solutionPath /t:Build /p:Configuration=Debug /v:normal + +# Controllo finale REALE sul codice di uscita dell'ultimo comando eseguito +$finalResult = $LASTEXITCODE + +if ($finalResult -eq 0) { + Write-Host "`n==================================================" -ForegroundColor Green + Write-Host "✅ COMPILAZIONE AVVENUTA CON SUCCESSO!" -ForegroundColor Green + Write-Host "==================================================" -ForegroundColor Green +} +else { + Write-Host "`n==================================================" -ForegroundColor Red + Write-Host "❌ COMPILAZIONE FALLITA!" -ForegroundColor Red + Write-Host "==================================================" -ForegroundColor Red +} \ No newline at end of file diff --git a/refactor_log.md b/refactor_log.md new file mode 100644 index 00000000..77863c74 --- /dev/null +++ b/refactor_log.md @@ -0,0 +1,39 @@ +# Log Refactoring Phase 1 - Infrastructure Extraction + +## Status: IN_PROGRESS + +## Objective +Extract infrastructure and helper components from `Generic.cs` to improve modularity and reduce the monolithic footprint. + +## Tasks + +### 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 `HttpService.CallUrl` directly, eliminating the unnecessary indirection layer. + +### 2. Redis Service Extraction (COMPLETED) +- [x] Encapsulate all `redisMan` calls into a `RedisService`. +- [x] Define a clean interface for key/value and hash operations. +- [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 (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). +- [x] Remove pass-through methods for `utils` (Network, MAC, WebClients) to reduce "noise" in the base class. +- [x] Cleaned up commented-out code blocks (`#if false`) to improve readability. + +## Progress Log +- [x] Created WIP document. +- [x] Completed Redis Semantic Refactoring. +- [x] Completed BaseObj Cleanup. +- [x] Identified Data Serializer components for extraction. +- [ ] Started migration of Serializers to `IOB_UT_NEXT`. diff --git a/refactor_log.pdf b/refactor_log.pdf new file mode 100644 index 00000000..6c334dd8 Binary files /dev/null and b/refactor_log.pdf differ diff --git a/refactor_progress_tracker.md b/refactor_progress_tracker.md new file mode 100644 index 00000000..f1820d9c --- /dev/null +++ b/refactor_progress_tracker.md @@ -0,0 +1,83 @@ +# 🚀 Piano di Refactoring e Monitoraggio: Ottimizzazione Simula.cs + +Questo documento funge da **Master Tracker** per il processo di refactoring della classe `Simula.cs`. Serve a monitorare lo stato di avanzamento di ogni singolo intervento, garantendo che ogni modifica sia mappata e verificata. + +--- + +## 📊 Stato di Avanzamento Generale +**Progresso Totale:** `[░░░░░░░░░░░░░░░░░░░░] 0%` + +| Fase | Obiettivo | Stato | +| :--- | :--- | :---: | +| **Fase 1** | **Async Optimization** (Eliminazione Sync-over-Async) | ⚪ NOT STARTED | +| **Fase 2** | **Throttling I/O** (Dirty Check & Rate Limiting) | ⚪ NOT STARTED | +| **Fase 3** | **Jittering & Staggering** (Disallineamento istanze) | ⚪ NOT STARTED | +| **Fase 4** | **Verbosity Control** (Logging Optimization) | ⚪ NOT STARTED | +| **Fase 5** | **Verifica & Test** (Stress Test & Monitoraggio CPU) | ⚪ NOT STARTED | + +--- + +## 🛠️ Dettaglio Interventi + +### 1. ⚡ Fase 1: Async Optimization (Priorità Massima) +*Obiettivo: Eliminare il context switching e il Thread Pool Starvation.* + +- [ ] **[TASK-1.1] Refactoring `IobGetDataFromServerToFtp`** + - *Problema:* Uso di `.GetAwaiter().GetResult()` (Line 1670). + - *Azione:* Trasformare il metodo in `async Task` e usare `await` per le chiamate `HttpService`. +- [ ] **[TASK-1.2] Refactoring `IobGetSendDossierKepware`** + - *Problema:* Uso di `.GetAwaiter().GetResult()` (Line 1802). + - *Azione:* Trasformare in `async Task`. +- [ ] **[TASK-1.3] Audit `Task.Run` (Fire-and-Forget)** + - *Problema:* Potenziali fughe di thread o eccezioni silenziate (Line 158, 1003, 1597, 1748). + - *Azione:* Implementare un wrapper `SafeTaskRun` con gestione log errori centralizzata. + +### 2. 🛡️ Fase 2: Throttling I/O & Dirty Check +*Obiettivo: Ridurre il traffico verso Redis e i servizi esterni.* + +- [ ] **[TASK-2.1] Implementazione Dirty Check `upsertKey`** + - *Problema:* Invio continuo di dati anche se invariati (Line 232, 298, 327, 978). + - *Azione:* Creare un `Dictionary _lastSentValues` per validare i dati prima di `upsertKey`. +- [ ] **[TASK-2.2] Rate Limiting `decodeToBaseBitmap`** + - *Problema:* Operazione pesante invocata troppo frequentemente (Line 612). + - *Azione:* Implementare un controllo temporale (es. max 1 esecuzione ogni 500ms). +- [ ] **[TASK-2.3] Throttling `trySendPzCountBlock`** + - *Problema:* Possibile saturazione chiamate HTTP per i contapezzi (Line 1246). + - *Azione:* Limitare la frequenza di invio tramite timer o flag di stato. +- [ ] **[TASK-2.4] Ottimizzazione chiamate `HttpService`** + - *Problema:* Chiamate REST ripetitive e non ottimizzate. + - *Azione:* Implementare un meccanismo di caching temporaneo per i dati che non cambiano rapidamente. + +### 3. 🎲 Fase 3: Jittering & Disallineamento +*Obiettivo: Distribuire il carico computazionale nel tempo tra le diverse VM.* + +- [ ] **[TASK-3.1] Jitter di Inizializzazione** + - *Problema:* Ritardo fisso o troppo breve all'avvio (Line 70). + - *Azione:* Estendere il range del `Random startDelay` e assicurarsi che non blocchi il thread principale. +- [ ] **[TASK-3.2] Jittering dei Periodi di Polling** + - *Problema:* Sincronizzazione dei task tra istanze diverse. + - *Azione:* Applicare un rumore statistico (jitter) a ogni iterazione dei cicli di polling/timer. + +### 4. 📝 Fase 4: Verbosity Control +*Obiettivo: Ridurre l'overhead di I/O disco e CPU per il logging.* + +- [ ] **[TASK-4.1] Pulizia Log ad alta frequenza** + - *Problema:* Log massivi di stringhe e memoria nei cicli critici (Line 972-975). + - *Azione:* Spostare i log di debug/trace in modalità non invasiva o eliminarli se ridondanti. + +--- + +## 🧪 Fase 5: Verifica e Validazione + +| Test Case | Risultato Atteso | Stato | Note | +| :--- | :--- | :---: | :--- | +| **Stress Test CPU** | Riduzione % CPU rispetto al baseline | ⚪ | | +| **Monitoraggio Context Switch** | Riduzione numero switch/sec | ⚪ | | +| **Test Correttezza Dati** | I dati inviati a Redis/MES sono identici | ⚪ | | +| **Test Error Handling** | Le eccezioni nei Task asincroni vengono loggate | ⚪ | | + +--- + +## 📓 Note e Osservazioni +*Aggiungere qui osservazioni durante lo sviluppo.* +- diff --git a/refactor_progress_tracker.pdf b/refactor_progress_tracker.pdf new file mode 100644 index 00000000..9657994b Binary files /dev/null and b/refactor_progress_tracker.pdf differ diff --git a/refactoring_wip.md b/refactoring_wip.md index 8675acf4..5e09b4e1 100644 --- a/refactoring_wip.md +++ b/refactoring_wip.md @@ -1,39 +1,16 @@ -# WIP: Refactoring Phase 1 - Infrastructure Extraction +# Refactoring Progress: IOB-WIN-FORM (Generic.cs) -## Status: IN_PROGRESS +## Obiettivo +Riduzione Context Switching e CPU Load tramite eliminazione Sync-over-Async e ottimizzazione I/O. -## Objective -Extract infrastructure and helper components from `Generic.cs` to improve modularity and reduce the monolithic footprint. +## Stato Attuale +- [x] Analisi iniziale del codice `Generic.cs` +- [ ] Mappatura dipendenze (Analisi firme metodi per evitare breaking changes) +- [ ] Implementazione Fase A (Dirty Checks & Throttling) +- [ ] Implementazione Fase B (Internal Async Refactoring) +- [ ] Implementazione Fase C (Signature Migration) -## Tasks - -### 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 `HttpService.CallUrl` directly, eliminating the unnecessary indirection layer. - -### 2. Redis Service Extraction (COMPLETED) -- [x] Encapsulate all `redisMan` calls into a `RedisService`. -- [x] Define a clean interface for key/value and hash operations. -- [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 (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). -- [x] Remove pass-through methods for `utils` (Network, MAC, WebClients) to reduce "noise" in the base class. -- [x] Cleaned up commented-out code blocks (`#if false`) to improve readability. - -## Progress Log -- [x] Created WIP document. -- [x] Completed Redis Semantic Refactoring. -- [x] Completed BaseObj Cleanup. -- [x] Identified Data Serializer components for extraction. -- [ ] Started migration of Serializers to `IOB_UT_NEXT`. +## Log Modifiche e Test di Build +| Data | Metodo/Area | Tipo Modifica | Esito Build (`--agent`) | Note/Errori | +| :--- | :--- | :--- | :--- | :--- | +| 2026-05-23 | Inizio | Analisi | N/A | Identificati colli di bottiglia (Sync-over-Async, Log eccessivo, lack of Dirty Checks) |