diff --git a/CVCncLib/CVCncLib.dll b/CVCncLib/CVCncLib.dll index 7a3680a5..484da646 100644 Binary files a/CVCncLib/CVCncLib.dll and b/CVCncLib/CVCncLib.dll differ diff --git a/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.REQ b/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.REQ new file mode 100644 index 00000000..82c6c8ca --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.REQ @@ -0,0 +1 @@ +SESSS0000 CONNECT; \ No newline at end of file diff --git a/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.RSP.KO b/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.RSP.KO new file mode 100644 index 00000000..35cc29f6 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.RSP.KO @@ -0,0 +1 @@ +SESSS0000 ERROR 05 00000004 "Warning of first connection: all previous job are lost"; diff --git a/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.RSP.OK b/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.RSP.OK new file mode 100644 index 00000000..7d6d36d5 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_00_CONN/SESS0000.RSP.OK @@ -0,0 +1 @@ +SESSS0000 PROCESSED; \ No newline at end of file diff --git a/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.DAT b/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.DAT new file mode 100644 index 00000000..695f1c08 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.DAT @@ -0,0 +1,15 @@ +MachVendor, "Plastic Metal"; +MachNbr, "6037"; +MachDesc, ""; +ContrType, ""; +ContrVersion, ""; +Version, "1.05a July 2000"; +MaxJobs, 20; +MaxReports, ; +MaxArchives, ; +InjUnitNbr, 2; +MaterialNbr, ; +CharDef, "850"; +MaxSessions, 20; +ActiveJobs, "GETID" "SESS0001.JOB" "MPW280SP\SESS0001.DAT"; +ActiveJobs, "GETINFO" "SESS0002.JOB" "MPW280SP\SESS0002.DAT"; diff --git a/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.JOB b/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.JOB new file mode 100644 index 00000000..941c2c29 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.JOB @@ -0,0 +1,2 @@ +JOB GETID RESPONSE "SESS0001.LOG"; +GETID "SESS0001.DAT"; \ No newline at end of file diff --git a/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.REQ b/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.REQ new file mode 100644 index 00000000..72ce2e2b --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_01_ID/SESS0001.REQ @@ -0,0 +1 @@ +SESS0001 EXECUTE "SESS0001.JOB"; \ No newline at end of file diff --git a/Documentazione/Euromap63/DemoCom/Step_02_SETTIME/SESS0002.JOB b/Documentazione/Euromap63/DemoCom/Step_02_SETTIME/SESS0002.JOB new file mode 100644 index 00000000..ac48c1bf --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_02_SETTIME/SESS0002.JOB @@ -0,0 +1,2 @@ +JOB ImpostaOrario RESPONSE "SESS0002.LOG"; +SET SetTimMach {DTNow}; diff --git a/Documentazione/Euromap63/DemoCom/Step_02_SETTIME/SESS0002.REQ b/Documentazione/Euromap63/DemoCom/Step_02_SETTIME/SESS0002.REQ new file mode 100644 index 00000000..c647022a --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_02_SETTIME/SESS0002.REQ @@ -0,0 +1 @@ +SESS0002 EXECUTE "SESS0002.JOB"; diff --git a/Documentazione/Euromap63/DemoCom/Step_03_ABORTALL/SESS0003.JOB b/Documentazione/Euromap63/DemoCom/Step_03_ABORTALL/SESS0003.JOB new file mode 100644 index 00000000..881afaa9 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_03_ABORTALL/SESS0003.JOB @@ -0,0 +1,7 @@ +JOB Abort1 RESPONSE "SESS0003.LOG"; + +//ABORT EVENT Event1; +//ABORT ALL REPORTS; +//ABORT JOB Job1Name; +ABORT ALL JOBS; +//ABORT REPORT Report1Name; diff --git a/Documentazione/Euromap63/DemoCom/Step_03_ABORTALL/SESS0003.REQ b/Documentazione/Euromap63/DemoCom/Step_03_ABORTALL/SESS0003.REQ new file mode 100644 index 00000000..f14fbdf4 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_03_ABORTALL/SESS0003.REQ @@ -0,0 +1 @@ +SESS0003 EXECUTE "SESS0003.JOB"; diff --git a/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.DAT b/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.DAT new file mode 100644 index 00000000..2447e9a1 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.DAT @@ -0,0 +1,2 @@ +DATE, TIME, ActStsMach +20201007, 21:28:10, 0A000 diff --git a/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.JOB b/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.JOB new file mode 100644 index 00000000..ca69cf84 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.JOB @@ -0,0 +1,11 @@ +JOB machstat RESPONSE "SESS0004.LOG"; + +REPORT status REWRITE "SESS0004.DAT" +START IMMEDIATE +STOP NEVER +CYCLIC TIME 00:00:01 +SESSIONS 60 +PARAMETERS +DATE, TIME, ActStsMach; + + diff --git a/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.REQ b/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.REQ new file mode 100644 index 00000000..d29e9602 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_04_STATUS/SESS0004.REQ @@ -0,0 +1 @@ +SESS0004 EXECUTE "SESS0004.JOB"; diff --git a/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.DAT b/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.DAT new file mode 100644 index 00000000..7f1bedb2 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.DAT @@ -0,0 +1,2 @@ +DATE, TIME, ActCntCyc, ActTimCyc, ActTimFill, @OutXhour, SetDescJob +20201007, 21:29:52, 5302, 8.61, 0.50, 10058, Nr. 1000987654.01 diff --git a/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.JOB b/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.JOB new file mode 100644 index 00000000..f387774a --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.JOB @@ -0,0 +1,25 @@ +JOB machstat RESPONSE "SESS0005.LOG"; + +REPORT status REWRITE "SESS0005.DAT" +START IMMEDIATE +STOP NEVER +CYCLIC TIME 00:00:03 +SESSIONS 100 +//PARAMETERS +//DATE, TIME, ActCntCyc, ActTimCyc, ActTimFill, @OutXhour, SetDescJob; +PARAMETERS +DATE, TIME +, ActCntCyc, ActTimCyc, ActTimFill +, @OutXhour +//, SetTmpBrlZnStb[1] +//, SetTmpBrlZn[2], SetTmpBrlZnHdev[2], SetTmpBrlZnLdev[2] +//, ActTmpBrlZn[1], ActTmpBrlZn[2], ActTmpBrlZn[3] +//, SetTmpMldZn[50], SetTmpMldZnStb[50], SetTmpMldZnHdev[50], SetTmpMldZnLdev[50], ActTmpMldZn[50] +//, SetTmpMldZn[51], SetTmpMldZnStb[51], SetTmpMldZnHdev[51], SetTmpMldZnLdev[51], ActTmpMldZn[51] +//, ActTmpCab, ActTmpMlt +//, ActStrCsh, ActStrCsh +//, ActSpdPlstMax, ActSpdPlstAve +, SetDescJob +//, ActCntPrt +//, ActTmpOil +; \ No newline at end of file diff --git a/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.REQ b/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.REQ new file mode 100644 index 00000000..34cd11bc --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_05_PROD/SESS0005.REQ @@ -0,0 +1 @@ +SESS0005 EXECUTE "SESS0005.JOB"; diff --git a/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.DAT b/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.DAT new file mode 100644 index 00000000..b25a3449 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.DAT @@ -0,0 +1,15 @@ +MachVendor, "Plastic Metal"; +MachNbr, "6037"; +MachDesc, ""; +ContrType, ""; +ContrVersion, ""; +Version, "1.05a July 2000"; +MaxJobs, 20; +MaxReports, ; +MaxArchives, ; +InjUnitNbr, 2; +MaterialNbr, ; +CharDef, "850"; +MaxSessions, 20; +ActiveJobs, "GETID" "MPW280SP\SESS0001.JOB" "MPW280SP\SESS0001.DAT"; +ActiveJobs, "GETINFO" "MPW280SP\SESS0002.JOB" "MPW280SP\SESS0002.DAT"; diff --git a/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.JOB b/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.JOB new file mode 100644 index 00000000..3b3ac5a0 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.JOB @@ -0,0 +1,2 @@ +JOB GETINFO RESPONSE "SESS0002.LOG"; +GETINFO "SESS0002.DAT"; \ No newline at end of file diff --git a/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.REQ b/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.REQ new file mode 100644 index 00000000..cced09c3 --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_19_INFO/SESS0002.REQ @@ -0,0 +1 @@ +SESS0002 EXECUTE "SESS0002.JOB"; \ No newline at end of file diff --git a/Documentazione/Euromap63/DemoCom/Step_99_DESCR/SESS0005.JOB b/Documentazione/Euromap63/DemoCom/Step_99_DESCR/SESS0005.JOB new file mode 100644 index 00000000..bc3956cb --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_99_DESCR/SESS0005.JOB @@ -0,0 +1,19 @@ +JOB SetID RESPONSE "SESS0005.LOG"; +//SET SetDescJob " "; +//SET SetDescPrt " " +//SET SetDescMld " "; +//SET SetDescOp " "; + +SET SetDescJob {ODL}; +SET SetDescPrt {DescrArt}; +SET SetDescMld {CodArt}; +SET SetDescOp {CodOpr}; + +//SET SetDescJob "Nr. 1000987654.01"; +//SET SetDescPrt "STICK: 8 componenti SENZA assemblaggio"; +//SET SetDescMld "Stampo componenti a 8 impronte"; +//SET SetDescOp "Operatore 01"; + +//SET SetCntMld 2; +//SET SetCntPrt 10000; +//SET SetCntPrtBox 20; diff --git a/Documentazione/Euromap63/DemoCom/Step_99_DESCR/SESS0005.REQ b/Documentazione/Euromap63/DemoCom/Step_99_DESCR/SESS0005.REQ new file mode 100644 index 00000000..34cd11bc --- /dev/null +++ b/Documentazione/Euromap63/DemoCom/Step_99_DESCR/SESS0005.REQ @@ -0,0 +1 @@ +SESS0005 EXECUTE "SESS0005.JOB"; diff --git a/Documentazione/Euromap63/eu63.pdf b/Documentazione/Euromap63/eu63.pdf new file mode 100644 index 00000000..aba321d2 Binary files /dev/null and b/Documentazione/Euromap63/eu63.pdf differ diff --git a/Documentazione/Siemens Punzonatrice FAPE/TM150701_ IO.pdf b/Documentazione/Siemens/Siemens Punzonatrice FAPE/TM150701_ IO.pdf similarity index 100% rename from Documentazione/Siemens Punzonatrice FAPE/TM150701_ IO.pdf rename to Documentazione/Siemens/Siemens Punzonatrice FAPE/TM150701_ IO.pdf diff --git a/Documentazione/Sinumerik_Integrated_OPC_UA_2014_uk.pdf b/Documentazione/Siemens/Sinumerik_Integrated_OPC_UA_2014_uk.pdf similarity index 100% rename from Documentazione/Sinumerik_Integrated_OPC_UA_2014_uk.pdf rename to Documentazione/Siemens/Sinumerik_Integrated_OPC_UA_2014_uk.pdf diff --git a/IOB-UT/Enums.cs b/IOB-UT/Enums.cs index 311e41b2..f72a39c1 100644 --- a/IOB-UT/Enums.cs +++ b/IOB-UT/Enums.cs @@ -5,6 +5,108 @@ using System.Text; namespace IOB_UT { + /// + /// Elenco MODI CNC + /// + public enum CNC_MODE + { + /// + /// Non definito + /// + ND = 0, + + /// + /// AUTOMATICO + /// + AUTO, + + /// + /// EDIT (MEMORY EDIT) + /// + EDIT, + + /// + /// MEN (MEMORY OPERATION) + /// + MEN, + + /// + /// MDI (MANUAL DATA INPUT) + /// + MDI, + + /// + /// HANDLE/INC (MANUAL HANDLE / INCREMENTAL FEED) + /// + HANDLE_INC, + + /// + /// HOME + /// + HOME, + + /// + /// JOG (MANUAL CONTINUOUS FEED) + /// + JOG, + + /// + /// JOG MAN + /// + JOG_MAN, + + /// + /// JOG_INC + /// + JOG_INC, + + /// + /// PROFILE + /// + PROFILE, + + /// + /// SEMI + /// + SEMI, + + /// + /// THND (TEACH IN HANDLE) + /// + THND, + + /// + /// TJOG (TEACH IN JOG) + /// + TJOG, + + /// + /// RMT (DNC OPERATION) + /// + RMT, + + /// + /// REF (MANUAL REFERENCE POSITION RETURN) + /// + REF + } + + /// + /// Elenco STATI CNC OSAI + /// + public enum CNC_STATUS_OSAI + { + IDLE = 1, + CYCLE, + HODA, + RUNH, + HRUN, + ERRO, + WAIT, + RESET, + EMERG, + INPUT + } /// /// Tipologie di DUMP memoria @@ -15,101 +117,13 @@ namespace IOB_UT /// Salvataggio all'avvio aree memoria (con sovrascrittura) /// STARTUP, + /// /// Campionamento periodico /// SAMPLE } - /// - /// Tipologia di adapters ammessi - /// - public enum tipoAdapter - { - /// - /// Adapter SIMULAZIONE - /// - SIMULA, - /// - /// adapter FANUC - /// - FANUC, - /// - /// adapter KAWASAKI e-controller - /// - KAWASAKI, - /// - /// Adapter non specificato - /// - ND, - /// - /// Adapter MTConnect - /// - MTConnect, - /// - /// Adapter OMRON - /// - OMRON, - /// - /// Adapter OSAI CNDEX (Cndex) - /// - OSAI_CNDEX, - /// - /// Adapter OSAI OPEN (ws) - /// - OSAI_OPEN, - /// - /// Adapter OSAI VB6 - /// - OSAI_VB6, - /// - /// Adapter SIEMENS - /// - SIEMENS, - /// - /// Adapter SIEMENS, interfaccia versione APROCHIM (filtro liquidi rettifiche) - /// - SIEMENS_APROCHIM, - /// - /// Adapter SIEMENS, interfaccia versione VIPA @2001 - /// - SIEMENS_AT2001, - /// - /// Adapter SIEMENS, interfaccia versione FAPE (punzonatrici) - /// - SIEMENS_FAPE, - /// - /// Adapter SIEMENS, interfaccia versione COMUR (dentatrice) - /// - SIEMENS_COMUR, - /// - /// Adapter SIEMENS, interfaccia versione INGENIA (Valvital, Automazione) - /// - SIEMENS_INGENIA, - /// - /// Adapter SIEMENS, interfaccia versione LASCO (Valvital, Pressa Bilancere) - /// - SIEMENS_LASCO, - /// - /// Adapter SIEMENS, interfaccia versione PRESSOIL + CEI (Valvital, Pressa Idraulica) - /// - SIEMENS_PRESSOIL_CEI, - /// - /// Adapter SIEMENS, interfaccia versione SAET (Valvital, forni / tempra) - /// - SIEMENS_SAET, - /// - /// Adapter SIEMENS, interfaccia versione SIMEC (Valvital, taglio) - /// - SIEMENS_SIMEC, - /// - /// Adapter SIEMENS, interfaccia versione Torri - /// - SIEMENS_TORRI, - /// - /// Metodi di WPS WebPageScraping (es x compressori Atlas Copco) - /// - WPS - } + /// /// Tipo di ciclo da processare /// @@ -119,40 +133,28 @@ namespace IOB_UT /// Very High Frequency (solo x invii...) /// VHF, + /// /// lettura dati ad alta frequenza /// HF, + /// /// lettura dati standard /// MF, + /// /// lettura dati bassa freq /// LF, + /// /// lettura dati bassissima priorità (re-sync stato allarmi) /// VLF } - /// - /// StFlag8: set di 8 bit (1 word) contente semaforo di variabili - /// - [Flags] - public enum StFlag8 : int - { - NONE = 0, - B0 = 1 << 0, - B1 = 1 << 1, - B2 = 1 << 2, - B3 = 1 << 3, - B4 = 1 << 4, - B5 = 1 << 5, - B6 = 1 << 6, - B7 = 1 << 7 - } /// /// StFlag32: set di 32 bit (4 word) contente semaforo di variabili /// @@ -193,6 +195,150 @@ namespace IOB_UT B30 = 1 << 30, B31 = 1 << 31 } + + /// + /// StFlag8: set di 8 bit (1 word) contente semaforo di variabili + /// + [Flags] + public enum StFlag8 : int + { + NONE = 0, + B0 = 1 << 0, + B1 = 1 << 1, + B2 = 1 << 2, + B3 = 1 << 3, + B4 = 1 << 4, + B5 = 1 << 5, + B6 = 1 << 6, + B7 = 1 << 7 + } + + /// + /// Tipologia di adapters ammessi + /// + public enum tipoAdapter + { + /// + /// Adapter SIMULAZIONE + /// + SIMULA, + + /// + /// adapter FANUC + /// + FANUC, + + /// + /// File Based exchange generic adapter + /// + FILE_GEN, + + /// + /// File Based exchange Euromap63 + /// + FILE_EUROM63, + + ///// + ///// File Based exchange SCM Xylog + ///// + //FILE_XYLOG, + + /// + /// adapter KAWASAKI e-controller + /// + KAWASAKI, + + /// + /// Adapter non specificato + /// + ND, + + /// + /// Adapter MTConnect + /// + MTConnect, + + /// + /// Adapter OMRON + /// + OMRON, + + /// + /// Adapter OSAI CNDEX (Cndex) + /// + OSAI_CNDEX, + + /// + /// Adapter OSAI OPEN (ws) + /// + OSAI_OPEN, + + /// + /// Adapter OSAI VB6 + /// + OSAI_VB6, + + /// + /// Adapter SIEMENS + /// + SIEMENS, + + /// + /// Adapter SIEMENS, interfaccia versione APROCHIM (filtro liquidi rettifiche) + /// + SIEMENS_APROCHIM, + + /// + /// Adapter SIEMENS, interfaccia versione VIPA @2001 + /// + SIEMENS_AT2001, + + /// + /// Adapter SIEMENS, interfaccia versione FAPE (punzonatrici) + /// + SIEMENS_FAPE, + + /// + /// Adapter SIEMENS, interfaccia versione COMUR (dentatrice) + /// + SIEMENS_COMUR, + + /// + /// Adapter SIEMENS, interfaccia versione INGENIA (Valvital, Automazione) + /// + SIEMENS_INGENIA, + + /// + /// Adapter SIEMENS, interfaccia versione LASCO (Valvital, Pressa Bilancere) + /// + SIEMENS_LASCO, + + /// + /// Adapter SIEMENS, interfaccia versione PRESSOIL + CEI (Valvital, Pressa Idraulica) + /// + SIEMENS_PRESSOIL_CEI, + + /// + /// Adapter SIEMENS, interfaccia versione SAET (Valvital, forni / tempra) + /// + SIEMENS_SAET, + + /// + /// Adapter SIEMENS, interfaccia versione SIMEC (Valvital, taglio) + /// + SIEMENS_SIMEC, + + /// + /// Adapter SIEMENS, interfaccia versione Torri + /// + SIEMENS_TORRI, + + /// + /// Metodi di WPS WebPageScraping (es x compressori Atlas Copco) + /// + WPS + } + #if false /// /// Enumerazione tipi di semaforo @@ -219,8 +365,9 @@ namespace IOB_UT /// Grigio/Spento /// SS - } + } #endif + /// /// Enumerazione tipi di tipi di URL x invio /// @@ -230,96 +377,10 @@ namespace IOB_UT /// Salvataggio FluxLog (valori estesi che non provocano calcoli di macchine a stati, eventi...) /// FLog, + /// /// INPUT segnali in ingresso (standard base MAPO) /// SignIN } - - /// - /// Elenco STATI CNC OSAI - /// - public enum CNC_STATUS_OSAI - { - IDLE = 1, - CYCLE, - HODA, - RUNH, - HRUN, - ERRO, - WAIT, - RESET, - EMERG, - INPUT - } - /// - /// Elenco MODI CNC - /// - public enum CNC_MODE - { - /// - /// Non definito - /// - ND = 0, - /// - /// AUTOMATICO - /// - AUTO, - /// - /// EDIT (MEMORY EDIT) - /// - EDIT, - /// - /// MEN (MEMORY OPERATION) - /// - MEN, - /// - /// MDI (MANUAL DATA INPUT) - /// - MDI, - /// - /// HANDLE/INC (MANUAL HANDLE / INCREMENTAL FEED) - /// - HANDLE_INC, - /// - /// HOME - /// - HOME, - /// - /// JOG (MANUAL CONTINUOUS FEED) - /// - JOG, - /// - /// JOG MAN - /// - JOG_MAN, - /// - /// JOG_INC - /// - JOG_INC, - /// - /// PROFILE - /// - PROFILE, - /// - /// SEMI - /// - SEMI, - /// - /// THND (TEACH IN HANDLE) - /// - THND, - /// - /// TJOG (TEACH IN JOG) - /// - TJOG, - /// - /// RMT (DNC OPERATION) - /// - RMT, - /// - /// REF (MANUAL REFERENCE POSITION RETURN) - /// - REF - } -} +} \ No newline at end of file diff --git a/IOB-UT/Eurom63.cs b/IOB-UT/Eurom63.cs new file mode 100644 index 00000000..8b7bf53c --- /dev/null +++ b/IOB-UT/Eurom63.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace IOB_UT +{ + /// + /// Classe di helper per metodi Euromap63 tramite File Exchange + /// + public class Eurom63 + { + #region Public Enums + + /// + /// Elenco dei livelli di comunicazione attivi + /// + public enum ComLevel + { + /// + /// Comunicazione NON attiva + /// + None = 0, + + /// + /// COntrollo comunicazione col PLC + /// + IsConnected, + + /// + /// Ricezione info preliminari macchina + /// + HasInfo, + + /// + /// Impostato data-ora correnti + /// + TimeSet, + + /// + /// Verificato il canale di comunicazione è OK, fatta pulizia con AbortAll, NON ci sono report attivi + /// + ChannelOk, + + /// + /// Status data richiesti + /// + StatusRequested, + + /// + /// Prod data richiesti + /// + ProdRequested + } + + public enum FileOpr + { + Copy = 0, + ReplaceAndCopy + } + + public enum FileType + { + NA = 0, + Dat, + Job, + Log, + Req, + Rsp + } + + public enum JobType + { + NA = 0, + AbortAll, + GetId, + GetInfo, + GetParams, + GetStatus, + GetProduction, + IsConnected, + SetDateTime, + SetParamOdl + } + + #endregion Public Enums + + #region Public Classes + + /// + /// Struttura per un file da processare + /// + public class FileTask + { + #region Public Properties + + public FileOpr OprReq { get; set; } = FileOpr.Copy; + public string Path { get; set; } = @"EUR63_JOB\SESS9999.FILE"; + + #endregion Public Properties + } + + public class ProtoConf + { + #region Public Fields + + public Dictionary ActiveSessions = new Dictionary(); + + #endregion Public Fields + + #region Public Properties + + public string BaseDir { get; set; } = @"C:\EUROMAP63\"; + public List cleanupExt { get; set; } = new List(); + public List DynData { get; set; } = new List(); + + #endregion Public Properties + } + + /// + /// Generic communication session + /// + public class Session + { + #region Public Properties + + /// + /// Session currently active + /// + public bool Active { get; set; } = false; + + /// + /// Indicates that must be repeated/restarted when not active + /// + public bool Cycle { get; set; } = false; + + /// + /// Session Description + /// + public string Description { get; set; } = ""; + + /// + /// Elenco dei file da processare + /// + public List FileList { get; set; } = new List(); + + /// + /// Numero MAX di esecuzioni da mantenere in HIST prima di eliminare i + vecchi (fare folder HIST\SESSnnnn) + /// + public int Max2Keep { get; set; } = 50; + + /// + /// Session check passed (= not to repeat) + /// + public bool Passed { get; set; } = false; + + /// + /// TAG per risposta con errori + /// + public string RespKo { get; set; } = "ERROR"; + + /// + /// Tag per risposta positiva + /// + public string RespOk { get; set; } = "PROCESSED"; + + /// + /// Seconds before do a new retry (default = 0 --> no veto) + /// + public double RetrySec { get; set; } = 0; + + /// + /// Veto for retry operation + /// + public DateTime RetryVeto { get; set; } = DateTime.Now; + + /// + /// Session Name + /// + public string SessionName { get; set; } = "SESS0000"; + + /// + /// Start of communication + /// + public DateTime SessionStarted { get; set; } = DateTime.Now.AddMinutes(-5); + + /// + /// Session type + /// + public JobType SessionType { get; set; } = JobType.NA; + + /// + /// Estimated Validity limit + /// + public DateTime SessionValidUntil { get; set; } = DateTime.Now.AddMinutes(-1); + + /// + /// Set Step Order (=execution priority, 1...n) + /// + public int StepOrder { get; set; } = 999; + + /// + /// Standard session validity time + /// + public double ValidityMinutes { get; set; } = 1; + + #endregion Public Properties + } + + #endregion Public Classes + } +} \ No newline at end of file diff --git a/IOB-UT/IOB-UT.csproj b/IOB-UT/IOB-UT.csproj index 54c5d7aa..faaeef15 100644 --- a/IOB-UT/IOB-UT.csproj +++ b/IOB-UT/IOB-UT.csproj @@ -99,6 +99,7 @@ + diff --git a/IOB-WIN/AdapterForm.cs b/IOB-WIN/AdapterForm.cs index ffea06b6..08bbbb31 100644 --- a/IOB-WIN/AdapterForm.cs +++ b/IOB-WIN/AdapterForm.cs @@ -13,1280 +13,1375 @@ using System.Windows.Forms; namespace IOB_WIN { - public partial class AdapterForm : Form - { - #region inizializzazione contatori - - /// - /// contatore veloce - /// - protected int fastCount; - - /// - /// Data-Ora prima apertura FORM... - /// - protected DateTime firstStart; - - /// - /// ultimo tentativo riavvio... - /// - protected DateTime lastStartTry; - - /// - /// contatore normale - /// - protected int normCount; - - /// - /// Contatore campionamento memoria - /// - protected int sampleMemCount; - - /// - /// contatore lento - /// - protected int slowCount; - - /// - /// contatore sync allarmi - /// - protected int verySlowCount; - - #endregion inizializzazione contatori - - #region inizializzazione oggetti base - - /// - /// Oggetto ultimo inviato stato IOB x REDIS - /// - protected IobWinStatus lastIobStatus = new IobWinStatus(); - - /// - /// Oggetto ultimo inviato stato MP-IO x REDIS - /// - protected ServerMpStatus lastSrvStatus = new ServerMpStatus(); - - /// - /// Temnpo attesa std in MS - /// - protected int waitRecMSec = 30000; - - /// - /// oggetto logging - /// - public static Logger lg; - - /// - /// Modello macchina - /// - public string curModel = ""; - - /// - /// Vendor macchina - /// - public string curVendor = ""; - - /// - /// configurazione caricata - /// - public IobConfiguration IOBConf; - - /// - /// Oggetto x gestione dell'adapter GENERICO (x poter usare metodi di ognuno...) - /// - public IobGeneric iobObj; - - /// - /// tipo di adapter prescelto... - /// - public tipoAdapter tipoScelto = tipoAdapter.SIMULA; - - /// - /// Codice IOB della macchina cui connettersi (x scegliere corretto file di conf...) - /// - protected string CurrIOB { get; set; } - - #endregion inizializzazione oggetti base - - #region utils ed helpers - - protected int delayShowLogMs { get; set; } = utils.CRI("delayShowLogMs"); - - /// - /// Stringa corrente di log... - /// - protected string logWatchString { get; set; } = ""; - - /// - /// Veto a NUOVE scritture in logWatch... - /// - protected DateTime logWatchWriteVeto { get; set; } = DateTime.Now; - - /// - /// Log verboso da configurazione (SOLO CHAIVE "verbose"... - /// - public bool isVerboseLog { get; set; } = utils.CRB("verbose"); - - /// - /// Logwatcher (in modalità "accodamento in testa" ultimi messaggi...) - /// - public string logWatcher + public partial class AdapterForm : Form { - get - { - return lblLogfile.Text; - } - set - { - try + #region inizializzazione contatori + + /// + /// contatore veloce + /// + protected int fastCount; + + /// + /// Data-Ora prima apertura FORM... + /// + protected DateTime firstStart; + + /// + /// ultimo tentativo riavvio... + /// + protected DateTime lastStartTry; + + /// + /// contatore normale + /// + protected int normCount; + + /// + /// Contatore campionamento memoria + /// + protected int sampleMemCount; + + /// + /// contatore lento + /// + protected int slowCount; + + /// + /// contatore sync allarmi + /// + protected int verySlowCount; + + #endregion inizializzazione contatori + + #region inizializzazione oggetti base + + /// + /// oggetto logging + /// + public static Logger lg; + + /// + /// Modello macchina + /// + public string curModel = ""; + + /// + /// Vendor macchina + /// + public string curVendor = ""; + + /// + /// configurazione caricata + /// + public IobConfiguration IOBConf; + + /// + /// Oggetto x gestione dell'adapter GENERICO (x poter usare metodi di ognuno...) + /// + public IobGeneric iobObj; + + /// + /// tipo di adapter prescelto... + /// + public tipoAdapter tipoScelto = tipoAdapter.SIMULA; + + /// + /// Oggetto ultimo inviato stato IOB x REDIS + /// + protected IobWinStatus lastIobStatus = new IobWinStatus(); + + /// + /// Oggetto ultimo inviato stato MP-IO x REDIS + /// + protected ServerMpStatus lastSrvStatus = new ServerMpStatus(); + + /// + /// Temnpo attesa std in MS + /// + protected int waitRecMSec = 30000; + + /// + /// Codice IOB della macchina cui connettersi (x scegliere corretto file di conf...) + /// + protected string CurrIOB { get; set; } + + #endregion inizializzazione oggetti base + + #region utils ed helpers + + /// + /// Log verboso da configurazione (SOLO CHAIVE "verbose"... + /// + public bool isVerboseLog { get; set; } = utils.CRB("verbose"); + + /// + /// Logwatcher (in modalità "accodamento in testa" ultimi messaggi...) + /// + public string logWatcher { - logWatchString = limitLine2show($"{value}{Environment.NewLine}{logWatchString}"); - DateTime adesso = DateTime.Now; - if (logWatchWriteVeto < adesso) - { - lblLogfile.Text = logWatchString; - lblLogfile.Refresh(); - logWatchWriteVeto = adesso.AddMilliseconds(delayShowLogMs); - } + get + { + return lblLogfile.Text; + } + set + { + try + { + logWatchString = limitLine2show($"{value}{Environment.NewLine}{logWatchString}"); + DateTime adesso = DateTime.Now; + if (logWatchWriteVeto < adesso) + { + lblLogfile.Text = logWatchString; + lblLogfile.Refresh(); + logWatchWriteVeto = adesso.AddMilliseconds(delayShowLogMs); + } + } + catch (Exception exc) + { + lgError($"Errore in esecuzione logWatcher{Environment.NewLine}--> {value}"); + if (isVerboseLog) + { + lgError($"{exc}"); + } + } + } } - catch (Exception exc) + + /// + /// Task watcher (in modalità "accodamento in testa" ultimi messaggi...) + /// + public string taskWatcher { - lgError($"Errore in esecuzione logWatcher{Environment.NewLine}--> {value}"); - if (isVerboseLog) - { - lgError($"{exc}"); - } + get + { + return lblTaskLog.Text; + } + set + { + try + { + lblTaskLog.Text = limitLine2show($"{value}{Environment.NewLine}{lblTaskLog.Text}"); + lblTaskLog.Refresh(); + } + catch (Exception exc) + { + lgError($"Errore in esecuzione taskWatcher{Environment.NewLine}--> {value}"); + if (isVerboseLog) + { + lgError($"{exc}"); + } + } + } } - } - } - /// - /// Task watcher (in modalità "accodamento in testa" ultimi messaggi...) - /// - public string taskWatcher - { - get - { - return lblTaskLog.Text; - } - set - { - try + protected int delayShowLogMs { get; set; } = utils.CRI("delayShowLogMs"); + + /// + /// Stringa corrente di log... + /// + protected string logWatchString { get; set; } = ""; + + /// + /// Veto a NUOVE scritture in logWatch... + /// + protected DateTime logWatchWriteVeto { get; set; } = DateTime.Now; + + /// + /// mostra un testo sulla status bar + LOG + /// + /// + public void displayTaskAndLog(string txt2show) { - lblTaskLog.Text = limitLine2show($"{value}{Environment.NewLine}{lblTaskLog.Text}"); - lblTaskLog.Refresh(); + lblStatus.Text = txt2show; + lblStatus.Invalidate(); + lgInfo(txt2show); } - catch (Exception exc) + + /// + /// Effettua un trim della stringa al numero max di linee da mostrare a video + /// + /// + /// + public string limitLine2show(string newString) { - lgError($"Errore in esecuzione taskWatcher{Environment.NewLine}--> {value}"); - if (isVerboseLog) - { - lgError($"{exc}"); - } + if (!string.IsNullOrEmpty(newString)) + { + // se num righe superiore a limite trimmo... + if (newString.Split('\n').Length > nLine2show) + { + //int idx = newString.LastIndexOf('\r'); + int idx = newString.LastIndexOf(Environment.NewLine); + newString = newString.Substring(0, idx); + } + } + return newString; } - } - } - /// - /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - protected void lgError(string txt2log) - { - if (!string.IsNullOrEmpty(txt2log)) - { - lg.Factory.Configuration.Variables["codIOB"] = this.CurrIOB; - lg.Error(txt2log); - // salvo anche in logwatcher... SE non si dimostra ricorsivo... - if (!txt2log.Contains("logWatcher")) + /// + /// Mostra update delle statistiche di comunicazione (numero chiamate, tempo medio...) + /// + /// + public void updateComStats(string txt2show) { - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | ERROR | {txt2log}"; - updateFormDisplay(currDispData); + lblComStats.Text = string.Format("{0} | ", txt2show); } - } - } - /// - /// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - protected void lgInfo(string txt2log) - { - lg.Factory.Configuration.Variables["codIOB"] = this.CurrIOB; - lg.Info(txt2log); - // salvo anche in logwatcher... - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | INFO | {txt2log}"; - updateFormDisplay(currDispData); - } - - /// - /// mostra un testo sulla status bar + LOG - /// - /// - public void displayTaskAndLog(string txt2show) - { - lblStatus.Text = txt2show; - lblStatus.Invalidate(); - lgInfo(txt2show); - } - - /// - /// Effettua un trim della stringa al numero max di linee da mostrare a video - /// - /// - /// - public string limitLine2show(string newString) - { - if (!string.IsNullOrEmpty(newString)) - { - // se num righe superiore a limite trimmo... - if (newString.Split('\n').Length > nLine2show) + /// + /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... + /// + /// + protected void lgError(string txt2log) { - //int idx = newString.LastIndexOf('\r'); - int idx = newString.LastIndexOf(Environment.NewLine); - newString = newString.Substring(0, idx); + if (!string.IsNullOrEmpty(txt2log)) + { + lg.Factory.Configuration.Variables["codIOB"] = this.CurrIOB; + lg.Error(txt2log); + // salvo anche in logwatcher... SE non si dimostra ricorsivo... + if (!txt2log.Contains("logWatcher")) + { + newDisplayData currDispData = new newDisplayData(); + currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | ERROR | {txt2log}"; + updateFormDisplay(currDispData); + } + } } - } - return newString; - } - /// - /// Mostra update delle statistiche di comunicazione (numero chiamate, tempo medio...) - /// - /// - public void updateComStats(string txt2show) - { - lblComStats.Text = string.Format("{0} | ", txt2show); - } + /// + /// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere... + /// + /// + protected void lgInfo(string txt2log) + { + lg.Factory.Configuration.Variables["codIOB"] = this.CurrIOB; + lg.Info(txt2log); + // salvo anche in logwatcher... + newDisplayData currDispData = new newDisplayData(); + currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | INFO | {txt2log}"; + updateFormDisplay(currDispData); + } - #endregion utils ed helpers + #endregion utils ed helpers - #region gestione form e visibilità + #region gestione form e visibilità - /// - /// Avvio MainForm - /// - /// - public AdapterForm(string codIOB) - { - CurrIOB = codIOB; - // continuo avvio... - InitializeComponent(); - myGraphInitForm(); + /// + /// Avvio MainForm + /// + /// + public AdapterForm(string codIOB) + { + CurrIOB = codIOB; + // continuo avvio... + InitializeComponent(); + myGraphInitForm(); - checkEditMes2Plc(); + checkEditMes2Plc(); - // inizializzo orologi - firstStart = DateTime.Now; - lastStartTry = DateTime.Now; + // inizializzo orologi + firstStart = DateTime.Now; + lastStartTry = DateTime.Now; - waitRecMSec = utils.CRI("waitRecMSec"); + waitRecMSec = utils.CRI("waitRecMSec"); #if DEBUG - // Setup the logging view for Sentinel - http://sentinel.codeplex.com - var sentinelTarget = new NLogViewerTarget() - { - Name = "sentinel", - Address = "udp://127.0.0.1:9999", - IncludeNLogData = false - }; - var sentinelRule = new LoggingRule("*", LogLevel.Trace, sentinelTarget); - LogManager.Configuration.AddTarget("sentinel", sentinelTarget); - LogManager.Configuration.LoggingRules.Add(sentinelRule); + // Setup the logging view for Sentinel - http://sentinel.codeplex.com + var sentinelTarget = new NLogViewerTarget() + { + Name = "sentinel", + Address = "udp://127.0.0.1:9999", + IncludeNLogData = false + }; + var sentinelRule = new LoggingRule("*", LogLevel.Trace, sentinelTarget); + LogManager.Configuration.AddTarget("sentinel", sentinelTarget); + LogManager.Configuration.LoggingRules.Add(sentinelRule); #endif - LogManager.ReconfigExistingLoggers(); + LogManager.ReconfigExistingLoggers(); - lg = LogManager.GetCurrentClassLogger(); - displayTaskAndLog("MainForm Starting"); + lg = LogManager.GetCurrentClassLogger(); + displayTaskAndLog("MainForm Starting"); - // se abilitato autoload conf leggo file corretto... - if (utils.CRB("autoLoadConf")) - { - try - { - loadIniFile(defConfFilePath); - lgInfo("INI LOADED"); - } - catch (Exception exc) - { - displayTaskAndLog(string.Format("Eccezione in autoLoadConf: {0}", exc)); - } - } - else - { - // definisco e avvio tipo adapter generico - tipoScelto = tipoAdapter.ND; - curVendor = "ACME"; - curModel = "NONE"; - IOBConf = new IobConfiguration(); - loadIobType(); - displayTaskAndLog("Waiting for config file selection"); - } - - // cerco tra i parametri opzionali se ho il parametro di - int timerIntMs = utils.CRI("timerIntMs"); - if (IOBConf.optPar.ContainsKey("timerIntMs")) - { - // recupero - string rawVal = IOBConf.optPar["timerIntMs"]; - if (!string.IsNullOrEmpty(rawVal)) - { - int.TryParse(rawVal, out timerIntMs); - lgInfo($"Impostato timerIntMs da IOB.ini: {timerIntMs}"); - } - } - // Start timer periodico comunicazione - gather.Interval = timerIntMs; - gather.Enabled = true; - displayTaskAndLog(string.Format("Main timer set: {0}ms", gather.Interval)); - - // Start timer periodico interfaccia - displTimer.Interval = utils.CRI("timerIntMs"); - displTimer.Enabled = true; - - displayTaskAndLog("Program Running"); - - try - { - // verifico server online... - if (iobObj.checkServerAlive) - { - // segnalo reboot (programma)... - IobGeneric.callUrl(iobObj.urlReboot, true); - } - else - { - displayTaskAndLog("AdapterForm: Server OFFLINE"); - } - } - catch (Exception exc) - { - lgError(string.Format("AdapterForm: EXCEPTION in fase di chiamata URL di reboot:{0}{1}{2}", iobObj.urlReboot, Environment.NewLine, exc)); - } - displayTaskAndLog("Main Form OK"); - } - - /// - /// File configurazione default - /// - public string defConfFilePath - { - get - { - return string.Format(@"{0}\{1}.ini", utils.confDir, CurrIOB); - } - } - - /// - /// Fase chiusura Form - /// - /// - /// - private void MainForm_FormClosing(object sender, FormClosingEventArgs e) - { - closeAdapter(); - } - - /// - /// Completato resize form - /// - /// - /// - private void MainForm_Resize(object sender, EventArgs e) - { - } - - /// - /// Mostrata form - /// - /// - /// - private void MainForm_Shown(object sender, EventArgs e) - { - displayTaskAndLog("Main Form SHOWN"); - } - - /// - /// Init form (grafica) con helper x testi e varie - /// - protected void myGraphInitForm() - { - lblStatus.Text = "Loading"; - - // aggiunta tooltip x send forzato - ToolTip ttForceSend = new ToolTip(); - - // imposto delay. - ttForceSend.AutoPopDelay = 3000; - ttForceSend.InitialDelay = 500; - ttForceSend.ReshowDelay = 500; - // sempre visibile (che sia o meno attiva la form). - ttForceSend.ShowAlways = true; - - // imposto tooltip - ttForceSend.SetToolTip(this.chkForceDequeue, "Forza invio eventi allo stop"); - } - - #endregion gestione form e visibilità - - #region gestione metodi specifici FORM - - private void checkFastTask() - { - // decremento... - fastCount--; - // se il counter è a zero eseguo... - if (fastCount <= 0) - { - fastCount = utils.CRI("fastCount"); - - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.HF); - } - } - - private void checkNormTask() - { - // decremento... - normCount--; - // se il counter è a zero eseguo... - if (normCount <= 0) - { - normCount = utils.CRI("normCount"); - - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.MF); - } - } - - private void checkSampleMem() - { - // decremento contatore... - sampleMemCount--; - if (sampleMemCount <= 0) - { - sampleMemCount = utils.CRI("sampleMemCount"); - // avvio fase raccolta dati e invio con adapter - iobObj.saveMemDump(dumpType.SAMPLE); - } - } - - private void checkSendTask() - { - // avvio fase invio con adapter (code MST) - iobObj.getAndSend(gatherCycle.VHF); - } - - private void checkSlowTask() - { - slowCount--; - if (slowCount <= 0) - { - slowCount = utils.CRI("slowCount"); - - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.LF); - } - } - - private void checkVerySlowData() - { - verySlowCount--; - if (verySlowCount <= 0) - { - verySlowCount = utils.CRI("verySlowCount"); - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.VLF); - } - } - - /// - /// Chiusura adapter - /// - private void closeAdapter() - { - fermaTutto(true, false, true, false); - } - - /// - /// Ferma tutti i componenti adapter + update buttons - /// - /// indica se fermare il timer (gather) principale (solo se non si chiude) - /// indica se tentare di riconnettersi - /// indica se sia richeisto di SVUOTARE le code delel info - /// indica se si debba aggiornare la form (no se si sta chiudendo...) - private void fermaTutto(bool stopTimer, bool tryRestart, bool forceDequeue, bool updateForm) - { - iobObj.stopAdapter(tryRestart, forceDequeue); - // salvo! - savePersistLayer(utils.defPersLayerFile); - savePersistLayer(utils.histPersLayerFile); - - stop.Enabled = false; - start.Enabled = true; - restart.Enabled = false; - - if (stopTimer) - { - gather.Enabled = false; - iobObj.tryDisconnect(); - } - - newDisplayData currDispData = new newDisplayData(); - currDispData.semIn = Semaforo.SS; - currDispData.semOut = Semaforo.SS; - if (updateForm) - { - updateFormDisplay(currDispData); - } - } - - private void gather_Tick(object sender, EventArgs e) - { - bool doLog = false; - if (iobObj != null) - { - if (iobObj.periodicLog) - { - doLog = true; - } - try - { - refreshFormData(); - // check esecuzione SendTask (VHF) COMUNQUE... - checkSendTask(); - // eseguo cicli attivi SOLO se adapter è in EFFETTIVO running... - if (iobObj.adpRunning) - { - if (iobObj.connectionOk) + // se abilitato autoload conf leggo file corretto... + if (utils.CRB("autoLoadConf")) { - // se richiesto faccio memory DUMP INIZIALE! - if (iobObj.doStartMemDump) - { - lgInfo("Inizio dump memoria"); - iobObj.saveMemDump(dumpType.STARTUP); - // fatto! non ripeto... - iobObj.doStartMemDump = false; - lgInfo("Finito dump memoria"); - } - // controllo se sia abilitato sampleDump della meoria (periodico) - if (iobObj.doSampleMemory) - { - checkSampleMem(); - } - // check esecuzione FastTask - checkFastTask(); - // check esecuzione NormTask - checkNormTask(); - // check esecuzione SlowTask - checkSlowTask(); - // check esecuzione AlarmSync - checkVerySlowData(); - if (utils.CRI("waitEndCycle") > 0) - { - Thread.Sleep(utils.CRI("waitEndCycle")); - } + try + { + loadIniFile(defConfFilePath); + lgInfo("INI LOADED"); + } + catch (Exception exc) + { + displayTaskAndLog(string.Format("Eccezione in autoLoadConf: {0}", exc)); + } } else { - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec); - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) - { - if (doLog) + // definisco e avvio tipo adapter generico + tipoScelto = tipoAdapter.ND; + curVendor = "ACME"; + curModel = "NONE"; + IOBConf = new IobConfiguration(); + loadIobType(); + displayTaskAndLog("Waiting for config file selection"); + } + + // cerco tra i parametri opzionali se ho il parametro di + int timerIntMs = utils.CRI("timerIntMs"); + if (IOBConf.optPar.ContainsKey("timerIntMs")) + { + // recupero + string rawVal = IOBConf.optPar["timerIntMs"]; + if (!string.IsNullOrEmpty(rawVal)) { - lgInfo($"Retry Time Elapsed ({waitRecMSec} ms)--> tryConnect"); + int.TryParse(rawVal, out timerIntMs); + lgInfo($"Impostato timerIntMs da IOB.ini: {timerIntMs}"); } - lastStartTry = DateTime.Now; - iobObj.tryConnect(); - } } - } - else - { - if (doLog) + // Start timer periodico comunicazione + gather.Interval = timerIntMs; + gather.Enabled = true; + displayTaskAndLog(string.Format("Main timer set: {0}ms", gather.Interval)); + + // Start timer periodico interfaccia + displTimer.Interval = utils.CRI("timerIntMs"); + displTimer.Enabled = true; + + displayTaskAndLog("Program Running"); + + try { - lgInfo("Adapter stopped"); + // verifico server online... + if (iobObj.checkServerAlive) + { + // segnalo reboot (programma)... + IobGeneric.callUrl(iobObj.urlReboot, true); + } + else + { + displayTaskAndLog("AdapterForm: Server OFFLINE"); + } } - // verifico SE debba tentare il riavvio, ovvero NON running ma adpTryRestart e non ho riprovato x oltre waitRecMSec - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec); - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) + catch (Exception exc) { - lastStartTry = DateTime.Now; - avviaAdapter(chkForceDequeue.Checked); + lgError(string.Format("AdapterForm: EXCEPTION in fase di chiamata URL di reboot:{0}{1}{2}", iobObj.urlReboot, Environment.NewLine, exc)); } - } + displayTaskAndLog("Main Form OK"); } - catch (Exception exc) + + /// + /// File configurazione default + /// + public string defConfFilePath { - lgError(string.Format("Eccezione in fase di gatherTick: {0}{1}", Environment.NewLine, exc)); + get + { + return string.Format(@"{0}\{1}.ini", utils.confDir, CurrIOB); + } } - } - } - /// - /// Carica file ini della configurazione richiesta - /// - /// - private void loadIniFile(string iniConfFile) - { - // out di cosa faccio... - displayTaskAndLog(string.Format("Loading iniConfFile: {0}", iniConfFile)); - // leggo file - IniFile fIni = new IniFile(iniConfFile); - - // leggo vendor e modello... - curVendor = fIni.ReadString("MACHINE", "VENDOR", "ACME"); - curModel = fIni.ReadString("MACHINE", "MODEL", "NONE"); - // verifico tipo adapter - try - { - tipoScelto = (tipoAdapter)Enum.Parse(typeof(tipoAdapter), fIni.ReadString("IOB", "CNCTYPE", "DEMO")); - } - catch (Exception exc) - { - lgError($"Eccezione in conversione tipo adapter: richiesto un tipo non codificato...{Environment.NewLine}{exc}"); - tipoScelto = tipoAdapter.ND; - } - // carivo vettore parametri opzionai - Dictionary optParRead = new Dictionary(); - string[] optParRows = fIni.ReadSection("OPTPAR"); - if (optParRows.Length > 0) - { - try + /// + /// Init form (grafica) con helper x testi e varie + /// + protected void myGraphInitForm() { - string[] kvp; - foreach (var item in optParRows) - { - kvp = item.Split('='); - optParRead.Add(kvp[0], kvp[1]); - } - lgInfo($"Caricati {optParRead.Count} parametri opzionali da OPTPAR"); + lblStatus.Text = "Loading"; + + // aggiunta tooltip x send forzato + ToolTip ttForceSend = new ToolTip(); + + // imposto delay. + ttForceSend.AutoPopDelay = 3000; + ttForceSend.InitialDelay = 500; + ttForceSend.ReshowDelay = 500; + // sempre visibile (che sia o meno attiva la form). + ttForceSend.ShowAlways = true; + + // imposto tooltip + ttForceSend.SetToolTip(this.chkForceDequeue, "Forza invio eventi allo stop"); } - catch (Exception exc) + + /// + /// Fase chiusura Form + /// + /// + /// + private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { - lgError(string.Format("EXCEPTION in fase di lettura OPTPAR: {0}{1}", Environment.NewLine, exc)); + closeAdapter(); } - } - // inizializzio conf IOB - IOBConf = new IobConfiguration - { - pingMsTimeout = fIni.ReadInteger("IOB", "PING_MS_TIMEOUT", 500) - , - vendor = curVendor - , - model = curModel - , - tipoIob = tipoScelto - , - optPar = optParRead - , - versIOB = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() - , - codIOB = CurrIOB - , - cncIpAddr = fIni.ReadString("CNC", "IP", "::1") - , - cncPort = fIni.ReadString("CNC", "PORT", "0") - , - iniFileName = iniConfFile - , - cpuType = fIni.ReadString("CNC", "CPUTYPE", "") - , - rack = (short)fIni.ReadInteger("CNC", "RACK", 0) - , - slot = (short)fIni.ReadInteger("CNC", "SLOT", 0) - , - serverData = new serverMapo(fIni.ReadString("SERVER", "MPIP", "::1"), fIni.ReadString("SERVER", "MPURL", "/"), fIni.ReadString("SERVER", "CMDBASE", "/"), fIni.ReadString("SERVER", "CMDFLOG", "/"), fIni.ReadString("SERVER", "CMDALIVE", "/"), fIni.ReadString("SERVER", "CMDENABLED", "/"), fIni.ReadString("SERVER", "CMDREBO", "/"), fIni.ReadString("SERVER", "CMD_ODL_STARTED", "/IOB/getCurrOdlStart/")) - , - MAX_COUNTER_BLINK = Convert.ToInt32(fIni.ReadString("BLINK", "MAX_COUNTER_BLINK", "1")) - , - BLINK_FILT = Convert.ToInt32(fIni.ReadString("BLINK", "BLINK_FILT", "0")) - , - TCMaxDelayFactor = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_TC_FACTOR", "1.2").Replace(".", ",")) - , - TCLambda = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_LAMBDA", "0.5").Replace(".", ",")) - , - TCMaxIncrPz = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_INCR", "5").Replace(".", ",")) - }; - lgInfo($"Creato IOBConf!"); - loadIobType(); - // avvio macchina con adapter specificato... - if (utils.CRB("autoStartOnLoad")) - { - displayTaskAndLog("Auto Starting..."); - // avvio! - avviaAdapter(chkForceDequeue.Checked); - displayTaskAndLog("Auto Started!"); - } - try - { - // segnalo reboot (programma)... metto in coda invio... - //iobObj.sendToMoonPro(urlType.FLog, "IOB INI Loaded"); - //iobObj.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB INI Loaded")); - } - catch (Exception exc) - { - lgError(string.Format("EXCEPTION in fase di chiamata URL di segnalazione caricamento INI file:{0}{1}", Environment.NewLine, exc)); - } - } - - private void refreshFormData() - { - // aggiorno visualizzazioni varie in form... - evQueueLen = iobObj.QueueIN.Count; - flQueueLen = iobObj.QueueFLog.Count; - alQueueLen = iobObj.QueueAlarm.Count; - msQueueLen = iobObj.QueueMessages.Count; - // aggiorno labels counters... - counterIob = $"pz IOB {iobObj.contapezziIOB}"; - counterMac = $"pz PLC {iobObj.contapezziPLC}"; - // verifico IOB status - IobWinStatus currIobStatus = new IobWinStatus() - { - CodIob = iobObj.cIobConf.codIOB, - queueEvLen = evQueueLen, - queueFlLen = flQueueLen, - queueAlLen = alQueueLen, - queueMsLen = msQueueLen, - counterIOB = iobObj.contapezziIOB, - counterMAC = iobObj.contapezziPLC, - lastUpdate = lastIobStatus.lastUpdate, - online = utils.IOB_Online, - lastDataIn = iobObj.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) - { - // aggiorno data - currIobStatus.lastUpdate = DateTime.Now; - // salvo su redis e in obj corrente - iobObj.redisMan.iobStatus = currIobStatus; - lastIobStatus = currIobStatus; - } - // se diverso SALVO MP IO status - if (lastSrvStatus.online != utils.MPIO_Online) - { - // aggiorno - ServerMpStatus currSrvStatus = iobObj.redisMan.servStatus; - currSrvStatus.online = utils.MPIO_Online; - currSrvStatus.lastUpdate = DateTime.Now; - // salvo su redis e in obj corrente - iobObj.redisMan.servStatus = currSrvStatus; - lastSrvStatus = currSrvStatus; - } - } - - /// - /// Salva su file l'oggetto di persistenza dati - /// - /// - public void savePersistLayer(string filePath) - { - // in primis check semaforo salvataggio... - if (!iobObj.adpSaving) - { - // alzo semaforo salvataggio - iobObj.adpSaving = true; - // se HO dei dati... - if (iobObj.persistenceLayer != null) + /// + /// Completato resize form + /// + /// + /// + private void MainForm_Resize(object sender, EventArgs e) { - try - { - utils.WritePlain(iobObj.persistenceLayer, filePath); - } - catch (Exception exc) - { - lgError(string.Format("Errore salvataggio file{0}{1}", Environment.NewLine, exc)); - } } - else + + /// + /// Mostrata form + /// + /// + /// + private void MainForm_Shown(object sender, EventArgs e) { - lgInfo("persistenceLayer null, non salvato..."); + displayTaskAndLog("Main Form SHOWN"); } - // abbasso semaforo salvataggio - iobObj.adpSaving = false; - } - } - #endregion gestione metodi specifici FORM + #endregion gestione form e visibilità - #region Area BackGroundWorker + #region gestione metodi specifici FORM - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - /// - /// Effettua update form una volta ricevuto OBJ che contiene le varie innovazioni... - /// - /// - public void updateFormDisplay(newDisplayData currDispData) - { - // ciclo x ogni oggetto x caricare le innovazioni... - if (currDispData != null && currDispData.hasData) - { - // RealTime display - if (!string.IsNullOrWhiteSpace(currDispData.newInData)) + /// + /// Salva su file l'oggetto di persistenza dati + /// + /// + public void savePersistLayer(string filePath) { - dataMonitor_0 = limitLine2show($"{currDispData.newInData}{Environment.NewLine}{dataMonitor_0}"); + // in primis check semaforo salvataggio... + if (!iobObj.adpSaving) + { + // alzo semaforo salvataggio + iobObj.adpSaving = true; + // se HO dei dati... + if (iobObj.persistenceLayer != null) + { + try + { + utils.WritePlain(iobObj.persistenceLayer, filePath); + } + catch (Exception exc) + { + lgError(string.Format("Errore salvataggio file{0}{1}", Environment.NewLine, exc)); + } + } + else + { + lgInfo("persistenceLayer null, non salvato..."); + } + // abbasso semaforo salvataggio + iobObj.adpSaving = false; + } } - if (!string.IsNullOrWhiteSpace(currDispData.newSignalData)) + + private void checkFastTask() { - dataMonitor_1 = limitLine2show($"{currDispData.newSignalData}{Environment.NewLine}{dataMonitor_1}"); + // decremento... + fastCount--; + // se il counter è a zero eseguo... + if (fastCount <= 0) + { + fastCount = utils.CRI("fastCount"); + + // avvio fase raccolta dati e invio con adapter + iobObj.getAndSend(gatherCycle.HF); + } } - if (!string.IsNullOrWhiteSpace(currDispData.newFLogData)) + + private void checkNormTask() { - dataMonitor_3 = limitLine2show($"{currDispData.newFLogData}{Environment.NewLine}{dataMonitor_3}"); + // decremento... + normCount--; + // se il counter è a zero eseguo... + if (normCount <= 0) + { + normCount = utils.CRI("normCount"); + + // avvio fase raccolta dati e invio con adapter + iobObj.getAndSend(gatherCycle.MF); + } } - if (!string.IsNullOrWhiteSpace(currDispData.newUrlCallData)) + + private void checkSampleMem() { - dataMonitor_2 = limitLine2show($"{currDispData.newUrlCallData}{Environment.NewLine}{dataMonitor_2}"); + // decremento contatore... + sampleMemCount--; + if (sampleMemCount <= 0) + { + sampleMemCount = utils.CRI("sampleMemCount"); + // avvio fase raccolta dati e invio con adapter + iobObj.saveMemDump(dumpType.SAMPLE); + } } - // Bitmap lettura attuale - if (currDispData.counter >= 0) + private void checkSendTask() { - lblCounter.Text = currDispData.counter.ToString(); + // avvio fase invio con adapter (code MST) + iobObj.getAndSend(gatherCycle.VHF); } - // Bitmap lettura attuale - if (!string.IsNullOrWhiteSpace(currDispData.currBitmap)) + + private void checkSlowTask() { - lblBitmap.Text = currDispData.currBitmap; - lblBitmap.Refresh(); + slowCount--; + if (slowCount <= 0) + { + slowCount = utils.CRI("slowCount"); + + // avvio fase raccolta dati e invio con adapter + iobObj.getAndSend(gatherCycle.LF); + } } - // LiveLog - if (!string.IsNullOrWhiteSpace(currDispData.newLiveLogData)) + + private void checkVerySlowData() { - logWatcher = currDispData.newLiveLogData; + verySlowCount--; + if (verySlowCount <= 0) + { + verySlowCount = utils.CRI("verySlowCount"); + // avvio fase raccolta dati e invio con adapter + iobObj.getAndSend(gatherCycle.VLF); + } } - // semafori - if (currDispData.semOut != Semaforo.ND) + + /// + /// Chiusura adapter + /// + private void closeAdapter() { - //aggiorno comunque! - sOUT = currDispData.semOut; + fermaTutto(true, false, true, false); } - if (currDispData.semIn != Semaforo.ND) + + /// + /// Ferma tutti i componenti adapter + update buttons + /// + /// indica se fermare il timer (gather) principale (solo se non si chiude) + /// indica se tentare di riconnettersi + /// indica se sia richeisto di SVUOTARE le code delel info + /// indica se si debba aggiornare la form (no se si sta chiudendo...) + private void fermaTutto(bool stopTimer, bool tryRestart, bool forceDequeue, bool updateForm) { - //aggiorno comunque! - sIN = currDispData.semIn; + iobObj.stopAdapter(tryRestart, forceDequeue); + // salvo! + savePersistLayer(utils.defPersLayerFile); + savePersistLayer(utils.histPersLayerFile); + + stop.Enabled = false; + start.Enabled = true; + restart.Enabled = false; + + if (stopTimer) + { + gather.Enabled = false; + iobObj.tryDisconnect(); + } + + newDisplayData currDispData = new newDisplayData(); + currDispData.semIn = Semaforo.SS; + currDispData.semOut = Semaforo.SS; + if (updateForm) + { + updateFormDisplay(currDispData); + } } - } - } - #endregion Area BackGroundWorker - - #region Area gestione controlli threadSafe - - private delegate void SafeCallDelegate(string text); - - public void WriteTextSafe(string text) - { - if (lblOutMessage3.InvokeRequired) - { - var d = new SafeCallDelegate(WriteTextSafe); - lblOutMessage3.Invoke(d, new object[] { text }); - } - else - { - lblOutMessage3.Text = text; - } - } - - #endregion Area gestione controlli threadSafe - - - - #region Protected Properties - - /// - /// Valore protected comunicazione PLC - /// - protected bool _commPlcActive { get; set; } = false; - - /// - /// Valore protetto stato comunicazione - /// - protected int _commSrvActive { get; set; } = 0; - - /// - /// Valore protected semaforo IN - /// - protected Semaforo _sIN { get; set; } = Semaforo.ND; - - /// - /// Valore protected semaforo OUT - /// - protected Semaforo _sOUT { get; set; } = Semaforo.ND; - - protected int maxAlQueue { get; set; } - - protected int maxEvQueue { get; set; } - - protected int maxFlQueue { get; set; } - - protected int maxMsQueue { get; set; } - - protected int qAlLen { get; set; } - - protected int qEvLen { get; set; } - - protected int qFlLen { get; set; } - - protected int qMsLen { get; set; } - - protected int totQueue - { - get - { - return qEvLen + qFlLen + qAlLen + qMsLen; - } - } - - #endregion Protected Properties - - public int alQueueLen - { - set - { - qAlLen = value; - lblQueueAlarmLen.Text = qAlLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qAlLen > maxAlQueue && qAlLen > 10) + private void gather_Tick(object sender, EventArgs e) { - maxAlQueue = qAlLen; - lgInfo($"[WARN] Coda FLog di {value} record"); + bool doLog = false; + if (iobObj != null) + { + if (iobObj.periodicLog) + { + doLog = true; + } + try + { + refreshFormData(); + // check esecuzione SendTask (VHF) COMUNQUE... + checkSendTask(); + // eseguo cicli attivi SOLO se adapter è in EFFETTIVO running... + if (iobObj.adpRunning) + { + if (iobObj.connectionOk) + { + // se richiesto faccio memory DUMP INIZIALE! + if (iobObj.doStartMemDump) + { + lgInfo("Inizio dump memoria"); + iobObj.saveMemDump(dumpType.STARTUP); + // fatto! non ripeto... + iobObj.doStartMemDump = false; + lgInfo("Finito dump memoria"); + } + // controllo se sia abilitato sampleDump della meoria (periodico) + if (iobObj.doSampleMemory) + { + checkSampleMem(); + } + // check esecuzione FastTask + checkFastTask(); + // check esecuzione NormTask + checkNormTask(); + // check esecuzione SlowTask + checkSlowTask(); + // check esecuzione AlarmSync + checkVerySlowData(); + if (utils.CRI("waitEndCycle") > 0) + { + Thread.Sleep(utils.CRI("waitEndCycle")); + } + } + else + { + DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec); + if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) + { + if (doLog) + { + lgInfo($"Retry Time Elapsed ({waitRecMSec} ms)--> tryConnect"); + } + lastStartTry = DateTime.Now; + iobObj.tryConnect(); + } + } + } + else + { + if (doLog) + { + lgInfo("Adapter stopped"); + } + // verifico SE debba tentare il riavvio, ovvero NON running ma adpTryRestart e non ho riprovato x oltre waitRecMSec + DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec); + if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) + { + lastStartTry = DateTime.Now; + avviaAdapter(chkForceDequeue.Checked); + } + } + } + catch (Exception exc) + { + lgError(string.Format("Eccezione in fase di gatherTick: {0}{1}", Environment.NewLine, exc)); + } + } } - else + + /// + /// Carica file ini della configurazione richiesta + /// + /// + private void loadIniFile(string iniConfFile) { - maxAlQueue--; - maxAlQueue = maxAlQueue < qAlLen ? qAlLen : maxAlQueue; + // out di cosa faccio... + displayTaskAndLog(string.Format("Loading iniConfFile: {0}", iniConfFile)); + // leggo file + IniFile fIni = new IniFile(iniConfFile); + + // leggo vendor e modello... + curVendor = fIni.ReadString("MACHINE", "VENDOR", "ACME"); + curModel = fIni.ReadString("MACHINE", "MODEL", "NONE"); + // verifico tipo adapter + try + { + tipoScelto = (tipoAdapter)Enum.Parse(typeof(tipoAdapter), fIni.ReadString("IOB", "CNCTYPE", "DEMO")); + } + catch (Exception exc) + { + lgError($"Eccezione in conversione tipo adapter: richiesto un tipo non codificato...{Environment.NewLine}{exc}"); + tipoScelto = tipoAdapter.ND; + } + // carivo vettore parametri opzionai + Dictionary optParRead = new Dictionary(); + string[] optParRows = fIni.ReadSection("OPTPAR"); + if (optParRows.Length > 0) + { + try + { + string[] kvp; + foreach (var item in optParRows) + { + kvp = item.Split('='); + optParRead.Add(kvp[0], kvp[1]); + } + lgInfo($"Caricati {optParRead.Count} parametri opzionali da OPTPAR"); + } + catch (Exception exc) + { + lgError(string.Format("EXCEPTION in fase di lettura OPTPAR: {0}{1}", Environment.NewLine, exc)); + } + } + // inizializzio conf IOB + IOBConf = new IobConfiguration + { + pingMsTimeout = fIni.ReadInteger("IOB", "PING_MS_TIMEOUT", 500) + , + vendor = curVendor + , + model = curModel + , + tipoIob = tipoScelto + , + optPar = optParRead + , + versIOB = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + , + codIOB = CurrIOB + , + cncIpAddr = fIni.ReadString("CNC", "IP", "::1") + , + cncPort = fIni.ReadString("CNC", "PORT", "0") + , + iniFileName = iniConfFile + , + cpuType = fIni.ReadString("CNC", "CPUTYPE", "") + , + rack = (short)fIni.ReadInteger("CNC", "RACK", 0) + , + slot = (short)fIni.ReadInteger("CNC", "SLOT", 0) + , + serverData = new serverMapo(fIni.ReadString("SERVER", "MPIP", "::1"), fIni.ReadString("SERVER", "MPURL", "/"), fIni.ReadString("SERVER", "CMDBASE", "/"), fIni.ReadString("SERVER", "CMDFLOG", "/"), fIni.ReadString("SERVER", "CMDALIVE", "/"), fIni.ReadString("SERVER", "CMDENABLED", "/"), fIni.ReadString("SERVER", "CMDREBO", "/"), fIni.ReadString("SERVER", "CMD_ODL_STARTED", "/IOB/getCurrOdlStart/")) + , + MAX_COUNTER_BLINK = Convert.ToInt32(fIni.ReadString("BLINK", "MAX_COUNTER_BLINK", "1")) + , + BLINK_FILT = Convert.ToInt32(fIni.ReadString("BLINK", "BLINK_FILT", "0")) + , + TCMaxDelayFactor = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_TC_FACTOR", "1.2").Replace(".", ",")) + , + TCLambda = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_LAMBDA", "0.5").Replace(".", ",")) + , + TCMaxIncrPz = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_INCR", "5").Replace(".", ",")) + }; + lgInfo($"Creato IOBConf!"); + + loadIobType(); + // avvio macchina con adapter specificato... + if (utils.CRB("autoStartOnLoad")) + { + displayTaskAndLog("Auto Starting..."); + // avvio! + avviaAdapter(chkForceDequeue.Checked); + displayTaskAndLog("Auto Started!"); + } + try + { + // segnalo reboot (programma)... metto in coda invio... + //iobObj.sendToMoonPro(urlType.FLog, "IOB INI Loaded"); + //iobObj.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB INI Loaded")); + } + catch (Exception exc) + { + lgError(string.Format("EXCEPTION in fase di chiamata URL di segnalazione caricamento INI file:{0}{1}", Environment.NewLine, exc)); + } } - } - get - { - return qAlLen; - } - } - /// - /// Visualizzazione stato di comunicazione attiva con PLC - /// - public bool commPlcActive - { - get - { - return _commPlcActive; - } - set - { - _commPlcActive = value; - // se true --> comunica/verde, altrimenti grigio - lblCNC.ForeColor = value ? Color.SeaGreen : Color.Black; - statusStrip1.Refresh(); - } - } - - /// - /// Visualizzazione stato di comunicazione attiva con PLC: - /// 0 = NO PING - /// 1 = PING OK - /// 2 = IOB enabled - /// - public int commSrvActive - { - get - { - return _commSrvActive; - } - set - { - _commSrvActive = value; - switch (value) + private void refreshFormData() { - case 0: - lblSrvUrl.ForeColor = Color.Red; - break; - - case 1: - lblSrvUrl.ForeColor = Color.OrangeRed; - break; - - case 2: - lblSrvUrl.ForeColor = Color.SeaGreen; - break; - - default: - break; + // aggiorno visualizzazioni varie in form... + evQueueLen = iobObj.QueueIN.Count; + flQueueLen = iobObj.QueueFLog.Count; + alQueueLen = iobObj.QueueAlarm.Count; + msQueueLen = iobObj.QueueMessages.Count; + // aggiorno labels counters... + counterIob = $"pz IOB {iobObj.contapezziIOB}"; + counterMac = $"pz PLC {iobObj.contapezziPLC}"; + // verifico IOB status + IobWinStatus currIobStatus = new IobWinStatus() + { + CodIob = iobObj.cIobConf.codIOB, + queueEvLen = evQueueLen, + queueFlLen = flQueueLen, + queueAlLen = alQueueLen, + queueMsLen = msQueueLen, + counterIOB = iobObj.contapezziIOB, + counterMAC = iobObj.contapezziPLC, + lastUpdate = lastIobStatus.lastUpdate, + online = utils.IOB_Online, + lastDataIn = iobObj.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) + { + // aggiorno data + currIobStatus.lastUpdate = DateTime.Now; + // salvo su redis e in obj corrente + iobObj.redisMan.iobStatus = currIobStatus; + lastIobStatus = currIobStatus; + } + // se diverso SALVO MP IO status + if (lastSrvStatus.online != utils.MPIO_Online) + { + // aggiorno + ServerMpStatus currSrvStatus = iobObj.redisMan.servStatus; + currSrvStatus.online = utils.MPIO_Online; + currSrvStatus.lastUpdate = DateTime.Now; + // salvo su redis e in obj corrente + iobObj.redisMan.servStatus = currSrvStatus; + lastSrvStatus = currSrvStatus; + } } - statusStrip1.Refresh(); - } - } - public string counterIob - { - get - { - return lblPzCountIob.Text; - } - set - { - lblPzCountIob.Text = value; - } - } + #endregion gestione metodi specifici FORM - public string counterMac - { - get - { - return lblPzCountMac.Text; - } - set - { - lblPzCountMac.Text = value; - } - } + #region Area BackGroundWorker - /// - /// Stringa dati monitoraggio mostrata (1 SX)... - /// - public string dataMonitor_0 - { - get - { - return lblRawData.Text; - } - set - { - lblRawData.Text = value; - } - } - - /// - /// Stringa dati monitoraggio mostrata (1 SX)... - /// - public string dataMonitor_1 - { - get - { - return lblOutMessage.Text; - } - set - { - lblOutMessage.Text = value; - } - } - - /// - /// Stringa dati monitoraggio mostrata (2 centro)... - /// - public string dataMonitor_2 - { - get - { - return lblOutMessage2.Text; - } - set - { - lblOutMessage2.Text = value; - } - } - - /// - /// Stringa dati monitoraggio mostrata (3 dx)... - /// - public string dataMonitor_3 - { - get - { - return lblOutMessage3.Text; - } - set - { - lblOutMessage3.Text = value; - } - } - - /// - /// label del numero di record processati (libera) - /// - public string dataProcLabel - { - get - { - return lblDataProc.Text; - } - set - { - lblDataProc.Text = value; - } - } - - public bool enableEditMes2Plc { get; set; } - - public int evQueueLen - { - set - { - qEvLen = value; - lblQueueLen.Text = qEvLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qEvLen > maxEvQueue && qEvLen > 10) + /// + /// Effettua update form una volta ricevuto OBJ che contiene le varie innovazioni... + /// + /// + public void updateFormDisplay(newDisplayData currDispData) { - maxEvQueue = qEvLen; - lgInfo($"[WARN] Coda EV di {value} record"); + // ciclo x ogni oggetto x caricare le innovazioni... + if (currDispData != null && currDispData.hasData) + { + // RealTime display + if (!string.IsNullOrWhiteSpace(currDispData.newInData)) + { + dataMonitor_0 = limitLine2show($"{currDispData.newInData}{Environment.NewLine}{dataMonitor_0}"); + } + if (!string.IsNullOrWhiteSpace(currDispData.newSignalData)) + { + dataMonitor_1 = limitLine2show($"{currDispData.newSignalData}{Environment.NewLine}{dataMonitor_1}"); + } + if (!string.IsNullOrWhiteSpace(currDispData.newFLogData)) + { + dataMonitor_3 = limitLine2show($"{currDispData.newFLogData}{Environment.NewLine}{dataMonitor_3}"); + } + if (!string.IsNullOrWhiteSpace(currDispData.newUrlCallData)) + { + dataMonitor_2 = limitLine2show($"{currDispData.newUrlCallData}{Environment.NewLine}{dataMonitor_2}"); + } + + // Bitmap lettura attuale + if (currDispData.counter >= 0) + { + lblCounter.Text = currDispData.counter.ToString(); + } + // Bitmap lettura attuale + if (!string.IsNullOrWhiteSpace(currDispData.currBitmap)) + { + lblBitmap.Text = currDispData.currBitmap; + lblBitmap.Refresh(); + } + // LiveLog + if (!string.IsNullOrWhiteSpace(currDispData.newLiveLogData)) + { + logWatcher = currDispData.newLiveLogData; + } + // semafori + if (currDispData.semOut != Semaforo.ND) + { + //aggiorno comunque! + sOUT = currDispData.semOut; + } + if (currDispData.semIn != Semaforo.ND) + { + //aggiorno comunque! + sIN = currDispData.semIn; + } + } } - else + + protected override void Dispose(bool disposing) { - maxEvQueue--; - maxEvQueue = maxEvQueue < qEvLen ? qEvLen : maxEvQueue; + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); } - } - get - { - return qEvLen; - } - } - public int flQueueLen - { - set - { - qFlLen = value; - lblQueueFLogLen.Text = qFlLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qFlLen > maxFlQueue && qFlLen > 10) + #endregion Area BackGroundWorker + + #region Area gestione controlli threadSafe + + private delegate void SafeCallDelegate(string text); + + public void WriteTextSafe(string text) { - maxFlQueue = qFlLen; - lgInfo($"[WARN] Coda FLog di {value} record"); + if (lblOutMessage3.InvokeRequired) + { + var d = new SafeCallDelegate(WriteTextSafe); + lblOutMessage3.Invoke(d, new object[] { text }); + } + else + { + lblOutMessage3.Text = text; + } } - else + + #endregion Area gestione controlli threadSafe + + #region Protected Properties + + /// + /// Valore protected comunicazione PLC + /// + protected bool _commPlcActive { get; set; } = false; + + /// + /// Valore protetto stato comunicazione + /// + protected int _commSrvActive { get; set; } = 0; + + /// + /// Valore protected semaforo IN + /// + protected Semaforo _sIN { get; set; } = Semaforo.ND; + + /// + /// Valore protected semaforo OUT + /// + protected Semaforo _sOUT { get; set; } = Semaforo.ND; + + protected int maxAlQueue { get; set; } + + protected int maxEvQueue { get; set; } + + protected int maxFlQueue { get; set; } + + protected int maxMsQueue { get; set; } + + protected int qAlLen { get; set; } + + protected int qEvLen { get; set; } + + protected int qFlLen { get; set; } + + protected int qMsLen { get; set; } + + protected int totQueue { - maxFlQueue--; - maxFlQueue = maxFlQueue < qFlLen ? qFlLen : maxFlQueue; + get + { + return qEvLen + qFlLen + qAlLen + qMsLen; + } } - } - get - { - return qFlLen; - } - } - public int msQueueLen - { - set - { - qMsLen = value; - lblQueueMessLen.Text = qMsLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qMsLen > maxMsQueue && qMsLen > 10) + #endregion Protected Properties + + public int alQueueLen { - maxMsQueue = qMsLen; - lgInfo($"[WARN] Coda FLog di {value} record"); + set + { + qAlLen = value; + lblQueueAlarmLen.Text = qAlLen.ToString(); + showQueueData(); + // se supero max precedente, ed è > 10... loggo! + if (qAlLen > maxAlQueue && qAlLen > 10) + { + maxAlQueue = qAlLen; + lgInfo($"[WARN] Coda FLog di {value} record"); + } + else + { + maxAlQueue--; + maxAlQueue = maxAlQueue < qAlLen ? qAlLen : maxAlQueue; + } + } + get + { + return qAlLen; + } } - else + + /// + /// Visualizzazione stato di comunicazione attiva con PLC + /// + public bool commPlcActive { - maxMsQueue--; - maxMsQueue = maxMsQueue < qMsLen ? qMsLen : maxMsQueue; + get + { + return _commPlcActive; + } + set + { + _commPlcActive = value; + // se true --> comunica/verde, altrimenti grigio + lblCNC.ForeColor = value ? Color.SeaGreen : Color.Black; + statusStrip1.Refresh(); + } } - } - get - { - return qMsLen; - } - } - /// - /// Numero max linee da mostrare (da controllo)... - /// - public int nLine2show - { - get - { - int answ = 5; - try + /// + /// Visualizzazione stato di comunicazione attiva con PLC: + /// 0 = NO PING + /// 1 = PING OK + /// 2 = IOB enabled + /// + public int commSrvActive { - Int32.TryParse(nLines.Text, out answ); + get + { + return _commSrvActive; + } + set + { + _commSrvActive = value; + switch (value) + { + case 0: + lblSrvUrl.ForeColor = Color.Red; + break; + + case 1: + lblSrvUrl.ForeColor = Color.OrangeRed; + break; + + case 2: + lblSrvUrl.ForeColor = Color.SeaGreen; + break; + + default: + break; + } + statusStrip1.Refresh(); + } } - catch - { } - return answ; - } - set - { - nLines.Text = value.ToString(); - } - } - /// - /// Imposta COLORE SFONDO x Semaforo IN - /// - public Semaforo sIN - { - get - { - return _sIN; - } - set - { - _sIN = value; - bIN.BackColor = decSemaforo(value); - bIN.Refresh(); - } - } + public string counterIob + { + get + { + return lblPzCountIob.Text; + } + set + { + lblPzCountIob.Text = value; + } + } - /// - /// Imposta COLORE SFONDO x Semaforo OUT - /// - public Semaforo sOUT - { - get - { - return _sOUT; - } - set - { - _sOUT = value; - bOUT.BackColor = decSemaforo(value); - bOUT.Refresh(); - } - } + public string counterMac + { + get + { + return lblPzCountMac.Text; + } + set + { + lblPzCountMac.Text = value; + } + } - private void BtnOpenLog_Click(object sender, EventArgs e) - { - try - { - string logPath = $"{System.AppDomain.CurrentDomain.BaseDirectory}logs\\{CurrIOB}\\{DateTime.Today:yyyy-MM-dd}.log"; - Process.Start(logPath); - } - catch (Exception exc) - { - lgError($"Eccezione in show log (MAIN):{Environment.NewLine}{exc}"); - } - } + /// + /// Stringa dati monitoraggio mostrata (1 SX)... + /// + public string dataMonitor_0 + { + get + { + return lblRawData.Text; + } + set + { + lblRawData.Text = value; + } + } - private void BtnSendPLC_Click(object sender, EventArgs e) - { - // invia a MES il parametro selezionato (es ART / ODL / PRG NAME, come task2exe..) - Dictionary forcedTask = new Dictionary(); - // guardo i parametri... - if (txtValue.Text != "") - { - forcedTask.Add(cmbParamValues.SelectedValue.ToString(), txtValue.Text); - } + /// + /// Stringa dati monitoraggio mostrata (1 SX)... + /// + public string dataMonitor_1 + { + get + { + return lblOutMessage.Text; + } + set + { + lblOutMessage.Text = value; + } + } + + /// + /// Stringa dati monitoraggio mostrata (2 centro)... + /// + public string dataMonitor_2 + { + get + { + return lblOutMessage2.Text; + } + set + { + lblOutMessage2.Text = value; + } + } + + /// + /// Stringa dati monitoraggio mostrata (3 dx)... + /// + public string dataMonitor_3 + { + get + { + return lblOutMessage3.Text; + } + set + { + lblOutMessage3.Text = value; + } + } + + /// + /// label del numero di record processati (libera) + /// + public string dataProcLabel + { + get + { + return lblDataProc.Text; + } + set + { + lblDataProc.Text = value; + } + } + + public bool enableEditMes2Plc { get; set; } + + public int evQueueLen + { + set + { + qEvLen = value; + lblQueueLen.Text = qEvLen.ToString(); + showQueueData(); + // se supero max precedente, ed è > 10... loggo! + if (qEvLen > maxEvQueue && qEvLen > 10) + { + maxEvQueue = qEvLen; + lgInfo($"[WARN] Coda EV di {value} record"); + } + else + { + maxEvQueue--; + maxEvQueue = maxEvQueue < qEvLen ? qEvLen : maxEvQueue; + } + } + get + { + return qEvLen; + } + } + + public int flQueueLen + { + set + { + qFlLen = value; + lblQueueFLogLen.Text = qFlLen.ToString(); + showQueueData(); + // se supero max precedente, ed è > 10... loggo! + if (qFlLen > maxFlQueue && qFlLen > 10) + { + maxFlQueue = qFlLen; + lgInfo($"[WARN] Coda FLog di {value} record"); + } + else + { + maxFlQueue--; + maxFlQueue = maxFlQueue < qFlLen ? qFlLen : maxFlQueue; + } + } + get + { + return qFlLen; + } + } + + public int msQueueLen + { + set + { + qMsLen = value; + lblQueueMessLen.Text = qMsLen.ToString(); + showQueueData(); + // se supero max precedente, ed è > 10... loggo! + if (qMsLen > maxMsQueue && qMsLen > 10) + { + maxMsQueue = qMsLen; + lgInfo($"[WARN] Coda FLog di {value} record"); + } + else + { + maxMsQueue--; + maxMsQueue = maxMsQueue < qMsLen ? qMsLen : maxMsQueue; + } + } + get + { + return qMsLen; + } + } + + /// + /// Numero max linee da mostrare (da controllo)... + /// + public int nLine2show + { + get + { + int answ = 5; + try + { + Int32.TryParse(nLines.Text, out answ); + } + catch + { } + return answ; + } + set + { + nLines.Text = value.ToString(); + } + } + + /// + /// Imposta COLORE SFONDO x Semaforo IN + /// + public Semaforo sIN + { + get + { + return _sIN; + } + set + { + _sIN = value; + bIN.BackColor = decSemaforo(value); + bIN.Refresh(); + } + } + + /// + /// Imposta COLORE SFONDO x Semaforo OUT + /// + public Semaforo sOUT + { + get + { + return _sOUT; + } + set + { + _sOUT = value; + bOUT.BackColor = decSemaforo(value); + bOUT.Refresh(); + } + } + + /// + /// Decodifica colore da valore semaforico + /// + /// + /// + public static Color decSemaforo(Semaforo valore) + { + Color colore = Color.LightGray; + switch (valore) + { + case Semaforo.SV: + colore = Color.LightGreen; + break; + + case Semaforo.SG: + colore = Color.LightGoldenrodYellow; + break; + + case Semaforo.SR: + colore = Color.Red; + break; + + case Semaforo.SS: + colore = Color.DarkGray; + break; + + default: + colore = Color.LightGray; + break; + } + return colore; + } + + /// + /// Avvio l'adapter + /// + /// indica se sia richeisto di SVUOTARE le code delel info + public void avviaAdapter(bool resetQueue) + { + displayTaskAndLog("Adapter starting"); + // se NON sta girando... + if (!iobObj.adpRunning) + { + iobObj.startAdapter(resetQueue); + displayTaskAndLog("Adapter started!"); + + // fix buttons start/stop/dump + start.Enabled = false; + stop.Enabled = true; + restart.Enabled = true; + + displayTaskAndLog("Start Timers"); + // inizializzo contatori fast/mid/slow + fastCount = utils.CRI("fastCount"); + normCount = utils.CRI("normCount"); + slowCount = utils.CRI("slowCount"); + verySlowCount = utils.CRI("verySlowCount"); + displayTaskAndLog("Adapter Running..."); + // init max queue + maxEvQueue = 1; + maxFlQueue = 1; + + try + { + // segnalo reboot (programma)... + iobObj.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB Started")); + } + catch (Exception exc) + { + lgError(string.Format("EXCEPTION in fase di chiamata URL di segnalazione AVVIO IOB:{0}{1}", Environment.NewLine, exc)); + } + } + else + { + displayTaskAndLog("Adapter STILL Running..."); + } + } + + /// + /// Ferma l'adapter + /// + /// determina se si debba tentare riavvio automatico (per caduta connessione) + /// indica se sia richeisto di SVUOTARE le code delel info + /// indica se aggiornare la form prima di fermare + public void fermaAdapter(bool tryRestart, bool forceDequeue, bool updateForm) + { + fermaTutto(false, tryRestart, forceDequeue, updateForm); + } + + /// + /// MOstra info su coda complessiva + /// + protected void showQueueData() + { + lblQueueLenTop.Text = totQueue == 0 ? "realtime" : $"ev: {qEvLen} | flog: {qFlLen} | tot: {totQueue}"; + } + + private void BtnOpenLog_Click(object sender, EventArgs e) + { + try + { + string logPath = $"{System.AppDomain.CurrentDomain.BaseDirectory}logs\\{CurrIOB}\\{DateTime.Today:yyyy-MM-dd}.log"; + Process.Start(logPath); + } + catch (Exception exc) + { + lgError($"Eccezione in show log (MAIN):{Environment.NewLine}{exc}"); + } + } + + private void BtnSendPLC_Click(object sender, EventArgs e) + { + // invia a MES il parametro selezionato (es ART / ODL / PRG NAME, come task2exe..) + Dictionary forcedTask = new Dictionary(); + // guardo i parametri... + if (txtValue.Text != "") + { + forcedTask.Add(cmbParamValues.SelectedValue.ToString(), txtValue.Text); + } #if false // accodo SE !="" if (currItemCode != "") @@ -1302,387 +1397,300 @@ namespace IOB_WIN forcedTask.Add("setProg", currPrgName); } #endif - // chiedo esecuzione task! - iobObj.processTask(forcedTask); - toggleEditMes2Plc(); - } + // chiedo esecuzione task! + iobObj.processTask(forcedTask); + toggleEditMes2Plc(); + } - private void checkEditMes2Plc() - { - cmbParamValues.Enabled = enableEditMes2Plc; - txtValue.Enabled = enableEditMes2Plc; - if (enableEditMes2Plc) - { - // aggiorno (se possibile) i parametri selezionabili... - fixComboParameters(); - } - } - - private void ChkEdit_CheckedChanged(object sender, EventArgs e) - { - toggleEditMes2Plc(); - } - - private void displTimer_Tick(object sender, EventArgs e) - { - } - - private void fixComboParameters() - { - if (iobObj != null) - { - if (iobObj.memMap != null) + private void checkEditMes2Plc() { - if (iobObj.memMap.mMapWrite != null) - { - if (iobObj.memMap.mMapWrite.Count > 0) + cmbParamValues.Enabled = enableEditMes2Plc; + txtValue.Enabled = enableEditMes2Plc; + if (enableEditMes2Plc) { - List parametri = new List(); - foreach (var item in iobObj.memMap.mMapWrite) - { - parametri.Add(item.Key); - } - cmbParamValues.DataSource = parametri; + // aggiorno (se possibile) i parametri selezionabili... + fixComboParameters(); } - } } - } - } - /// - /// GEstione evento refresh - /// - /// - /// - private void IobObj_eh_refreshed(object sender, iobRefreshedEventArgs e) - { - // aggiorno! - updateFormDisplay(e.DisplayDataObject); - } - - /// - /// carica IOB richiesto - /// - private void loadIobType() - { - switch (tipoScelto) - { - case tipoAdapter.SIMULA: - iobObj = new IobSimula(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.FANUC: - iobObj = new IobFanuc(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.KAWASAKI: - iobObj = new IobKawasaki(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.MTConnect: - iobObj = new IobMTC(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.OMRON: - iobObj = new IobOmron(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.OSAI_OPEN: - case tipoAdapter.OSAI_CNDEX: - case tipoAdapter.OSAI_VB6: - // versione CVCncLib - iobObj = new IobOSAI(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS: - iobObj = new IobSiemens(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_APROCHIM: - iobObj = new IobSiemensAprochim(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_AT2001: - iobObj = new IobSiemensAt2001(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_COMUR: - iobObj = new IobSiemensComur(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_FAPE: - iobObj = new IobSiemensFape(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_INGENIA: - iobObj = new IobSiemensIngenia(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_LASCO: - iobObj = new IobSiemensLasco(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_PRESSOIL_CEI: - iobObj = new IobSiemensPressoilCei(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_SAET: - iobObj = new IobSiemensSaet(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_SIMEC: - iobObj = new IobSiemensSimec(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_TORRI: - iobObj = new IobSiemensTorri(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.WPS: - iobObj = new IobWPS(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.ND: - default: - iobObj = new IobSimula(this, IOBConf); - start.Enabled = false; - break; - } - lblCNC.Text = $"CNC: {IOBConf.tipoIob} [{IOBConf.cncIpAddr}:{IOBConf.cncPort}]"; - lblSrvUrl.Text = $"SRV: {IOBConf.serverData.MPIP} | URL: {IOBConf.serverData.MPURL}{IOBConf.serverData.CMDBASE}"; - - // aggancio evento refresh - iobObj.eh_refreshed += IobObj_eh_refreshed; - - // carico i default values su interfaccia - setDefaults(); - - displayTaskAndLog(string.Format("Caricata conf per adapter {0}", tipoScelto)); - } - - private void mLoadConf_Click(object sender, EventArgs e) - { - // mostro selettore file x leggere adapter.. - OpenFileDialog openFileDial = new OpenFileDialog(); - - // directory iniziale - openFileDial.InitialDirectory = utils.confDir; // string.Format(@"{0}\{1}", Application.StartupPath, utils.CRS("dataConfPath")); - // Set filter options and filter index. - openFileDial.Filter = "INI Files (.ini)|*.ini|All Files (*.*)|*.*"; - openFileDial.FilterIndex = 1; - // altre opzioni - openFileDial.Multiselect = false; - - // Call the ShowDialog method to show the dialog box. - DialogResult userClickedOK = openFileDial.ShowDialog(); - - // Process input if the user clicked OK. - if (userClickedOK == DialogResult.OK) - { - string iniConfFile = openFileDial.FileName; - loadIniFile(iniConfFile); - lgInfo("INI LOADED"); - } - } - - /// - /// Button restart - /// - /// - /// - private void restart_Click(object sender, EventArgs e) - { - string message = "Attenzione: con l'operazione di reset veranno persi (e non inviati) i dati eventualmente accumulati (indipendentemente dalla selezione del checkbox 'svuota coda')."; - string caption = "Conferma Reset Dati IOB"; - MessageBoxButtons buttons = MessageBoxButtons.YesNo; - DialogResult result; - - // verifica con messagebox - result = MessageBox.Show(message, caption, buttons); - // solo se ho conferma da utente - if (result == DialogResult.Yes) - { - // faccio stop... SENZA inviare - fermaAdapter(false, false, true); - displayTaskAndLog("RESTARTING: Adapter Stopped"); - // rileggo INI - loadIniFile(defConfFilePath); - displayTaskAndLog("RESTARTING: Ini File Reloaded"); - // faccio start... CON RESET delel code - avviaAdapter(true); - displayTaskAndLog("RESTARTING: Adapter Started"); - // resetto i data monitor... - dataMonitor_0 = ""; - dataMonitor_1 = ""; - dataMonitor_2 = ""; - dataMonitor_3 = ""; - } - } - - /// - /// impostazione valori defaults - /// - private void setDefaults() - { - stop.Enabled = false; - - evQueueLen = 0; - flQueueLen = 0; - nLine2show = utils.CRI("numRowConsole"); - } - - private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) - { - } - - /// - /// Avvio dell'adapter - /// - /// - /// - private void start_Click(object sender, EventArgs e) - { - avviaAdapter(chkForceDequeue.Checked); - // salvo che ho avviato adapter - lgInfo("Completato LOAD Adapter"); - } - - /// - /// fermata dell'adapter - /// - /// - /// - private void stop_Click(object sender, EventArgs e) - { - fermaAdapter(false, chkForceDequeue.Checked, true); - // salvo che ho fermato adapter - lgInfo("UNLOAD Adapter"); - } - - private void TabData_Selected(object sender, TabControlEventArgs e) - { - } - - private void toggleEditMes2Plc() - { - // abilita i campi --> PLC per editing - enableEditMes2Plc = !enableEditMes2Plc; - checkEditMes2Plc(); - } - - /// - /// MOstra info su coda complessiva - /// - protected void showQueueData() - { - lblQueueLenTop.Text = totQueue == 0 ? "realtime" : $"ev: {qEvLen} | flog: {qFlLen} | tot: {totQueue}"; - } - - /// - /// Decodifica colore da valore semaforico - /// - /// - /// - public static Color decSemaforo(Semaforo valore) - { - Color colore = Color.LightGray; - switch (valore) - { - case Semaforo.SV: - colore = Color.LightGreen; - break; - - case Semaforo.SG: - colore = Color.LightGoldenrodYellow; - break; - - case Semaforo.SR: - colore = Color.Red; - break; - - case Semaforo.SS: - colore = Color.DarkGray; - break; - - default: - colore = Color.LightGray; - break; - } - return colore; - } - - /// - /// Avvio l'adapter - /// - /// indica se sia richeisto di SVUOTARE le code delel info - public void avviaAdapter(bool resetQueue) - { - displayTaskAndLog("Adapter starting"); - // se NON sta girando... - if (!iobObj.adpRunning) - { - iobObj.startAdapter(resetQueue); - displayTaskAndLog("Adapter started!"); - - // fix buttons start/stop/dump - start.Enabled = false; - stop.Enabled = true; - restart.Enabled = true; - - displayTaskAndLog("Start Timers"); - // inizializzo contatori fast/mid/slow - fastCount = utils.CRI("fastCount"); - normCount = utils.CRI("normCount"); - slowCount = utils.CRI("slowCount"); - verySlowCount = utils.CRI("verySlowCount"); - displayTaskAndLog("Adapter Running..."); - // init max queue - maxEvQueue = 1; - maxFlQueue = 1; - - try + private void ChkEdit_CheckedChanged(object sender, EventArgs e) { - // segnalo reboot (programma)... - iobObj.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB Started")); + toggleEditMes2Plc(); } - catch (Exception exc) - { - lgError(string.Format("EXCEPTION in fase di chiamata URL di segnalazione AVVIO IOB:{0}{1}", Environment.NewLine, exc)); - } - } - else - { - displayTaskAndLog("Adapter STILL Running..."); - } - } - /// - /// Ferma l'adapter - /// - /// determina se si debba tentare riavvio automatico (per caduta connessione) - /// indica se sia richeisto di SVUOTARE le code delel info - /// indica se aggiornare la form prima di fermare - public void fermaAdapter(bool tryRestart, bool forceDequeue, bool updateForm) - { - fermaTutto(false, tryRestart, forceDequeue, updateForm); + private void displTimer_Tick(object sender, EventArgs e) + { + } + + private void fixComboParameters() + { + if (iobObj != null) + { + if (iobObj.memMap != null) + { + if (iobObj.memMap.mMapWrite != null) + { + if (iobObj.memMap.mMapWrite.Count > 0) + { + List parametri = new List(); + foreach (var item in iobObj.memMap.mMapWrite) + { + parametri.Add(item.Key); + } + cmbParamValues.DataSource = parametri; + } + } + } + } + } + + /// + /// GEstione evento refresh + /// + /// + /// + private void IobObj_eh_refreshed(object sender, iobRefreshedEventArgs e) + { + // aggiorno! + updateFormDisplay(e.DisplayDataObject); + } + + /// + /// carica IOB richiesto + /// + private void loadIobType() + { + switch (tipoScelto) + { + case tipoAdapter.SIMULA: + iobObj = new IobSimula(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.FILE_GEN: + iobObj = new IobFile(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.FILE_EUROM63: + iobObj = new IobFileEurom63(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.FANUC: + iobObj = new IobFanuc(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.KAWASAKI: + iobObj = new IobKawasaki(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.MTConnect: + iobObj = new IobMTC(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.OMRON: + iobObj = new IobOmron(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.OSAI_OPEN: + case tipoAdapter.OSAI_CNDEX: + case tipoAdapter.OSAI_VB6: + // versione CVCncLib + iobObj = new IobOSAI(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS: + iobObj = new IobSiemens(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_APROCHIM: + iobObj = new IobSiemensAprochim(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_AT2001: + iobObj = new IobSiemensAt2001(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_COMUR: + iobObj = new IobSiemensComur(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_FAPE: + iobObj = new IobSiemensFape(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_INGENIA: + iobObj = new IobSiemensIngenia(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_LASCO: + iobObj = new IobSiemensLasco(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_PRESSOIL_CEI: + iobObj = new IobSiemensPressoilCei(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_SAET: + iobObj = new IobSiemensSaet(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_SIMEC: + iobObj = new IobSiemensSimec(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.SIEMENS_TORRI: + iobObj = new IobSiemensTorri(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.WPS: + iobObj = new IobWPS(this, IOBConf); + start.Enabled = true; + break; + + case tipoAdapter.ND: + default: + iobObj = new IobSimula(this, IOBConf); + start.Enabled = false; + break; + } + lblCNC.Text = $"CNC: {IOBConf.tipoIob} [{IOBConf.cncIpAddr}:{IOBConf.cncPort}]"; + lblSrvUrl.Text = $"SRV: {IOBConf.serverData.MPIP} | URL: {IOBConf.serverData.MPURL}{IOBConf.serverData.CMDBASE}"; + + // aggancio evento refresh + iobObj.eh_refreshed += IobObj_eh_refreshed; + + // carico i default values su interfaccia + setDefaults(); + + displayTaskAndLog(string.Format("Caricata conf per adapter {0}", tipoScelto)); + } + + private void mLoadConf_Click(object sender, EventArgs e) + { + // mostro selettore file x leggere adapter.. + OpenFileDialog openFileDial = new OpenFileDialog(); + + // directory iniziale + openFileDial.InitialDirectory = utils.confDir; // string.Format(@"{0}\{1}", Application.StartupPath, utils.CRS("dataConfPath")); + // Set filter options and filter index. + openFileDial.Filter = "INI Files (.ini)|*.ini|All Files (*.*)|*.*"; + openFileDial.FilterIndex = 1; + // altre opzioni + openFileDial.Multiselect = false; + + // Call the ShowDialog method to show the dialog box. + DialogResult userClickedOK = openFileDial.ShowDialog(); + + // Process input if the user clicked OK. + if (userClickedOK == DialogResult.OK) + { + string iniConfFile = openFileDial.FileName; + loadIniFile(iniConfFile); + lgInfo("INI LOADED"); + } + } + + /// + /// Button restart + /// + /// + /// + private void restart_Click(object sender, EventArgs e) + { + string message = "Attenzione: con l'operazione di reset veranno persi (e non inviati) i dati eventualmente accumulati (indipendentemente dalla selezione del checkbox 'svuota coda')."; + string caption = "Conferma Reset Dati IOB"; + MessageBoxButtons buttons = MessageBoxButtons.YesNo; + DialogResult result; + + // verifica con messagebox + result = MessageBox.Show(message, caption, buttons); + // solo se ho conferma da utente + if (result == DialogResult.Yes) + { + // faccio stop... SENZA inviare + fermaAdapter(false, false, true); + displayTaskAndLog("RESTARTING: Adapter Stopped"); + // rileggo INI + loadIniFile(defConfFilePath); + displayTaskAndLog("RESTARTING: Ini File Reloaded"); + // faccio start... CON RESET delel code + avviaAdapter(true); + displayTaskAndLog("RESTARTING: Adapter Started"); + // resetto i data monitor... + dataMonitor_0 = ""; + dataMonitor_1 = ""; + dataMonitor_2 = ""; + dataMonitor_3 = ""; + } + } + + /// + /// impostazione valori defaults + /// + private void setDefaults() + { + stop.Enabled = false; + + evQueueLen = 0; + flQueueLen = 0; + nLine2show = utils.CRI("numRowConsole"); + } + + private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) + { + } + + /// + /// Avvio dell'adapter + /// + /// + /// + private void start_Click(object sender, EventArgs e) + { + avviaAdapter(chkForceDequeue.Checked); + // salvo che ho avviato adapter + lgInfo("Completato LOAD Adapter"); + } + + /// + /// fermata dell'adapter + /// + /// + /// + private void stop_Click(object sender, EventArgs e) + { + fermaAdapter(false, chkForceDequeue.Checked, true); + // salvo che ho fermato adapter + lgInfo("UNLOAD Adapter"); + } + + private void TabData_Selected(object sender, TabControlEventArgs e) + { + } + + private void toggleEditMes2Plc() + { + // abilita i campi --> PLC per editing + enableEditMes2Plc = !enableEditMes2Plc; + checkEditMes2Plc(); + } } - } } \ No newline at end of file diff --git a/IOB-WIN/DATA/CONF/EM63.ini b/IOB-WIN/DATA/CONF/EM63.ini new file mode 100644 index 00000000..95c3a566 --- /dev/null +++ b/IOB-WIN/DATA/CONF/EM63.ini @@ -0,0 +1,66 @@ +;Configurazione IOB-WIN +[IOB] +;MAcchina con protocollo Euromap63 PlasticMetal NPM +CNCTYPE=FILE_EUROM63 +PING_MS_TIMEOUT=500 + +[MACHINE] +VENDOR=PlasticMetal +MODEL=MPW280SP + +[CNC] +;IP=192.168.1.55 +IP=10.74.82.253 +;IP=10.82.74.1 + +[SERVER] +MPIP=http://10.74.82.218 +;MPIP=http://192.168.1.150 +MPURL=/MP/IO +CMDBASE=/IOB/input/ +CMDFLOG=/IOB/flog/ +CMDALIVE=/IOB +CMDENABLED=/IOB/enabled/ +CMDADV1=?valore= +CMDREBO=/sendReboot.aspx?idxMacchina= + +[MEMORY] +ADDR_READ=DB0.DBB0 +ADDR_WRITE=DB0.DBB0 +SIZE_READ=1 +SIZE_WRITE=0 +;BIT0=CONN +BIT1=DB0.DBB1 +;BIT2=PZCOUNT.STD.DB700.DBW22 +BIT3=DB0.DBB3 +BIT4=DB0.DBB4 + + +[BLINK] +;MAX_COUNTER_BLINK = 30 +MAX_COUNTER_BLINK = 15 +;bit0 = 0 +;bit1 = 0 +;bit2 = 1 +;bit3 = 1 +;bit4 = 1 +;bit5 = 0 +;bit6 = 0 +;bit7 = 0 +BLINK_FILT=0 +;BLINK_FILT=28 + +[OPTPAR] +;PZCOUNT_MODE=STD.[PAR/MEM].info|BIT.indice +; attenzione memoria sempre base BYTE (1604 DW --> 6416...) +;PZCOUNT_MODE=STD.DB550.DBDW0 +PZCOUNT_MODE=NONE +DISABLE_PZCOUNT=TRUE +ENABLE_DYN_DATA=TRUE +FORCE_DYN_DATA=TRUE +; CONF variabili da recuperare in WebPage (stato macchina, contatori, variabili, ...) +LUT_CONF=EM63.json +timerIntMs=50 + +[BRANCH] +NAME=master diff --git a/IOB-WIN/DATA/CONF/EM63.json b/IOB-WIN/DATA/CONF/EM63.json new file mode 100644 index 00000000..5984ff3f --- /dev/null +++ b/IOB-WIN/DATA/CONF/EM63.json @@ -0,0 +1,185 @@ +{ + "BaseDir": "C:\\NPM_E63\\E63\\MPW280SP", + "cleanupExt": [ + "*.dat", + "*.job", + "*.log", + "*.req", + "*.rsp" + ], + "DynData": [ + { + "key": "CLOCK_1", + "name": "CLOCK_1", + "val": "ct4", + "unit": "DateTime", + "func": "CHANGE", + "sPeriod": 10 + }, + { + "key": "CLOCK_2", + "name": "CLOCK_2", + "val": "ct4", + "unit": "DateTime", + "func": "SAMPLE", + "sPeriod": 10 + } + ], + "ActiveSessions": { + "0": { + "Cycle": false, + "Description": "Check Connection Status", + "Max2Keep": 10, + "RetrySec": 5, + "SessionName": "SESS0000", + "SessionType": "IsConnected", + "StepOrder": 0, + "ValidityMinutes": 0.0, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0000.REQ", + "OprReq": "Copy" + } + ] + }, + "1": { + "Cycle": false, + "Description": "Get ID data", + "Max2Keep": 10, + "SessionName": "SESS0001", + "SessionType": "GetId", + "StepOrder": 1, + "ValidityMinutes": 0.0, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0001.JOB", + "OprReq": "Copy" + }, + { + "Path": "DATA\\EUR63_JOB\\SESS0001.REQ", + "OprReq": "Copy" + } + ] + }, + "2": { + "Cycle": false, + "Description": "Set DateTime on machine at start", + "RetrySec": 10, + "SessionName": "SESS0002", + "SessionType": "SetDateTime", + "ValidityMinutes": 0.0, + "Max2Keep": 10, + "StepOrder": 2, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0002.JOB", + "OprReq": "ReplaceAndCopy" + }, + { + "Path": "DATA\\EUR63_JOB\\SESS0002.REQ", + "OprReq": "Copy" + } + ] + }, + "3": { + "Cycle": false, + "Description": "Abort All prev requests", + "RetrySec": 10, + "SessionName": "SESS0003", + "SessionType": "AbortAll", + "ValidityMinutes": 0.0, + "Max2Keep": 10, + "StepOrder": 3, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0003.JOB", + "OprReq": "Copy" + }, + { + "Path": "DATA\\EUR63_JOB\\SESS0003.REQ", + "OprReq": "Copy" + } + ] + }, + "4": { + "Cycle": true, + "Description": "Get Machine Status", + "RetrySec": 15, + "SessionName": "SESS0004", + "SessionType": "GetStatus", + "ValidityMinutes": 5.0, + "Max2Keep": 120, + "StepOrder": 4, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0004.JOB", + "OprReq": "Copy" + }, + { + "Path": "DATA\\EUR63_JOB\\SESS0004.REQ", + "OprReq": "Copy" + } + ] + }, + "5": { + "Cycle": true, + "Description": "Get Production", + "RetrySec": 15, + "SessionName": "SESS0005", + "SessionType": "GetProduction", + "ValidityMinutes": 5.0, + "Max2Keep": 120, + "StepOrder": 5, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0005.JOB", + "OprReq": "Copy" + }, + { + "Path": "DATA\\EUR63_JOB\\SESS0005.REQ", + "OprReq": "Copy" + } + ] + }, + "10": { + "Cycle": false, + "Description": "Set Param ODL at Setup", + "RetrySec": 5, + "SessionName": "SESS0010", + "SessionType": "SetParamOdl", + "ValidityMinutes": 0.0, + "Max2Keep": 10, + "StepOrder": 10, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0010.JOB", + "OprReq": "ReplaceAndCopy" + }, + { + "Path": "DATA\\EUR63_JOB\\SESS0010.REQ", + "OprReq": "Copy" + } + ] + }, + "19": { + "Cycle": false, + "Description": "Get INFO data", + "Max2Keep": 10, + "RetrySec": 5, + "SessionName": "SESS0019", + "SessionType": "GetInfo", + "StepOrder": 19, + "ValidityMinutes": 0.0, + "FileList": [ + { + "Path": "DATA\\EUR63_JOB\\SESS0019.JOB", + "OprReq": "Copy" + }, + { + "Path": "DATA\\EUR63_JOB\\SESS0019.REQ", + "OprReq": "Copy" + } + ] + } + } +} \ No newline at end of file diff --git a/IOB-WIN/DATA/CONF/SIMUL_01.ini b/IOB-WIN/DATA/CONF/SIMUL_01.ini index ac18284d..c453dab5 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_01.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_01.ini @@ -55,7 +55,7 @@ SIM_WUCD=8000|20 ; indica gestione e simulazione bit 7 --> emergenza SIM_EMRG=4000|10 ; indica simulazione delle funzionalità power ON/ OFF -SIM_POW_ON_OFF=false +SIM_POW_ON_OFF=true T_ON=7 T_OFF=22 ; gestione DynData simulati diff --git a/IOB-WIN/DATA/CONF/SIMUL_02.ini b/IOB-WIN/DATA/CONF/SIMUL_02.ini index 3a312bf5..cb5e4701 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_02.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_02.ini @@ -58,7 +58,7 @@ FORCE_DYN_DATA=TRUE NEW_DYN_DATA=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; indica parametri gestione TcMan diff --git a/IOB-WIN/DATA/CONF/SIMUL_03.ini b/IOB-WIN/DATA/CONF/SIMUL_03.ini index 435eaf4b..1339e2fe 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_03.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_03.ini @@ -58,7 +58,7 @@ FORCE_DYN_DATA=TRUE NEW_DYN_DATA=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; indica parametri gestione TcMan diff --git a/IOB-WIN/DATA/CONF/SIMUL_04.ini b/IOB-WIN/DATA/CONF/SIMUL_04.ini index a442eae2..91d7ff31 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_04.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_04.ini @@ -58,7 +58,7 @@ FORCE_DYN_DATA=TRUE NEW_DYN_DATA=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; indica parametri gestione TcMan diff --git a/IOB-WIN/DATA/CONF/SIMUL_05.ini b/IOB-WIN/DATA/CONF/SIMUL_05.ini index 7d2a4d57..34e0e9f6 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_05.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_05.ini @@ -58,7 +58,7 @@ FORCE_DYN_DATA=TRUE NEW_DYN_DATA=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; indica parametri gestione TcMan diff --git a/IOB-WIN/DATA/CONF/SIMUL_06.ini b/IOB-WIN/DATA/CONF/SIMUL_06.ini index fcb35fdb..65c71337 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_06.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_06.ini @@ -58,7 +58,7 @@ FORCE_DYN_DATA=TRUE NEW_DYN_DATA=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; indica parametri gestione TcMan diff --git a/IOB-WIN/DATA/CONF/SIMUL_07.ini b/IOB-WIN/DATA/CONF/SIMUL_07.ini index 9fa3968a..e49824ef 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_07.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_07.ini @@ -58,7 +58,7 @@ FORCE_DYN_DATA=TRUE NEW_DYN_DATA=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; indica parametri gestione TcMan diff --git a/IOB-WIN/DATA/CONF/SIMUL_08.ini b/IOB-WIN/DATA/CONF/SIMUL_08.ini index 731ac086..63b75bd6 100644 --- a/IOB-WIN/DATA/CONF/SIMUL_08.ini +++ b/IOB-WIN/DATA/CONF/SIMUL_08.ini @@ -58,7 +58,7 @@ FORCE_DYN_DATA=TRUE NEW_DYN_DATA=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; indica parametri gestione TcMan diff --git a/IOB-WIN/DATA/CONF/SIM_DP_01.ini b/IOB-WIN/DATA/CONF/SIM_DP_01.ini index d96026df..20f9f7c4 100644 --- a/IOB-WIN/DATA/CONF/SIM_DP_01.ini +++ b/IOB-WIN/DATA/CONF/SIM_DP_01.ini @@ -41,7 +41,7 @@ PZCOUNT_MODE=BIT ENABLE_PZ_RESET=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; per il simulatore: 50|1 = WAIT 50, DURATION 1 con riferimento al PERIODO base (PER_BASE in ms, default 1 secondo) diff --git a/IOB-WIN/DATA/CONF/SIM_DP_02.ini b/IOB-WIN/DATA/CONF/SIM_DP_02.ini index a1bcf74d..64eae285 100644 --- a/IOB-WIN/DATA/CONF/SIM_DP_02.ini +++ b/IOB-WIN/DATA/CONF/SIM_DP_02.ini @@ -41,7 +41,7 @@ PZCOUNT_MODE=BIT ENABLE_PZ_RESET=TRUE ;gestione invio pezzi in blocco ENABLE_SEND_PZC_BLOCK=TRUE -MIN_SEND_PZC_BLOCK=5 +MIN_SEND_PZC_BLOCK=0 MAX_SEND_PZC_BLOCK=100 MIN_DURATA_ODL=240 ; per il simulatore: 50|1 = WAIT 50, DURATION 1 con riferimento al PERIODO base (PER_BASE in ms, default 1 secondo) diff --git a/IOB-WIN/DATA/EUR63_JOB/.placeholder b/IOB-WIN/DATA/EUR63_JOB/.placeholder new file mode 100644 index 00000000..5f282702 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/.placeholder @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0000.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0000.REQ new file mode 100644 index 00000000..98436c00 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0000.REQ @@ -0,0 +1 @@ +SESSS0000 CONNECT; \ No newline at end of file diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0001.JOB b/IOB-WIN/DATA/EUR63_JOB/SESS0001.JOB new file mode 100644 index 00000000..941c2c29 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0001.JOB @@ -0,0 +1,2 @@ +JOB GETID RESPONSE "SESS0001.LOG"; +GETID "SESS0001.DAT"; \ No newline at end of file diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0001.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0001.REQ new file mode 100644 index 00000000..72ce2e2b --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0001.REQ @@ -0,0 +1 @@ +SESS0001 EXECUTE "SESS0001.JOB"; \ No newline at end of file diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0002.JOB b/IOB-WIN/DATA/EUR63_JOB/SESS0002.JOB new file mode 100644 index 00000000..ac48c1bf --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0002.JOB @@ -0,0 +1,2 @@ +JOB ImpostaOrario RESPONSE "SESS0002.LOG"; +SET SetTimMach {DTNow}; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0002.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0002.REQ new file mode 100644 index 00000000..c647022a --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0002.REQ @@ -0,0 +1 @@ +SESS0002 EXECUTE "SESS0002.JOB"; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0003.JOB b/IOB-WIN/DATA/EUR63_JOB/SESS0003.JOB new file mode 100644 index 00000000..881afaa9 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0003.JOB @@ -0,0 +1,7 @@ +JOB Abort1 RESPONSE "SESS0003.LOG"; + +//ABORT EVENT Event1; +//ABORT ALL REPORTS; +//ABORT JOB Job1Name; +ABORT ALL JOBS; +//ABORT REPORT Report1Name; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0003.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0003.REQ new file mode 100644 index 00000000..f14fbdf4 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0003.REQ @@ -0,0 +1 @@ +SESS0003 EXECUTE "SESS0003.JOB"; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0004.JOB b/IOB-WIN/DATA/EUR63_JOB/SESS0004.JOB new file mode 100644 index 00000000..ca69cf84 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0004.JOB @@ -0,0 +1,11 @@ +JOB machstat RESPONSE "SESS0004.LOG"; + +REPORT status REWRITE "SESS0004.DAT" +START IMMEDIATE +STOP NEVER +CYCLIC TIME 00:00:01 +SESSIONS 60 +PARAMETERS +DATE, TIME, ActStsMach; + + diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0004.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0004.REQ new file mode 100644 index 00000000..d29e9602 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0004.REQ @@ -0,0 +1 @@ +SESS0004 EXECUTE "SESS0004.JOB"; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0005.JOB b/IOB-WIN/DATA/EUR63_JOB/SESS0005.JOB new file mode 100644 index 00000000..f387774a --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0005.JOB @@ -0,0 +1,25 @@ +JOB machstat RESPONSE "SESS0005.LOG"; + +REPORT status REWRITE "SESS0005.DAT" +START IMMEDIATE +STOP NEVER +CYCLIC TIME 00:00:03 +SESSIONS 100 +//PARAMETERS +//DATE, TIME, ActCntCyc, ActTimCyc, ActTimFill, @OutXhour, SetDescJob; +PARAMETERS +DATE, TIME +, ActCntCyc, ActTimCyc, ActTimFill +, @OutXhour +//, SetTmpBrlZnStb[1] +//, SetTmpBrlZn[2], SetTmpBrlZnHdev[2], SetTmpBrlZnLdev[2] +//, ActTmpBrlZn[1], ActTmpBrlZn[2], ActTmpBrlZn[3] +//, SetTmpMldZn[50], SetTmpMldZnStb[50], SetTmpMldZnHdev[50], SetTmpMldZnLdev[50], ActTmpMldZn[50] +//, SetTmpMldZn[51], SetTmpMldZnStb[51], SetTmpMldZnHdev[51], SetTmpMldZnLdev[51], ActTmpMldZn[51] +//, ActTmpCab, ActTmpMlt +//, ActStrCsh, ActStrCsh +//, ActSpdPlstMax, ActSpdPlstAve +, SetDescJob +//, ActCntPrt +//, ActTmpOil +; \ No newline at end of file diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0005.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0005.REQ new file mode 100644 index 00000000..34cd11bc --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0005.REQ @@ -0,0 +1 @@ +SESS0005 EXECUTE "SESS0005.JOB"; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0010.JOB b/IOB-WIN/DATA/EUR63_JOB/SESS0010.JOB new file mode 100644 index 00000000..14278cfa --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0010.JOB @@ -0,0 +1,19 @@ +JOB SetID RESPONSE "SESS0010.LOG"; +//SET SetDescJob " "; +//SET SetDescPrt " " +//SET SetDescMld " "; +//SET SetDescOp " "; + +SET SetDescJob {ODL}; +SET SetDescPrt {DescrArt}; +SET SetDescMld {CodArt}; +SET SetDescOp {CodOpr}; + +//SET SetDescJob "Nr. 1000987654.01"; +//SET SetDescPrt "STICK: 8 componenti SENZA assemblaggio"; +//SET SetDescMld "Stampo componenti a 8 impronte"; +//SET SetDescOp "Operatore 01"; + +//SET SetCntMld 2; +//SET SetCntPrt 10000; +//SET SetCntPrtBox 20; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0010.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0010.REQ new file mode 100644 index 00000000..1a589005 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0010.REQ @@ -0,0 +1 @@ +SESS0010 EXECUTE "SESS0010.JOB"; diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0019.JOB b/IOB-WIN/DATA/EUR63_JOB/SESS0019.JOB new file mode 100644 index 00000000..06249f76 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0019.JOB @@ -0,0 +1,2 @@ +JOB GETINFO RESPONSE "SESS0019.LOG"; +GETINFO "SESS0019.DAT"; \ No newline at end of file diff --git a/IOB-WIN/DATA/EUR63_JOB/SESS0019.REQ b/IOB-WIN/DATA/EUR63_JOB/SESS0019.REQ new file mode 100644 index 00000000..536ba257 --- /dev/null +++ b/IOB-WIN/DATA/EUR63_JOB/SESS0019.REQ @@ -0,0 +1 @@ +SESS0019 EXECUTE "SESS0019.JOB"; \ No newline at end of file diff --git a/IOB-WIN/DATA/HIST/.placeholder b/IOB-WIN/DATA/HIST/.placeholder new file mode 100644 index 00000000..5f282702 --- /dev/null +++ b/IOB-WIN/DATA/HIST/.placeholder @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/IOB-WIN/DATA/TEMP/.placeholder b/IOB-WIN/DATA/TEMP/.placeholder new file mode 100644 index 00000000..5f282702 --- /dev/null +++ b/IOB-WIN/DATA/TEMP/.placeholder @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/IOB-WIN/IOB-WIN.csproj b/IOB-WIN/IOB-WIN.csproj index 668069fb..9f16907d 100644 --- a/IOB-WIN/IOB-WIN.csproj +++ b/IOB-WIN/IOB-WIN.csproj @@ -148,6 +148,7 @@ + @@ -157,6 +158,7 @@ + @@ -481,6 +483,12 @@ Always + + Always + + + Always + Always @@ -496,6 +504,60 @@ Always + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + diff --git a/IOB-WIN/IobFile.cs b/IOB-WIN/IobFile.cs new file mode 100644 index 00000000..c9484db3 --- /dev/null +++ b/IOB-WIN/IobFile.cs @@ -0,0 +1,357 @@ +using IOB_UT; +using MapoSDK; +using Newtonsoft.Json; +using OpenQA.Selenium; +using OpenQA.Selenium.Chrome; +using OpenQA.Selenium.Firefox; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace IOB_WIN +{ + /// + /// Generica classe per implementare IOB basato su scambio FILE + /// + public class IobFile : IobGeneric, IDisposable + { + /* -------------------------------------------------------------------------------- + * Controlli dotati di GENERICA funzionalità scambio info tramite file + * + * -------------------------------------------------------------------------------- */ + + #region Protected Fields + + /// + /// Cartella di base per interscambio + /// + protected string BaseDir = @"C:\Steamware"; + + /// + /// Array di configurazione degli oggetti da cercare x decodifica e recupero info + /// + protected Dictionary dataLocatorLUT; + + /// + /// Vettore della frequenza di ogni status trovato... invio ogni 100 rilevazioni (modulo 100, resto == 1) + /// + protected Dictionary freqUnknStatus = new Dictionary(); + + #endregion Protected Fields + + #region Public Constructors + + /// + /// Estende l'init della classe base... + /// + /// + /// + public IobFile(AdapterForm caller, IobConfiguration IOBConf) : base(caller, IOBConf) + { + lgInfo("INIT IobFile"); + //reloadAdapterConf(); + } + + #endregion Public Constructors + + #region Internal Methods + + /// + /// Pulizia preliminare folder comunicazione + /// + internal virtual void cleanupFolder() + { + // + } + + /// + /// Ricarica conf adapter... + /// + internal virtual void reloadAdapterConf() + { +#if false + // init obj display + newDisplayData currDispData = new newDisplayData(); + lgInfo("BEGIN reloadAdapterConf"); + // inizializzo LUT decodifica + string jsonConf = getOptPar("LUT_CONF"); + if (!string.IsNullOrEmpty(jsonConf)) + { + string jsonFullPath = $"{Application.StartupPath}/DATA/CONF/{jsonConf}"; + lgInfo($"Apertura file {jsonFullPath}"); + StreamReader reader = new StreamReader(jsonFullPath); + string jsonData = reader.ReadToEnd(); + if (!string.IsNullOrEmpty(jsonData)) + { + try + { + monitoredItems = JsonConvert.DeserializeObject(jsonData); + // salvo baseUri + baseDir = monitoredItems.SrvData.baseUri; + lgInfo($"baseUri = {baseDir}"); + // imposto a zero la bitmap x riavvio! + B_input = 0; + // FORZO invio dati... + accodaSigIN(ref currDispData); + // loggo! + lgInfo($"init input bitmap to zero: {B_input}"); + } + catch (Exception exc) + { + lgError(exc, "Eccezione in decodifica conf json"); + } + } + reader.Dispose(); + } + lgInfo("DONE reloadAdapterConf"); + raiseRefresh(currDispData); +#endif + } + + #endregion Internal Methods + + #region Metodi specifici (da verificare/completare in implementazione) + + /// + /// Processo stati unknown... + /// + /// + private void processUnknStatus(string cKey) + { + // cerco se avevo già una key nella dictionary... + if (freqUnknStatus.ContainsKey(cKey)) + { + freqUnknStatus[cKey]++; + // se è 1 ogni 100 (%100, resto ==1) --> loggo... + if (freqUnknStatus[cKey] % 100 == 1) + { + lgInfo($"Errore in decodifica status: MAPPING non trovato per {cKey} | freq: {freqUnknStatus[cKey]}"); + // accodo come invio di tipo FLOG... + string sVal = string.Format("[UnknStatus] {0}, freq: {1}", cKey, freqUnknStatus); + // chiamo accodamento... + accodaFLog(sVal, qEncodeFLog("UnknStatus", sVal)); + } + } + else + { + // creo chiave con freq = 1 + freqUnknStatus.Add(cKey, 1); + // log iniziale + lgInfo($"Errore in decodifica status: MAPPING non trovato per {cKey}"); + } + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + /// + /// Recupero dati dinamici in formato dictionary + /// + /// + public override Dictionary getDynData() + { + lgInfo("Chiamata getDynData x IOB FILE!"); + Dictionary outVal = new Dictionary(); +#if false + try + { + /* ---------------------------------------------------------- + * Recupero dalla TUTTE le chiavi richieste... + * */ + + string cKey = ""; + string cVal = ""; + // processo tutti i DynData... + foreach (var item in monitoredItems.DynData) + { + // cerco elemento indicato + element = driver.FindElement(By.Id(item.val)); + cVal = element.Text; + // verifico nome o key... + if (!string.IsNullOrEmpty(item.name)) + { + cKey = item.name; + } + else + { + element = driver.FindElement(By.Id(item.key)); + cKey = element.Text; + } + // controllo se devo inviare (per tipo di dato, x scadenza) + if (monItem2Send(cVal, item)) + { + item.actVal = cVal; + item.DTScad = DateTime.Now.AddSeconds(item.sPeriod); + // accodo! + outVal.Add(cKey, cVal); + } + } + } + catch (Exception exc) + { + lgError(exc, "Errore in getDynData x IOB FILE"); + } +#endif + return outVal; + } + + /// + /// Effettua processing del recupero delle OVERRIDE (spindle, feedrate, rapid) + /// + public override void processOverride() + { + } + + /// + /// Effettua lettura semafori principale + /// Parametri da aggiornare x display in form + /// + public override void readSemafori(ref newDisplayData currDispData) + { + // init a zero... + B_input = 0; + // 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); + } + catch (Exception exc) + { + lgError(exc, "Errore in readSemafori x IOB FILE"); + if (currDispData != null) + currDispData.semIn = Semaforo.SR; + } + } + + public override void startAdapter(bool resetQueue) + { + // in primis RICARICO conf specifica... + reloadAdapterConf(); + // pulizia preliminare folder + cleanupFolder(); + // continuo con start... + base.startAdapter(resetQueue); + } + + /// + /// Override x chiusura driver... + /// + /// + /// + public override void stopAdapter(bool tryRestart, bool forceDequeue) + { + try + { +#if false + // in primis chiudo driver... + if (driver != null) + { + driver.Quit(); + } +#endif + } + catch (Exception exc) + { + lgError(exc, "Eccezione in tryDisconnect"); + } + // continuo + base.stopAdapter(tryRestart, forceDequeue); + } + + /// + /// Connessione + /// + public override void tryConnect() + { + // controllo ping --> segno connected... + connectionOk = Directory.Exists(BaseDir); + if (connectionOk) + { +#if false + try + { + // modalità sincrona + startDriver(); + lgInfo("Completato start driver"); + } + catch (Exception exc) + { + lgError(exc, "Eccezione in tryConnect"); + } +#endif + } + else + { + // aspetto prima di riprovare... + Thread.Sleep(200); + } + } + + /// + /// Disconnessione + /// + public override void tryDisconnect() + { + connectionOk = false; + try + { +#if false + // in primis chiudo driver... + if (driver != null) + //if (driver != null && driver.WindowHandles.Count > 0) + { + driver.Quit(); + } +#endif + } + catch (Exception exc) + { + lgError(exc, "Eccezione in tryDisconnect"); + } + } + + #endregion Metodi specifici (da verificare/completare in implementazione) + } +} \ No newline at end of file diff --git a/IOB-WIN/IobFileEurom63.cs b/IOB-WIN/IobFileEurom63.cs new file mode 100644 index 00000000..eaf6fff6 --- /dev/null +++ b/IOB-WIN/IobFileEurom63.cs @@ -0,0 +1,648 @@ +using CncLib.OPENcontrol; +using IOB_UT; +using MapoSDK; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Windows.Forms; + +namespace IOB_WIN +{ + public class IobFileEurom63 : IobFile + { + #region Protected Fields + + /// + /// step di comunicazione attivo + /// + protected Eurom63.ComLevel actLevel = Eurom63.ComLevel.None; + + /// + /// DIrectory eseguibile corrente + /// + protected string appPath = Directory.GetCurrentDirectory(); + + /// + /// Oggetti decodificati da pagina + /// + protected Eurom63.ProtoConf confE63; + + #endregion Protected Fields + + #region Public Constructors + + /// + /// Estende l'init della classe base... + /// + /// + /// + public IobFileEurom63(AdapterForm caller, IobConfiguration IOBConf) : base(caller, IOBConf) + { + lgInfo("INIT IobFileEurom63"); + } + + #endregion Public Constructors + + #region Private Methods + + /// + /// Se la sessione fosse scaduta o non attiva --> torna al livello indicato + /// + /// + private void checkSessionActive(Eurom63.Session currSession, Eurom63.ComLevel nextLevel) + { + // SOLO SE ha senso che controllo (sono in sampling...) + if (actLevel > Eurom63.ComLevel.ChannelOk) + { + // devono essere ATTIVE le sessioni di campionamento... + if (!currSession.Active) + { + DateTime adesso = DateTime.Now; + // devono NON essere scadute... + if (currSession.SessionValidUntil < adesso) + { + // elimino TUTTE le risposte... + cleanupResp(); + cleanupFolder(); + // imposto livello... + actLevel = Eurom63.ComLevel.ChannelOk; + // richiedo abortall... + abortPrevJob(); + } + } + } + } + + #endregion Private Methods + + #region Protected Methods + + protected void abortPrevJob() + { + var nextLevel = Eurom63.ComLevel.ChannelOk; + var connectSession = confE63.ActiveSessions[3]; + processSession(nextLevel, connectSession); + } + + /// + /// Verifica una sessione configurata (ovvero la comunicazione su TUTTI i file associati) + /// + /// + /// + protected bool checkResp(Eurom63.Session session) + { + bool answ = false; + string fileName = ""; + if (session != null) + { + fileName = $"{BaseDir}\\{session.SessionName}.RSP"; + if (File.Exists(fileName)) + { + // verifico contenuto + string rawData = File.ReadAllText(fileName); + answ = rawData.Contains(session.RespOk); + if (!answ) + { + // se NON ok faccio pulizia... + cleanupSession(session); + } + } + } + return answ; + } + + /// + /// verifica periodica dei campionamenti: + /// - i due jobs devono essere attivi e non scaduti + /// - non devo aver già resettato... + /// + protected void checkSampling() + { + var currSession = confE63.ActiveSessions[4]; + checkSessionActive(currSession, Eurom63.ComLevel.ChannelOk); + + currSession = confE63.ActiveSessions[5]; + checkSessionActive(currSession, Eurom63.ComLevel.ChannelOk); + } + + /// + /// Elimina i file della sessione indicata (SE è un task ciclico --> solo RSP) + /// + /// + /// + protected bool cleanupSession(Eurom63.Session session) + { + bool answ = false; + if (session != null) + { + // solo se scaduta validità... + if (session.SessionValidUntil < DateTime.Now) + { + string searchPattern = $"{session.SessionName}.*"; + // task ciclico? + if (session.Cycle) + { + // solo risposta! + searchPattern = $"{session.SessionName}.RSP"; + } + string[] file2del = Directory.GetFiles(BaseDir, searchPattern); + foreach (var file in file2del) + { + File.Delete(file); + } + } + } + return answ; + } + + /// + /// Processa una sessione + /// - andando a verificare l'esistenza della REQ + se esito positivo pulizia + /// - andando a richeidere di nuovo risposta + /// + /// + /// + protected void processSession(Eurom63.ComLevel nextLevel, Eurom63.Session connectSession) + { + if (connectSession != null) + { + // controllo esistenza directory --> segno connected... + connectionOk = Directory.Exists(BaseDir); + if (connectionOk) + { + // verifico se ci sia risp CONNECT + if (checkResp(connectSession)) + { + // aggiorno livello + actLevel = nextLevel; + // elimino file sessione + cleanupSession(connectSession); + connectSession.Active = false; + connectSession.Passed = true; + } + // richiedo SE non ci fosse i dati CONNECT... + else + { + DateTime adesso = DateTime.Now; + // evito di richiedere SE non fosse già scaduta richiesta... + if (adesso > connectSession.RetryVeto) + { + processSessionFile(connectSession); + connectSession.Active = true; + connectSession.Passed = false; + connectSession.SessionStarted = adesso; + connectSession.SessionValidUntil = adesso.AddMinutes(connectSession.ValidityMinutes); + connectSession.RetryVeto = adesso.AddSeconds(connectSession.RetrySec); + } + } + } + else + { + // aspetto prima di riprovare... + Thread.Sleep(50); + } + } + else + { + // aspetto prima di riprovare... + Thread.Sleep(50); + } + } + + /// + /// Processa i file della sessione indicata (copy + transform) + /// + /// + /// + protected bool processSessionFile(Eurom63.Session session) + { + bool answ = false; + if (session != null) + { + string fileFrom = ""; + string fileTo = ""; + // processo OGNI file sessione x farne copia + foreach (var file2Proc in session.FileList) + { + fileFrom = $"{appPath}\\{file2Proc.Path}"; + fileTo = $"{BaseDir}\\{Path.GetFileName(file2Proc.Path)}"; + if (file2Proc.OprReq == Eurom63.FileOpr.Copy) + { + File.Copy(fileFrom, fileTo, true); + } + else + { + // leggo file originale... + string rawData = File.ReadAllText(fileFrom); + // processo sostituzioni + rawData = rawData.Replace("{DTNow}", DateTime.Now.ToString("HHmmssyyyyMMdd")); + // ora in posizione definitiva + File.WriteAllText(fileTo, rawData); + } + } + } + return answ; + } + + /// + /// Effettua richiesta info x macchina (validare startup process) + /// + protected void requestInfo() + { + var nextLevel = Eurom63.ComLevel.HasInfo; + var connectSession = confE63.ActiveSessions[1]; + processSession(nextLevel, connectSession); + } + + protected void requestProdData() + { + var nextLevel = Eurom63.ComLevel.ProdRequested; + var connectSession = confE63.ActiveSessions[5]; + processSession(nextLevel, connectSession); + } + + protected void requestStatusData() + { + var nextLevel = Eurom63.ComLevel.StatusRequested; + var connectSession = confE63.ActiveSessions[4]; + processSession(nextLevel, connectSession); + } + + protected void setMachineTime() + { + var nextLevel = Eurom63.ComLevel.TimeSet; + var connectSession = confE63.ActiveSessions[2]; + processSession(nextLevel, connectSession); + } + + #endregion Protected Methods + + #region Internal Methods + + /// + /// Metodi preliminari x comunicazione: + /// - richiesta connessione + /// - richiesta stato attivo + /// + internal void checkCommStatus() + { + // init obj display + newDisplayData currDispData = new newDisplayData(); + + switch (actLevel) + { + case Eurom63.ComLevel.None: + tryConnect(); + break; + + case Eurom63.ComLevel.IsConnected: + requestInfo(); + break; + + case Eurom63.ComLevel.HasInfo: + setMachineTime(); + break; + + case Eurom63.ComLevel.TimeSet: + abortPrevJob(); + break; + + case Eurom63.ComLevel.ChannelOk: + requestStatusData(); + break; + + case Eurom63.ComLevel.StatusRequested: + requestProdData(); + break; + + case Eurom63.ComLevel.ProdRequested: + checkSampling(); + break; + + default: + break; + } + + lgInfo("DONE checkCommStatus"); + raiseRefresh(currDispData); + } + + /// + /// Pulizia preliminare folder comunicazione + /// + internal override void cleanupFolder() + { + // elimino OGNI file per tipo configurato + foreach (var cleanExt in confE63.cleanupExt) + { + string[] file2del = Directory.GetFiles(BaseDir, cleanExt); + foreach (var file in file2del) + { + File.Delete(file); + } + } + } + + /// + /// Pulizia folder da tutti i file RSP + /// + internal void cleanupResp() + { + string[] file2del = Directory.GetFiles(BaseDir, "*.RSP"); + foreach (var file in file2del) + { + File.Delete(file); + } + } + + /// + /// Ricarica conf adapter... + /// + internal override void reloadAdapterConf() + { + // init obj display + newDisplayData currDispData = new newDisplayData(); + lgInfo("BEGIN reloadAdapterConf"); + // inizializzo LUT decodifica + string jsonConf = getOptPar("LUT_CONF"); + if (!string.IsNullOrEmpty(jsonConf)) + { + string jsonFullPath = $"{Application.StartupPath}/DATA/CONF/{jsonConf}"; + lgInfo($"Apertura file {jsonFullPath}"); + StreamReader reader = new StreamReader(jsonFullPath); + string jsonData = reader.ReadToEnd(); + if (!string.IsNullOrEmpty(jsonData)) + { + try + { + confE63 = JsonConvert.DeserializeObject(jsonData); + + // salvo baseUri + BaseDir = confE63.BaseDir; + lgInfo($"baseDir = {BaseDir}"); + // imposto a zero la bitmap x riavvio! + B_input = 0; + // FORZO invio dati... + accodaSigIN(ref currDispData); + // loggo! + lgInfo($"init input bitmap to zero: {B_input}"); + } + catch (Exception exc) + { + lgError(exc, "Eccezione in decodifica conf json"); + } + } + reader.Dispose(); + } + lgInfo("DONE reloadAdapterConf"); + raiseRefresh(currDispData); + } + + #endregion Internal Methods + + #region Public Methods + + /// + /// Effettua vero processing contapezzi + /// + public override void processContapezzi() + { + if (utils.CRB("enableContapezzi")) + { + // controllo se sono in sampling della produzione + if (actLevel > Eurom63.ComLevel.ProdRequested) + { + /************************************************************ + * + * EXAMPLE + * DATE, TIME, ActCntCyc, ActTimCyc, ActTimFill, @OutXhour, SetDescJob + * 20201007, 21:29:52, 5302, 8.61, 0.50, 10058, Nr. 1000987654.01 + * + * devo prendere il 3° valore + * + * + ************************************************************/ + + // leggo il file della produzione HARD CODED... + var sessProd = confE63.ActiveSessions[5]; + string currPzCount = ""; + if (sessProd != null) + { + if (sessProd.Active) + { + // nome file... + string fileName = $"{BaseDir}\\{sessProd.SessionName}.DAT"; + if (File.Exists(fileName)) + { + // leggo il file... + string[] rawLines = File.ReadAllLines(fileName); + // devo avere almeno 2 righe... + if (rawLines.Length >= 2) + { + string[] statusData = rawLines[2].Split(','); + currPzCount = statusData[2].Trim(); + // salvo se valido + if (!string.IsNullOrEmpty(currPzCount)) + { + int newVal = -1; + Int32.TryParse(currPzCount, out newVal); + contapezziPLC = newVal > -1 ? newVal : contapezziPLC; + } + } + } + } + } + } + } + } + + /// + /// Effettua lettura semafori principale + /// Parametri da aggiornare x display in form + /// + public override void readSemafori(ref newDisplayData currDispData) + { + // in primis controllo status... + checkCommStatus(); + + // init a zero... + B_input = 0; + + // se sono OLTRE i primi 2 step --> accesa... + if (actLevel > Eurom63.ComLevel.None) + { + B_input += (1 << 0); + } + + // ciclo! + try + { + // controllo di essere in sampling... + if (actLevel > Eurom63.ComLevel.ChannelOk) + { + // controllo se sono in sampling dello stato + if (actLevel > Eurom63.ComLevel.StatusRequested) + { + /* ----------------------------------------------------- + * bitmap MAPO + * B0: POWER_ON + * B1: RUN + * B2: pzCount + * B3: allarme + * B4: manuale + * B5: allarme TCiclo (SLOW) + ----------------------------------------------------- */ + + /****************************************************************** + * + * EXAMPLE file content + * DATE, TIME, ActStsMach + * 20201007, 21:28:10, 0A000 + * + * Configurazione array status: 5 char status decoding + * + * Pos1: (status) + * 0: poweron + * 1: poweroff + * + * Pos2: (mode) + * A: AUTO + * S: SEMI auto + * M: Manual + * U: Setup + * H: Hord + * C: Maintenance + * 0: Unknown + * I: Idle + * + * Pos3: (assist call) + * 0: No assistance + * 2: Assistance required + * + * Pos4: (Bad part) + * 0: last cycle not bad + * 1: last cycle bad + * + * Pos5: Active Alarm + * 0: No alarm + * 1: Alarm + * + * + * + *******************************************************************/ + + // leggo il file dela produzione HARD CODED... + var sessStatus = confE63.ActiveSessions[4]; + string currStatus = "00000"; + if (sessStatus != null) + { + if (sessStatus.Active) + { + // nome file... + string fileName = $"{BaseDir}\\{sessStatus.SessionName}.DAT"; + if (File.Exists(fileName)) + { + // leggo il file... + string[] rawLines = File.ReadAllLines(fileName); + // devo avere almeno 2 righe... + if (rawLines.Length >= 2) + { + string[] statusData = rawLines[2].Split(','); + currStatus = statusData[2].Trim(); + if (!string.IsNullOrEmpty(currStatus)) + { + currDispData.semIn = Semaforo.SV; + } + } + } + } + } + // processo il currentStatus... parto da poweron + B_input = currStatus[0] == '1' ? 0 : 1; + // ora MODE + switch (currStatus[1]) + { + case 'A': + B_input += (1 << 1); + break; + + case 'S': + case 'M': + case 'U': + B_input += (1 << 4); + break; + + default: + break; + } + // ora cerco allarmi + if (currStatus[5] == '1') + { + B_input += (1 << 3); + } + } + } + + // riporto bitmap... + reportRawInput(ref currDispData); + } + catch (Exception exc) + { + lgError(exc, "Errore in readSemafori x IOB FILE"); + if (currDispData != null) + currDispData.semIn = Semaforo.SR; + } + } + + /// + /// Effettua reset del contapezzi, NON PERMESSO per EM63 (read only) + /// + /// + public override bool resetcontapezziPLC() + { + bool answ = false; + return answ; + } + + /// + /// Effettua IMPOSTAZIONE FORZATA del contapezzi, NON PERMESSO per EM63 (read only) + /// + /// + public override bool setcontapezziPLC(int newPzCount) + { + bool answ = false; + return answ; + } + + /// + /// Connessione + /// + public override void tryConnect() + { + var nextLevel = Eurom63.ComLevel.IsConnected; + var connectSession = confE63.ActiveSessions[0]; + processSession(nextLevel, connectSession); + } + + /// + /// Disconnessione + /// + public override void tryDisconnect() + { + connectionOk = false; + try + { + cleanupFolder(); + } + catch (Exception exc) + { + lgError(exc, "Eccezione in tryDisconnect"); + } + } + + #endregion Public Methods + } +} \ No newline at end of file diff --git a/IOB-WIN/IobSimula.cs b/IOB-WIN/IobSimula.cs index bfe267f2..9872f1f7 100644 --- a/IOB-WIN/IobSimula.cs +++ b/IOB-WIN/IobSimula.cs @@ -366,6 +366,8 @@ namespace IOB_WIN { B_input = 0; } + // aggiungo NON emergenza... + B_input += (1 << 7); } } // in primis verifico SE posso inviare in blocco i pezzi...... SE MP online e SE NON E' MULTI diff --git a/IOB-WIN/Resources/ChangeLog.html b/IOB-WIN/Resources/ChangeLog.html index 6c31df9b..7ab91d78 100644 --- a/IOB-WIN/Resources/ChangeLog.html +++ b/IOB-WIN/Resources/ChangeLog.html @@ -1,113 +1,120 @@ -

MAPO-IOB-WIN

- v: {{CURRENT-REL}} -
- Acquisitore MAPO-IOB per sistemi Windows -
- Note di rilascio: -
    -
  • - v.2.6.* → v.3.0.* -
      -
    • revisione sistema metodi invio in blocco
    • -
    • Gestione invio contapezzi in step > 1
    • -
    • Gestione eventi in blocco (indipendente e prioritario su EvBlock)
    • -
    • Gestione limite eventi memorizzabili
    • -
    • Integrazione REDIS
    • -
    • Integrazione IOB-MAN
    • -
    -
  • -
  • - v.2.5.* → v.2.6.* -
      -
    • revisione sistema timeout Ping
    • -
    • Gestione AutoODL in prod generale (non solo SIM)
    • -
    -
  • -
  • - v.2.4.* → v.2.5.* -
      -
    • Aggiunto adapter MTConnect
    • -
    • Ottimizzazione gestione SIEMENS
    • -
    -
  • -
  • - v.2.3.* → v.2.4.* -
      -
    • inserita gestione conf json x Flog acquisiti
    • -
    • gestione invio Json blocchi dati FLog
    • -
    • ottimizzazioni varie adapter Siemens
    • -
    • ottimizzazione processo svuotamento code
    • -
    • riduzione interferenza e interblocchi in fase di PLC assente
    • -
    -
  • -
  • - Ultime modifiche: -
      {{LAST-CHANGES}}
    -
  • -
  • - v.1.18.* → v.2.3.* -
      -
    • inserimento WPS x acontrolli WebPage human readable
    • -
    • fix gestione task2exe
    • -
    • aggiunte varie versioni PLC siemens
    • -
    • aggiunto PLC WPS x generiche web pages
    • -
    • revisitazione LOG ODL e contapezzi
    • -
    • modifica pagina presentazione dati (master) x resize
    • -
    • Attivazione IOB SIMULATOR per test di carico (sostituito type DEMO)
    • -
    • Aggiunto simulatore macchine MULTI pallet
    • -
    • Ottimizzazione simulatore
    • -
    • Ottimizzazioni PLC Siemens x riavvio post disconnessione (es spegnimento notturno)
    • -
    • Ottimizzazione processo chiusura in update applicazione
    • -
    • Aggiunta simulazione spegnimento con WU/CD
    • -
    -
  • -
  • - v.1.11.* → v.1.18.* -
      -
    • Inserimento controller SIEMENS con S7+ library
    • -
    • Inserimento nuove letture FANUC x programmi
    • -
    • Inserimento nuove letture FANUC x SysEx (informazioni sistema)
    • -
    • Inserimento invio FluxLog x parametri estesi (es SysEx, ProgName,...)
    • -
    • FIX visualizzazione dati FluxLog e URL inviati
    • -
    • FIX MAIN program da FANUC (non il current)
    • -
    • Inserita modalita' DUMP memoria (iniziale full + periodica)
    • -
    • Inserimento gestione contapezzi standard/checkBit in IOB.cfg
    • -
    • Inserimento contapezzi da area memoria X
    • -
    • NUOVA Gestione rami cliente e URL di update
    • -
    • Gestione modi CNC
    • -
    • Lettura dari dinamycs FANUC (feed, speed)
    • -
    • aggiunta gestione aree G0..G30 (overrides?)
    • -
    • fix errore disconnessione FANUC (allo spegnimento dl CNC) e memoria valori persistente a 1
    • -
    • fix globali x gestione log IN / FLOG + ottimizzaizone check FANUC (PING)
    • -
    • ottimizzazione fasi di restart in caso di assenza del server (evita reinvii inutili e migliora tempo ripartenza invio)
    • -
    • review procedure controllo connessione x FANUC (es Tornos II)
    • -
    • non richeide più privilegi admin x fare update
    • -
    • gestione segnali inverted
    • -
    • completata gestione configurabilità parametrica segnali (Tornos, CMZ, Biglia)
    • -
    • revisitazione LOG x distinguere processi IOB
    • -
    -
  • -
  • - v.0.1.* → v.0.10.* -
      -
    • Testato in produzione x update ad avvio e su richiesta
    • -
    • Testato in produzione x lettura dati da Fanuc
    • -
    • Inizio deploy con copia file su area IIS
    • -
    • Prima versione con autoupdate
    • -
    • Test PrettyBin x spostamento dll
    • -
    • Base acquisitore FANUC
    • -
    • Sistema base sw controllo in tray
    • -
    -
  • -
-
-
- +

MAPO-IOB-WIN

+ v: {{CURRENT-REL}} +
+ Acquisitore MAPO-IOB per sistemi Windows +
+ Note di rilascio: +
    +
  • + v.3.1.* → v.3.2.* +
      +
    • Nuovi simulatori con gestione emergenza
    • +
    • Fix gestione invio dati Redis
    • +
    • Implementazione IOB Eurom63
    • +
    +
  • +
  • + v.2.6.* → v.3.0.* +
      +
    • revisione sistema metodi invio in blocco
    • +
    • Gestione invio contapezzi in step > 1
    • +
    • Gestione eventi in blocco (indipendente e prioritario su EvBlock)
    • +
    • Gestione limite eventi memorizzabili
    • +
    • Integrazione REDIS
    • +
    • Integrazione IOB-MAN
    • +
    +
  • +
  • + v.2.5.* → v.2.6.* +
      +
    • revisione sistema timeout Ping
    • +
    • Gestione AutoODL in prod generale (non solo SIM)
    • +
    +
  • +
  • + v.2.4.* → v.2.5.* +
      +
    • Aggiunto adapter MTConnect
    • +
    • Ottimizzazione gestione SIEMENS
    • +
    +
  • +
  • + v.2.3.* → v.2.4.* +
      +
    • inserita gestione conf json x Flog acquisiti
    • +
    • gestione invio Json blocchi dati FLog
    • +
    • ottimizzazioni varie adapter Siemens
    • +
    • ottimizzazione processo svuotamento code
    • +
    • riduzione interferenza e interblocchi in fase di PLC assente
    • +
    +
  • +
  • + Ultime modifiche: +
      {{LAST-CHANGES}}
    +
  • +
  • + v.1.18.* → v.2.3.* +
      +
    • inserimento WPS x acontrolli WebPage human readable
    • +
    • fix gestione task2exe
    • +
    • aggiunte varie versioni PLC siemens
    • +
    • aggiunto PLC WPS x generiche web pages
    • +
    • revisitazione LOG ODL e contapezzi
    • +
    • modifica pagina presentazione dati (master) x resize
    • +
    • Attivazione IOB SIMULATOR per test di carico (sostituito type DEMO)
    • +
    • Aggiunto simulatore macchine MULTI pallet
    • +
    • Ottimizzazione simulatore
    • +
    • Ottimizzazioni PLC Siemens x riavvio post disconnessione (es spegnimento notturno)
    • +
    • Ottimizzazione processo chiusura in update applicazione
    • +
    • Aggiunta simulazione spegnimento con WU/CD
    • +
    +
  • +
  • + v.1.11.* → v.1.18.* +
      +
    • Inserimento controller SIEMENS con S7+ library
    • +
    • Inserimento nuove letture FANUC x programmi
    • +
    • Inserimento nuove letture FANUC x SysEx (informazioni sistema)
    • +
    • Inserimento invio FluxLog x parametri estesi (es SysEx, ProgName,...)
    • +
    • FIX visualizzazione dati FluxLog e URL inviati
    • +
    • FIX MAIN program da FANUC (non il current)
    • +
    • Inserita modalita' DUMP memoria (iniziale full + periodica)
    • +
    • Inserimento gestione contapezzi standard/checkBit in IOB.cfg
    • +
    • Inserimento contapezzi da area memoria X
    • +
    • NUOVA Gestione rami cliente e URL di update
    • +
    • Gestione modi CNC
    • +
    • Lettura dari dinamycs FANUC (feed, speed)
    • +
    • aggiunta gestione aree G0..G30 (overrides?)
    • +
    • fix errore disconnessione FANUC (allo spegnimento dl CNC) e memoria valori persistente a 1
    • +
    • fix globali x gestione log IN / FLOG + ottimizzaizone check FANUC (PING)
    • +
    • ottimizzazione fasi di restart in caso di assenza del server (evita reinvii inutili e migliora tempo ripartenza invio)
    • +
    • review procedure controllo connessione x FANUC (es Tornos II)
    • +
    • non richeide più privilegi admin x fare update
    • +
    • gestione segnali inverted
    • +
    • completata gestione configurabilità parametrica segnali (Tornos, CMZ, Biglia)
    • +
    • revisitazione LOG x distinguere processi IOB
    • +
    +
  • +
  • + v.0.1.* → v.0.10.* +
      +
    • Testato in produzione x update ad avvio e su richiesta
    • +
    • Testato in produzione x lettura dati da Fanuc
    • +
    • Inizio deploy con copia file su area IIS
    • +
    • Prima versione con autoupdate
    • +
    • Test PrettyBin x spostamento dll
    • +
    • Base acquisitore FANUC
    • +
    • Sistema base sw controllo in tray
    • +
    +
  • +
+ - -
- \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index f2e21cdd..6805741b 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -9,9 +9,9 @@ pipeline { steps { /* calcolo numero versione... diverso x branch MASTER/DEVELOP */ script { - withEnv(['NEXT_BUILD_NUMBER=705']) { - // env.versionNumber = VersionNumber(versionNumberString : '3.2.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true) - env.versionNumber = VersionNumber(versionNumberString : '3.2.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') + withEnv(['NEXT_BUILD_NUMBER=706']) { + // env.versionNumber = VersionNumber(versionNumberString : '3.3.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true) + env.versionNumber = VersionNumber(versionNumberString : '3.3.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') env.APP_NAME = 'MAPO-IOB-WIN' } } diff --git a/TestApp.sln b/TestApp.sln new file mode 100644 index 00000000..fc358db9 --- /dev/null +++ b/TestApp.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30413.136 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp", "TestApp\TestApp.csproj", "{41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D37298AA-67AF-432E-B3BB-12C51CD28F92} + EndGlobalSection +EndGlobal diff --git a/TestApp/FSWatch.cs b/TestApp/FSWatch.cs new file mode 100644 index 00000000..89f8715c --- /dev/null +++ b/TestApp/FSWatch.cs @@ -0,0 +1,109 @@ +using System; +using System.IO; +using System.Security.Permissions; + +namespace TestApp +{ + /************************************************** + * Classe gestione verifica cambio files in directory + * + * links: + * https://docs.microsoft.com/it-it/dotnet/api/system.io.filesystemwatcher?view=netframework-4.0 + * https://www.c-sharpcorner.com/UploadFile/puranindia/filesystemwatcher-in-C-Sharp/ + * + * + * ***********************************************/ + public static class FSWatch + { + + /// + /// Metodo principale esecuzione check filesystem + /// + [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] + public static void Run() + { + //string[] args = Environment.GetCommandLineArgs(); + + //// If a directory is not specified, exit program. + //if (args.Length != 2) + //{ + // // Display the proper way to call the program. + // Console.WriteLine("Usage: Watcher.exe (directory)"); + // return; + //} + + try + { + // Create a new FileSystemWatcher and set its properties. + using (FileSystemWatcher watcher = new FileSystemWatcher()) + { + //watcher.Path = args[1]; + + watcher.Path = Directory.GetCurrentDirectory(); + + // NO guardo le subdirs + watcher.IncludeSubdirectories = false; + + // Watch for changes in LastAccess and LastWrite times, and + // the renaming of files or directories. + //watcher.NotifyFilter = NotifyFilters.DirectoryName + // | NotifyFilters.FileName + // | NotifyFilters.LastAccess + // | NotifyFilters.LastWrite + // | NotifyFilters.Size; + watcher.NotifyFilter = NotifyFilters.Attributes + | NotifyFilters.CreationTime + | NotifyFilters.DirectoryName + | NotifyFilters.FileName + | NotifyFilters.LastAccess + | NotifyFilters.LastWrite + | NotifyFilters.Security + | NotifyFilters.Size; + + // Only watch text files. + watcher.Filter = "*.*"; + + // Add event handlers. + watcher.Changed += OnChanged; + watcher.Created += OnChanged; + watcher.Error += OnError; + watcher.Deleted += OnChanged; + watcher.Renamed += OnRenamed; + + // Begin watching. + watcher.EnableRaisingEvents = true; + + // Wait for the user to quit the program. + Console.WriteLine("Press 'q' to quit the sample."); + while (Console.Read() != 'q') ; + } + } + catch (IOException e) + { + //Console.WriteLine("A Exception Occurred :" + e); + Utils.Log.Error("A Exception Occurred :" + e); + } + catch (Exception oe) + { + //Console.WriteLine("An Exception Occurred :" + oe); + Utils.Log.Error("An Exception Occurred :" + oe); + } + } + + private static void OnError(object sender, ErrorEventArgs e) => + // Specify what is done when a file is changed, created, or deleted. + Console.WriteLine($"{DateTime.Now} | Error: {e.GetException()}"); + + // Define the event handlers. + private static void OnChanged(object source, FileSystemEventArgs e) => + Utils.Log.Info($"File: {e.Name} {e.ChangeType}"); + // Specify what is done when a file is changed, created, or deleted. + //Console.WriteLine($"{DateTime.Now} | File: {e.Name} {e.ChangeType} ({e.FullPath})"); + + + private static void OnRenamed(object source, RenamedEventArgs e) => + Utils.Log.Info($"File: {e.OldName} renamed to {e.Name}"); + // Specify what is done when a file is renamed. + //Console.WriteLine($"{DateTime.Now} | File: {e.OldName} renamed to {e.Name} ({e.OldFullPath} --> {e.FullPath})"); + } +} \ No newline at end of file diff --git a/TestApp/NLog.config b/TestApp/NLog.config new file mode 100644 index 00000000..a6354580 --- /dev/null +++ b/TestApp/NLog.config @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/TestApp/Program.cs b/TestApp/Program.cs new file mode 100644 index 00000000..5149f5b6 --- /dev/null +++ b/TestApp/Program.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace TestApp +{ + internal class Program + { + private static void Main(string[] args) + { + // eseguo test FS Watcher + FSWatch.Run(); + } + } +} \ No newline at end of file diff --git a/TestApp/Properties/AssemblyInfo.cs b/TestApp/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..3edf2271 --- /dev/null +++ b/TestApp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Le informazioni generali relative a un assembly sono controllate dal seguente +// set di attributi. Modificare i valori di questi attributi per modificare le informazioni +// associate a un assembly. +[assembly: AssemblyTitle("TestApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("TestApp")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili +// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da +// COM, impostare su true l'attributo ComVisible per tale tipo. +[assembly: ComVisible(false)] + +// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi +[assembly: Guid("41ced9a1-a4f8-4f8d-97ec-cbefc2b3f2eb")] + +// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: +// +// Versione principale +// Versione secondaria +// Numero di build +// Revisione +// +// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build +// usando l'asterisco '*' come illustrato di seguito: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/TestApp/TestApp.csproj b/TestApp/TestApp.csproj new file mode 100644 index 00000000..dde66a30 --- /dev/null +++ b/TestApp/TestApp.csproj @@ -0,0 +1,73 @@ + + + + + Debug + AnyCPU + {41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB} + Exe + TestApp + TestApp + v4.0 + 512 + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\NLog.4.7.5\lib\net40-client\NLog.dll + + + + + + + + + + + + + + + + + + + + + + Always + + + Always + + + + + + + + + + \ No newline at end of file diff --git a/TestApp/Utils.cs b/TestApp/Utils.cs new file mode 100644 index 00000000..473b5e49 --- /dev/null +++ b/TestApp/Utils.cs @@ -0,0 +1,23 @@ +using NLog; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace TestApp +{ + public class Utils + { + + /// + /// S + /// + public static Logger Log { get; private set; } + static Utils() + { + LogManager.ReconfigExistingLoggers(); + + Log = LogManager.GetCurrentClassLogger(); + } + } +} diff --git a/TestApp/logs/.placeholder b/TestApp/logs/.placeholder new file mode 100644 index 00000000..5f282702 --- /dev/null +++ b/TestApp/logs/.placeholder @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/TestApp/packages.config b/TestApp/packages.config new file mode 100644 index 00000000..73e35b24 --- /dev/null +++ b/TestApp/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file