From abbe7e3ed0565a3d634d279a1155556482406b49 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 15 Sep 2020 22:33:53 +0200 Subject: [PATCH 1/5] new vers --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 5e18c6bc..7e4f09ee 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -9,7 +9,7 @@ pipeline { steps { /* calcolo numero versione... diverso x branch MASTER/DEVELOP */ script { - withEnv(['NEXT_BUILD_NUMBER=697']) { + withEnv(['NEXT_BUILD_NUMBER=698']) { // env.versionNumber = VersionNumber(versionNumberString : '3.0.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true) env.versionNumber = VersionNumber(versionNumberString : '3.0.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}') env.APP_NAME = 'MAPO-IOB-WIN' From f145c64ceb3320e63b4b1336e3215f652c123731 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 15 Sep 2020 22:37:08 +0200 Subject: [PATCH 2/5] fix conf COMUR --- IOB-WIN/DATA/CONF/VL21.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/IOB-WIN/DATA/CONF/VL21.ini b/IOB-WIN/DATA/CONF/VL21.ini index b4d650aa..f7eba6c8 100644 --- a/IOB-WIN/DATA/CONF/VL21.ini +++ b/IOB-WIN/DATA/CONF/VL21.ini @@ -53,8 +53,8 @@ BLINK_FILT=0 [OPTPAR] ;PZCOUNT_MODE=STD.[PAR/MEM].info|BIT.indice -; attenzione memoria sempre base BYTE (1604 DW --> 6416...) -PZCOUNT_MODE=SPEC.DB111.DBB2 +; attenzione memoria sempre base BYTE (1604 DW --> 6416...) +PZCOUNT_MODE=SPEC.DB111.DBDW24 DISABLE_PZCOUNT=TRUE ENABLE_DYN_DATA=TRUE FORCE_DYN_DATA=TRUE From c640dca3384c5ec4c6ce0105ceecc63c7ed81818 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 15 Sep 2020 22:37:18 +0200 Subject: [PATCH 3/5] aggiunta conf x SIMEC --- IOB-WIN/DATA/CONF/VL26.ini | 60 +++++++++++++++++++++++++++++++++++++ IOB-WIN/DATA/CONF/VL26.json | 41 +++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 IOB-WIN/DATA/CONF/VL26.ini create mode 100644 IOB-WIN/DATA/CONF/VL26.json diff --git a/IOB-WIN/DATA/CONF/VL26.ini b/IOB-WIN/DATA/CONF/VL26.ini new file mode 100644 index 00000000..da2e1e13 --- /dev/null +++ b/IOB-WIN/DATA/CONF/VL26.ini @@ -0,0 +1,60 @@ +;Configurazione IOB-WIN +[IOB] +;Macchina taglio barre per Valvital +CNCTYPE=SIEMENS_SIMEC +PING_MS_TIMEOUT=500 + +[MACHINE] +VENDOR=SIMEC +MODEL=180 + +[CNC] +IP=192.168.219.15 +CPUTYPE=S7300 +RACK=0 +SLOT=0 + +[SERVER] +MPIP=http://192.168.214.4 +MPURL=/MP/IO +CMDBASE=/IOB/input/ +CMDFLOG=/IOB/flog/ +CMDALIVE=/IOB +CMDENABLED=/IOB/enabled/ +CMDADV1=?valore= +CMDREBO=/sendReboot.aspx?idxMacchina= + +[MEMORY] +ADDR_READ=DB29.DBB0 +ADDR_WRITE=DB30.DBB0 +SIZE_READ=10 +SIZE_WRITE=40 + + +[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 +PZCOUNT_MODE=STD.DB29.DBDW6 +;PZSCRAP_MODE=STD.DB700.DBDW32 +DISABLE_PZCOUNT=TRUE +ENABLE_DYN_DATA=TRUE +FORCE_DYN_DATA=TRUE + +; conf parametri memoria READ/WRITE +PARAM_CONF=VL26.json + +[BRANCH] +NAME=master \ No newline at end of file diff --git a/IOB-WIN/DATA/CONF/VL26.json b/IOB-WIN/DATA/CONF/VL26.json new file mode 100644 index 00000000..02214474 --- /dev/null +++ b/IOB-WIN/DATA/CONF/VL26.json @@ -0,0 +1,41 @@ +{ + "mMapWrite": { + "setPzComm": { + "name": "setProg", + "description": "Programma", + "tipoMem": "String", + "memAddr": "DB30.DBB30", + "index": 30, + "size": 10 + }, + "setComm": { + "name": "setComm", + "description": "Commessa", + "tipoMem": "String", + "memAddr": "DB30.DBB20", + "index": 20, + "size": 10 + }, + "setArt": { + "name": "setArt", + "description": "Articolo", + "tipoMem": "String", + "memAddr": "DB30.DBB0", + "index": 0, + "size": 20 + } + }, + "mMapRead": { + "ContatoreAssoluto": { + "name": "ContatoreAssoluto", + "description": "Contapezzi ASSOLUTO", + "memAddr": "DB29.DBB2", + "tipoMem": "DInt", + "index": 2, + "size": 4, + "func": "MAX", + "period": 60, + "factor": 1 + } + } +} \ No newline at end of file From ffa5f7dd59d654ce0d94198f697e579161017e28 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 15 Sep 2020 22:37:26 +0200 Subject: [PATCH 4/5] Aggiunta siemens SIMEC --- IOB-WIN/IobSiemensSimec.cs | 244 +++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 IOB-WIN/IobSiemensSimec.cs diff --git a/IOB-WIN/IobSiemensSimec.cs b/IOB-WIN/IobSiemensSimec.cs new file mode 100644 index 00000000..c91de155 --- /dev/null +++ b/IOB-WIN/IobSiemensSimec.cs @@ -0,0 +1,244 @@ +using MapoSDK; +using System; +using System.Collections.Generic; + +namespace IOB_WIN +{ + /// + /// Controllo Siemens specifico x impianti Simec + /// + public class IobSiemensSimec : IobSiemens + { + /* -------------------------------------------------------------------------------- + * Controlli SIEMENS SIMEC + * - basasto su SIEMENS + * - S7 vers 1500 + * + * STRUTTURA MEMORIA DB29: (lettura) 10byte, + * G:\Drive condivisi\30_Clienti\Valvital\Comunicazione PLC\26 - SIMEC Taglio\ + * + * Si intende lettura con DB29.DBxx, scrittura DB30.DBxx + * + * DB30 blocco dati scritto dal MES + * CodArt Array[0..19] of Char DBB0..19 + * CodComm Array[0..9] of Char DBB20..29 + * CodProgr Array[0..9] of Char DBB30..39 + * + * DB29 blocco dati letto dal MES Byte Bit + * CicloOn Bool 0 0 + * MacchOn Bool 0 1 + * ManualeOn Bool 0 2 + * AllarmiOn Bool 0 3 + * EmergenzaOn Bool 0 4 + * EmergenzaPremuta Bool 0 5 + * b06 Bool 0 6 + * b07 Bool 0 7 + * b10 Bool 1 0 + * b11 Bool 1 1 + * b12 Bool 1 2 + * b13 Bool 1 3 + * b14 Bool 1 4 + * b15 Bool 1 5 + * b16 Bool 1 6 + * b17 Bool 1 7 + * ContapezziAssoluto DInt 2 + * Comtapezzi parziale DInt 6 + * -------------------------------------------------------------------------------- */ + + /// + /// Classe base con i metodi x Siemens + /// + /// + /// + public IobSiemensSimec(AdapterForm caller, IobConfiguration IOBConf) : base(caller, IOBConf) + { + lgInfo("NEW IOB SIEMENS versione SIMEC"); + } + + #region Metodi specifici (da verificare/completare in implementazione) + + /// + /// Processo i task richiesti e li elimino dalla coda 1:1 + /// + /// + public override Dictionary executeTasks(Dictionary task2exe) + { + // Verificare il protocollo: dovrebeb togliere SOLO i task eseguiti... + Dictionary taskDone = new Dictionary(); + bool taskOk = false; + string taskVal = ""; + // inizio con 1 byte di default + byte[] MemBlock = new byte[1]; + string memAddrWrite = ""; + if (task2exe != null) + { + // cerco task specifici + foreach (var item in task2exe) + { + taskOk = false; + taskVal = ""; + // converto richiesta in enum... + taskType tName = taskType.nihil; + Enum.TryParse(item.Key, out tName); + // controllo sulla KEY + switch (tName) + { + case taskType.nihil: + case taskType.fixStopSetup: + case taskType.forceResetPzCount: + case taskType.forceSetPzCount: + case taskType.setProg: + case taskType.sendWatchDogMes2Plc: + case taskType.setPzComm: + taskVal = $"taskReq: {tName} | key: {item.Key} | val: {item.Value} | SKIPPED | NO EXEC"; + break; + case taskType.setArt: + case taskType.setComm: + saveProdData(item); + int byteSize = 0; + // recupero dati da memMap... altrimenti NULLA + if (memMap.mMapWrite.ContainsKey(item.Key)) + { + dataConf currMem = memMap.mMapWrite[item.Key]; + byteSize = currMem.size; + memAddrWrite = currMem.memAddr; + MemBlock = new byte[byteSize]; + if (currMem.tipoMem == plcDataType.String) + { + saveStringOnMemBlock(ref MemBlock, item.Key, 0, byteSize); + } + else if (currMem.tipoMem == plcDataType.DInt) + { + int valDInt = 0; + int.TryParse(item.Value, out valDInt); + MemBlock = S7.Net.Types.DInt.ToByteArray(valDInt); + } + else if (currMem.tipoMem == plcDataType.Int) + { + short valDInt = 0; + short.TryParse(item.Value, out valDInt); + MemBlock = S7.Net.Types.Int.ToByteArray(valDInt); + } + } + taskVal = item.Value; + break; + case taskType.startSetup: + //// processo scrittura BIT su DB150.DBX4.0 + //MemBlock = new byte[1]; + //MemBlock[0] = (byte)1; + //memAddrWrite = "DB150.DBB4"; + break; + case taskType.stopSetup: + //// processo scrittura BIT su DB150.DBX4.0 + //MemBlock = new byte[1]; + //MemBlock[0] = (byte)0; + //memAddrWrite = "DB150.DBB4"; + break; + case taskType.setParameter: + // richiedo da URL i parametri WRITE da popolare + lgInfo("Chiamata processMemWriteRequests"); + taskVal = processMemWriteRequests(); + // se restituiscce "" faccio altra prova... + if (string.IsNullOrEmpty(taskVal)) + { + // i parametri me li aspetto come stringa composta paramName|paramvalue + if (item.Value.Contains("|")) + { + string[] paramsJob = item.Value.Split('|'); + taskVal = $"REQUEST SET PARAMETERS: {paramsJob[0]} --> {paramsJob[1]}"; + } + else + { + taskVal = $"WRONG REQUEST FOR SET PARAMETERS: {item.Value} doesnt contain pipe for splitting key/value"; + } + } + break; + default: + taskVal = "SKIPPED | NO EXEC"; + break; + } + // aggiungo task! + taskDone.Add(item.Key, taskVal); + if (string.IsNullOrEmpty(memAddrWrite)) + { + // scrivo comunque! + taskOk = S7WriteBB(ref MemBlock, memAddrWrite); + } + if (!taskOk) + { + lgError($"Errore in S7WriteBB durante executeTasks: {item.Key} | {item.Value}"); + } + } + } + return taskDone; + } + + /// + /// Effettua decodifica aree memoria alla bitmap usata x MAPO + /// + protected override void decodeToBaseBitmap() + { + // init a zero... + B_input = 0; + + /* ----------------------------------------------------- + * bitmap MAPO STANDARD + * B0: POWER_ON + * B1: RUN + * B2: pzCount + * B3: allarme + * B4: manuale + * + * - BIT di stato + * DB29 blocco dati letto dal MES Byte Bit + * CicloOn Bool 0 0 + * MacchOn Bool 0 1 + * ManualeOn Bool 0 2 + * AllarmiOn Bool 0 3 + * EmergenzaOn Bool 0 4 + * EmergenzaPremuta Bool 0 5 + * ContapezziAssoluto DInt 2 + * Comtapezzi parziale DInt 6 + * + ----------------------------------------------------- */ + + byte mainData = RawInput[0]; + + int byteSignals = 0; + // bit 0 (poweron) imposto a 1 SE connected... + if (currPLC.IsConnected) + { + byteSignals += (1 << 0); + } + + // lavora --> bit0 e bit1: cicloOn AND macchOn + if ((mainData & (1 << 0)) != 0 && (mainData & (1 << 1)) != 0) + { + byteSignals += (1 << 1); + } + + // controllo il bit ALARM OR emergenza dello status + if ((mainData & (1 << 3)) != 0 || (mainData & (1 << 5)) != 0) + { + byteSignals += (1 << 3); + } + + // check MANUALE ... + if ((mainData & (1 << 2)) != 0) + { + byteSignals += (1 << 4); + } + + // salvo! + B_input = byteSignals; + + // log opzionale! + if (verboseLog) + { + lgInfo($"Trasformazione dati: RawInput:{RawInput[0]} --> B_input: {B_input}"); + } + } + + #endregion + } +} From 574b19e41e7d3609bd57ae6bfa0bc5817d49ba68 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 15 Sep 2020 22:37:36 +0200 Subject: [PATCH 5/5] update progetto x simec --- IOB-UT/Enums.cs | 544 ++++---- IOB-WIN/AdapterForm.cs | 2964 ++++++++++++++++++++-------------------- IOB-WIN/IOB-WIN.csproj | 7 + 3 files changed, 1765 insertions(+), 1750 deletions(-) diff --git a/IOB-UT/Enums.cs b/IOB-UT/Enums.cs index d326babf..311e41b2 100644 --- a/IOB-UT/Enums.cs +++ b/IOB-UT/Enums.cs @@ -6,189 +6,193 @@ using System.Text; namespace IOB_UT { - /// - /// Tipologie di DUMP memoria - /// - public enum dumpType - { /// - /// Salvataggio all'avvio aree memoria (con sovrascrittura) + /// Tipologie di DUMP memoria /// - STARTUP, + public enum dumpType + { + /// + /// Salvataggio all'avvio aree memoria (con sovrascrittura) + /// + STARTUP, + /// + /// Campionamento periodico + /// + SAMPLE + } /// - /// Campionamento periodico + /// Tipologia di adapters ammessi /// - SAMPLE - } - /// - /// Tipologia di adapters ammessi - /// - public enum tipoAdapter - { + 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 + } /// - /// Adapter SIMULAZIONE + /// Tipo di ciclo da processare /// - 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 Torri - /// - SIEMENS_TORRI, - /// - /// Metodi di WPS WebPageScraping (es x compressori Atlas Copco) - /// - WPS - } - /// - /// Tipo di ciclo da processare - /// - public enum gatherCycle - { - /// - /// 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 - } + public enum gatherCycle + { + /// + /// 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 - /// - [Flags] - public enum StFlag32 : int - { - NONE = 0, - B00 = 1 << 0, - B01 = 1 << 1, - B02 = 1 << 2, - B03 = 1 << 3, - B04 = 1 << 4, - B05 = 1 << 5, - B06 = 1 << 6, - B07 = 1 << 7, - B08 = 1 << 8, - B09 = 1 << 9, - B10 = 1 << 10, - B11 = 1 << 11, - B12 = 1 << 12, - B13 = 1 << 13, - B14 = 1 << 14, - B15 = 1 << 15, - B16 = 1 << 16, - B17 = 1 << 17, - B18 = 1 << 18, - B19 = 1 << 19, - B20 = 1 << 20, - B21 = 1 << 21, - B22 = 1 << 22, - B23 = 1 << 23, - B24 = 1 << 24, - B25 = 1 << 25, - B26 = 1 << 26, - B27 = 1 << 27, - B28 = 1 << 28, - B29 = 1 << 29, - 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 + } + /// + /// StFlag32: set di 32 bit (4 word) contente semaforo di variabili + /// + [Flags] + public enum StFlag32 : int + { + NONE = 0, + B00 = 1 << 0, + B01 = 1 << 1, + B02 = 1 << 2, + B03 = 1 << 3, + B04 = 1 << 4, + B05 = 1 << 5, + B06 = 1 << 6, + B07 = 1 << 7, + B08 = 1 << 8, + B09 = 1 << 9, + B10 = 1 << 10, + B11 = 1 << 11, + B12 = 1 << 12, + B13 = 1 << 13, + B14 = 1 << 14, + B15 = 1 << 15, + B16 = 1 << 16, + B17 = 1 << 17, + B18 = 1 << 18, + B19 = 1 << 19, + B20 = 1 << 20, + B21 = 1 << 21, + B22 = 1 << 22, + B23 = 1 << 23, + B24 = 1 << 24, + B25 = 1 << 25, + B26 = 1 << 26, + B27 = 1 << 27, + B28 = 1 << 28, + B29 = 1 << 29, + B30 = 1 << 30, + B31 = 1 << 31 + } #if false /// /// Enumerazione tipi di semaforo @@ -217,105 +221,105 @@ namespace IOB_UT SS } #endif - /// - /// Enumerazione tipi di tipi di URL x invio - /// - public enum urlType - { /// - /// Salvataggio FluxLog (valori estesi che non provocano calcoli di macchine a stati, eventi...) + /// Enumerazione tipi di tipi di URL x invio /// - FLog, - /// - /// INPUT segnali in ingresso (standard base MAPO) - /// - SignIN - } + public enum urlType + { + /// + /// 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 + /// Elenco STATI CNC OSAI /// - ND = 0, + public enum CNC_STATUS_OSAI + { + IDLE = 1, + CYCLE, + HODA, + RUNH, + HRUN, + ERRO, + WAIT, + RESET, + EMERG, + INPUT + } /// - /// AUTOMATICO + /// Elenco MODI CNC /// - 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 - } + 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 + } } diff --git a/IOB-WIN/AdapterForm.cs b/IOB-WIN/AdapterForm.cs index 02e99cbb..6e1a4c1e 100644 --- a/IOB-WIN/AdapterForm.cs +++ b/IOB-WIN/AdapterForm.cs @@ -13,1525 +13,1529 @@ using System.Windows.Forms; namespace IOB_WIN { - public partial class AdapterForm : Form - { - #region inizializzazione contatori - - /// - /// contatore veloce - /// - protected int fastCount; - /// - /// contatore normale - /// - protected int normCount; - /// - /// contatore lento - /// - protected int slowCount; - /// - /// contatore sync allarmi - /// - protected int verySlowCount; - /// - /// Contatore campionamento memoria - /// - protected int sampleMemCount; - /// - /// ultimo tentativo riavvio... - /// - protected DateTime lastStartTry; - /// - /// Data-Ora prima apertura FORM... - /// - protected DateTime firstStart; - - #endregion - - #region inizializzazione oggetti base - - /// - /// oggetto logging - /// - public static Logger lg; - /// - /// Oggetto x gestione dell'adapter GENERICO (x poter usare metodi di ognuno...) - /// - public IobGeneric iobObj; - /// - /// configurazione caricata - /// - public IobConfiguration IOBConf; - /// - /// tipo di adapter prescelto... - /// - public tipoAdapter tipoScelto = tipoAdapter.SIMULA; - /// - /// Vendor macchina - /// - public string curVendor = ""; - /// - /// Modello macchina - /// - public string curModel = ""; - /// - /// Codice IOB della macchina cui connettersi (x scegliere corretto file di conf...) - /// - protected string CurrIOB { get; set; } - /// - /// Temnpo attesa std in MS - /// - protected int waitRecMSec = 30000; - /// - /// Oggetto ultimo inviato stato MP-IO x REDIS - /// - protected ServerMpStatus lastSrvStatus = new ServerMpStatus(); - /// - /// Oggetto ultimo inviato stato IOB x REDIS - /// - protected IobWinStatus lastIobStatus = new IobWinStatus(); - - #endregion - - #region utils ed helpers - - /// - /// Log verboso da configurazione (SOLO CHAIVE "verbose"... - /// - public bool isVerboseLog { get; set; } = utils.CRB("verbose"); - 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; - - /// - /// Effettua un trim della stringa al numero max di linee da mostrare a video - /// - /// - /// - public string limitLine2show(string newString) + public partial class AdapterForm : Form { - if (!string.IsNullOrEmpty(newString)) - { - // se num righe superiore a limite trimmo... - if (newString.Split('\n').Length > nLine2show) + #region inizializzazione contatori + + /// + /// contatore veloce + /// + protected int fastCount; + /// + /// contatore normale + /// + protected int normCount; + /// + /// contatore lento + /// + protected int slowCount; + /// + /// contatore sync allarmi + /// + protected int verySlowCount; + /// + /// Contatore campionamento memoria + /// + protected int sampleMemCount; + /// + /// ultimo tentativo riavvio... + /// + protected DateTime lastStartTry; + /// + /// Data-Ora prima apertura FORM... + /// + protected DateTime firstStart; + + #endregion + + #region inizializzazione oggetti base + + /// + /// oggetto logging + /// + public static Logger lg; + /// + /// Oggetto x gestione dell'adapter GENERICO (x poter usare metodi di ognuno...) + /// + public IobGeneric iobObj; + /// + /// configurazione caricata + /// + public IobConfiguration IOBConf; + /// + /// tipo di adapter prescelto... + /// + public tipoAdapter tipoScelto = tipoAdapter.SIMULA; + /// + /// Vendor macchina + /// + public string curVendor = ""; + /// + /// Modello macchina + /// + public string curModel = ""; + /// + /// Codice IOB della macchina cui connettersi (x scegliere corretto file di conf...) + /// + protected string CurrIOB { get; set; } + /// + /// Temnpo attesa std in MS + /// + protected int waitRecMSec = 30000; + /// + /// Oggetto ultimo inviato stato MP-IO x REDIS + /// + protected ServerMpStatus lastSrvStatus = new ServerMpStatus(); + /// + /// Oggetto ultimo inviato stato IOB x REDIS + /// + protected IobWinStatus lastIobStatus = new IobWinStatus(); + + #endregion + + #region utils ed helpers + + /// + /// Log verboso da configurazione (SOLO CHAIVE "verbose"... + /// + public bool isVerboseLog { get; set; } = utils.CRB("verbose"); + 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; + + /// + /// Effettua un trim della stringa al numero max di linee da mostrare a video + /// + /// + /// + public string limitLine2show(string newString) { - //int idx = newString.LastIndexOf('\r'); - int idx = newString.LastIndexOf(Environment.NewLine); - newString = newString.Substring(0, idx); + 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; } - } - return newString; - } - /// - /// Logwatcher (in modalità "accodamento in testa" ultimi messaggi...) - /// - public string logWatcher - { - get - { - return lblLogfile.Text; - } - set - { - try + /// + /// 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 + + /// + /// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere... + /// + /// + protected void lgInfo(string txt2log) { - lblTaskLog.Text = limitLine2show($"{value}{Environment.NewLine}{lblTaskLog.Text}"); - lblTaskLog.Refresh(); + 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); } - catch (Exception exc) + /// + /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... + /// + /// + protected void lgError(string txt2log) { - lgError($"Errore in esecuzione taskWatcher{Environment.NewLine}--> {value}"); - if (isVerboseLog) - { - lgError($"{exc}"); - } + 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); + } + } } - } - } - /// - /// 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); - } - /// - /// 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 un testo sulla status bar + LOG + /// + /// + public void displayTaskAndLog(string txt2show) { - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | ERROR | {txt2log}"; - updateFormDisplay(currDispData); + lblStatus.Text = txt2show; + lblStatus.Invalidate(); + lgInfo(txt2show); } - } - } + /// + /// Mostra update delle statistiche di comunicazione (numero chiamate, tempo medio...) + /// + /// + public void updateComStats(string txt2show) + { + lblComStats.Text = string.Format("{0} | ", txt2show); + } + + #endregion + + #region gestione form e visibilità - /// - /// mostra un testo sulla status bar + LOG - /// - /// - public void displayTaskAndLog(string txt2show) - { - lblStatus.Text = txt2show; - lblStatus.Invalidate(); - lgInfo(txt2show); - } - /// - /// Mostra update delle statistiche di comunicazione (numero chiamate, tempo medio...) - /// - /// - public void updateComStats(string txt2show) - { - lblComStats.Text = string.Format("{0} | ", txt2show); - } + /// + /// File configurazione default + /// + public string defConfFilePath + { + get + { + return string.Format(@"{0}\{1}.ini", utils.confDir, CurrIOB); + } + } + /// + /// Init form (grafica) con helper x testi e varie + /// + protected void myGraphInitForm() + { + lblStatus.Text = "Loading"; - #endregion + // aggiunta tooltip x send forzato + ToolTip ttForceSend = new ToolTip(); - #region gestione form e visibilità + // 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"); + } - /// - /// File configurazione default - /// - public string defConfFilePath - { - get - { - return string.Format(@"{0}\{1}.ini", utils.confDir, CurrIOB); - } - } - /// - /// Init form (grafica) con helper x testi e varie - /// - protected void myGraphInitForm() - { - lblStatus.Text = "Loading"; + /// + /// Avvio MainForm + /// + /// + public AdapterForm(string codIOB) + { + CurrIOB = codIOB; + // continuo avvio... + InitializeComponent(); + myGraphInitForm(); - // aggiunta tooltip x send forzato - ToolTip ttForceSend = new ToolTip(); + checkEditMes2Plc(); - // imposto delay. - ttForceSend.AutoPopDelay = 3000; - ttForceSend.InitialDelay = 500; - ttForceSend.ReshowDelay = 500; - // sempre visibile (che sia o meno attiva la form). - ttForceSend.ShowAlways = true; + // inizializzo orologi + firstStart = DateTime.Now; + lastStartTry = DateTime.Now; - // imposto tooltip - ttForceSend.SetToolTip(this.chkForceDequeue, "Forza invio eventi allo stop"); - } - - /// - /// Avvio MainForm - /// - /// - public AdapterForm(string codIOB) - { - CurrIOB = codIOB; - // continuo avvio... - InitializeComponent(); - myGraphInitForm(); - - checkEditMes2Plc(); - - // 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"); - } - /// - /// Fase chiusura Form - /// - /// - /// - private void MainForm_FormClosing(object sender, FormClosingEventArgs e) - { - closeAdapter(); - } - /// - /// Mostrata form - /// - /// - /// - private void MainForm_Shown(object sender, EventArgs e) - { - displayTaskAndLog("Main Form SHOWN"); - } - /// - /// Completato resize form - /// - /// - /// - private void MainForm_Resize(object sender, EventArgs e) - { - } - - #endregion - - #region gestione metodi specifici FORM - - private void checkSendTask() - { - // avvio fase invio con adapter (code MST) - iobObj.getAndSend(gatherCycle.VHF); - } - 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 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); - } - } - - 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 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.contapezzi}"; - counterMac = $"pz mac {iobObj.lastCountCNC}"; - // verifico IOB status - IobWinStatus currIobStatus = new IobWinStatus() - { - CodIob = iobObj.cIobConf.codIOB, - queueEvLen = evQueueLen, - queueFlLen = flQueueLen, - queueAlLen = alQueueLen, - queueMsLen = msQueueLen, - counterIOB = iobObj.contapezzi, - counterMAC = iobObj.lastCountCNC, - 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; - } - } - 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) + /// + /// Fase chiusura Form + /// + /// + /// + private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { - lgError(string.Format("Eccezione in fase di gatherTick: {0}{1}", Environment.NewLine, exc)); + closeAdapter(); } - } - } - - /// - /// 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); - } - } - - /// - /// 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 + /// + /// Mostrata form + /// + /// + /// + private void MainForm_Shown(object sender, EventArgs e) { - string[] kvp; - foreach (var item in optParRows) - { - kvp = item.Split('='); - optParRead.Add(kvp[0], kvp[1]); - } - lgInfo($"Caricati {optParRead.Count} parametri opzionali da OPTPAR"); + displayTaskAndLog("Main Form SHOWN"); } - catch (Exception exc) + /// + /// Completato resize form + /// + /// + /// + private void MainForm_Resize(object sender, EventArgs e) { - 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, // fIni.ReadString("IOB", "IDXMACC", "0"), - 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")) - }; - 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)); - } - } - - /// - /// 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) - { - 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; - } - } - - #endregion - - #region Area BackGroundWorker - - - /// - /// 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)) - { - 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) + #endregion + + #region gestione metodi specifici FORM + + 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 checkFastTask() { - 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; - } - } - } - - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #endregion - - #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 - - 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"); - } - } - - /// - /// 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_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)); - } - /// - /// GEstione evento refresh - /// - /// - /// - private void IobObj_eh_refreshed(object sender, iobRefreshedEventArgs e) - { - // aggiorno! - updateFormDisplay(e.DisplayDataObject); - } - - /// - /// impostazione valori defaults - /// - private void setDefaults() - { - stop.Enabled = false; - - evQueueLen = 0; - flQueueLen = 0; - nLine2show = utils.CRI("numRowConsole"); - } - /// - /// Valore protected comunicazione PLC - /// - protected bool _commPlcActive { get; set; } = false; - /// - /// 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(); - } - } - /// - /// Valore protetto stato comunicazione - /// - protected int _commSrvActive { get; set; } = 0; - /// - /// 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) - { - 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(); - } - } - - /// - /// Avvio dell'adapter - /// - /// - /// - private void start_Click(object sender, EventArgs e) - { - avviaAdapter(chkForceDequeue.Checked); - // salvo che ho avviato adapter - lgInfo("Completato LOAD Adapter"); - } - /// - /// 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..."); - } - } - /// - /// 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 = ""; - } - } - /// - /// fermata dell'adapter - /// - /// - /// - private void stop_Click(object sender, EventArgs e) - { - fermaAdapter(false, chkForceDequeue.Checked, true); - // salvo che ho fermato adapter - lgInfo("UNLOAD Adapter"); - } - /// - /// 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); - } - - /// - /// 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; - } - } - protected int maxEvQueue { get; set; } - protected int maxFlQueue { get; set; } - protected int maxAlQueue { get; set; } - protected int maxMsQueue { get; set; } - - protected int qEvLen { get; set; } - protected int qFlLen { get; set; } - protected int qAlLen { get; set; } - protected int qMsLen { get; set; } - - protected int totQueue - { - get - { - return qEvLen + qFlLen + qAlLen + qMsLen; - } - } - /// - /// MOstra info su coda complessiva - /// - protected void showQueueData() - { - lblQueueLenTop.Text = totQueue == 0 ? "realtime" : $"ev: {qEvLen} | flog: {qFlLen} | tot: {totQueue}"; - } - - 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 alQueueLen - { - 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; - } - } - 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; - } - } - - public string counterMac - { - get - { - return lblPzCountMac.Text; - } - set - { - lblPzCountMac.Text = value; - } - } - public string counterIob - { - get - { - return lblPzCountIob.Text; - } - set - { - lblPzCountIob.Text = value; - } - } - - /// - /// 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(); - } - } - /// - /// Valore protected semaforo IN - /// - protected Semaforo _sIN { get; set; } = Semaforo.ND; - /// - /// Imposta COLORE SFONDO x Semaforo IN - /// - public Semaforo sIN - { - get - { - return _sIN; - } - set - { - _sIN = value; - bIN.BackColor = decSemaforo(value); - bIN.Refresh(); - } - } - /// - /// Valore protected semaforo OUT - /// - protected Semaforo _sOUT { get; set; } = Semaforo.ND; - /// - /// 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; - } - - private void displTimer_Tick(object sender, EventArgs e) - { - } - - private void TabData_Selected(object sender, TabControlEventArgs e) - { - } - - private void fixComboParameters() - { - if (iobObj != null) - { - if (iobObj.memMap != null) - { - if (iobObj.memMap.mMapWrite != null) - { - if (iobObj.memMap.mMapWrite.Count > 0) + // decremento... + fastCount--; + // se il counter è a zero eseguo... + if (fastCount <= 0) { - List parametri = new List(); - foreach (var item in iobObj.memMap.mMapWrite) - { - parametri.Add(item.Key); - } - cmbParamValues.DataSource = parametri; + 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"); - private void checkEditMes2Plc() - { - cmbParamValues.Enabled = enableEditMes2Plc; - txtValue.Enabled = enableEditMes2Plc; - if (enableEditMes2Plc) - { - // aggiorno (se possibile) i parametri selezionabili... - fixComboParameters(); - } - } - public bool enableEditMes2Plc { get; set; } + // avvio fase raccolta dati e invio con adapter + iobObj.getAndSend(gatherCycle.MF); + } + } + private void checkSlowTask() + { + slowCount--; + if (slowCount <= 0) + { + slowCount = utils.CRI("slowCount"); - private void ChkEdit_CheckedChanged(object sender, EventArgs e) - { - toggleEditMes2Plc(); - } + // avvio fase raccolta dati e invio con adapter + iobObj.getAndSend(gatherCycle.LF); + } + } - private void toggleEditMes2Plc() - { - // abilita i campi --> PLC per editing - enableEditMes2Plc = !enableEditMes2Plc; - checkEditMes2Plc(); - } + private void checkVerySlowData() + { + verySlowCount--; + if (verySlowCount <= 0) + { + verySlowCount = utils.CRI("verySlowCount"); + // avvio fase raccolta dati e invio con adapter + iobObj.getAndSend(gatherCycle.VLF); + } + } - 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); - } + 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 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.contapezzi}"; + counterMac = $"pz mac {iobObj.lastCountCNC}"; + // verifico IOB status + IobWinStatus currIobStatus = new IobWinStatus() + { + CodIob = iobObj.cIobConf.codIOB, + queueEvLen = evQueueLen, + queueFlLen = flQueueLen, + queueAlLen = alQueueLen, + queueMsLen = msQueueLen, + counterIOB = iobObj.contapezzi, + counterMAC = iobObj.lastCountCNC, + 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; + } + } + 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 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)); + } + } + } + + /// + /// 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); + } + } + + /// + /// 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 + { + 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, // fIni.ReadString("IOB", "IDXMACC", "0"), + 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")) + }; + 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)); + } + } + + /// + /// 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) + { + 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; + } + } + + #endregion + + #region Area BackGroundWorker + + + /// + /// 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)) + { + 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; + } + } + } + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #endregion + + #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 + + 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"); + } + } + + /// + /// 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)); + } + /// + /// GEstione evento refresh + /// + /// + /// + private void IobObj_eh_refreshed(object sender, iobRefreshedEventArgs e) + { + // aggiorno! + updateFormDisplay(e.DisplayDataObject); + } + + /// + /// impostazione valori defaults + /// + private void setDefaults() + { + stop.Enabled = false; + + evQueueLen = 0; + flQueueLen = 0; + nLine2show = utils.CRI("numRowConsole"); + } + /// + /// Valore protected comunicazione PLC + /// + protected bool _commPlcActive { get; set; } = false; + /// + /// 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(); + } + } + /// + /// Valore protetto stato comunicazione + /// + protected int _commSrvActive { get; set; } = 0; + /// + /// 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) + { + 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(); + } + } + + /// + /// Avvio dell'adapter + /// + /// + /// + private void start_Click(object sender, EventArgs e) + { + avviaAdapter(chkForceDequeue.Checked); + // salvo che ho avviato adapter + lgInfo("Completato LOAD Adapter"); + } + /// + /// 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..."); + } + } + /// + /// 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 = ""; + } + } + /// + /// fermata dell'adapter + /// + /// + /// + private void stop_Click(object sender, EventArgs e) + { + fermaAdapter(false, chkForceDequeue.Checked, true); + // salvo che ho fermato adapter + lgInfo("UNLOAD Adapter"); + } + /// + /// 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); + } + + /// + /// 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; + } + } + protected int maxEvQueue { get; set; } + protected int maxFlQueue { get; set; } + protected int maxAlQueue { get; set; } + protected int maxMsQueue { get; set; } + + protected int qEvLen { get; set; } + protected int qFlLen { get; set; } + protected int qAlLen { get; set; } + protected int qMsLen { get; set; } + + protected int totQueue + { + get + { + return qEvLen + qFlLen + qAlLen + qMsLen; + } + } + /// + /// MOstra info su coda complessiva + /// + protected void showQueueData() + { + lblQueueLenTop.Text = totQueue == 0 ? "realtime" : $"ev: {qEvLen} | flog: {qFlLen} | tot: {totQueue}"; + } + + 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 alQueueLen + { + 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; + } + } + 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; + } + } + + public string counterMac + { + get + { + return lblPzCountMac.Text; + } + set + { + lblPzCountMac.Text = value; + } + } + public string counterIob + { + get + { + return lblPzCountIob.Text; + } + set + { + lblPzCountIob.Text = value; + } + } + + /// + /// 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(); + } + } + /// + /// Valore protected semaforo IN + /// + protected Semaforo _sIN { get; set; } = Semaforo.ND; + /// + /// Imposta COLORE SFONDO x Semaforo IN + /// + public Semaforo sIN + { + get + { + return _sIN; + } + set + { + _sIN = value; + bIN.BackColor = decSemaforo(value); + bIN.Refresh(); + } + } + /// + /// Valore protected semaforo OUT + /// + protected Semaforo _sOUT { get; set; } = Semaforo.ND; + /// + /// 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; + } + + private void displTimer_Tick(object sender, EventArgs e) + { + } + + private void TabData_Selected(object sender, TabControlEventArgs 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; + } + } + } + } + } + + private void checkEditMes2Plc() + { + cmbParamValues.Enabled = enableEditMes2Plc; + txtValue.Enabled = enableEditMes2Plc; + if (enableEditMes2Plc) + { + // aggiorno (se possibile) i parametri selezionabili... + fixComboParameters(); + } + } + public bool enableEditMes2Plc { get; set; } + + private void ChkEdit_CheckedChanged(object sender, EventArgs e) + { + toggleEditMes2Plc(); + } + + private void toggleEditMes2Plc() + { + // abilita i campi --> PLC per editing + enableEditMes2Plc = !enableEditMes2Plc; + checkEditMes2Plc(); + } + + 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 != "") @@ -1547,28 +1551,28 @@ namespace IOB_WIN forcedTask.Add("setProg", currPrgName); } #endif - // chiedo esecuzione task! - iobObj.processTask(forcedTask); - toggleEditMes2Plc(); - } + // chiedo esecuzione task! + iobObj.processTask(forcedTask); + toggleEditMes2Plc(); + } - 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 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 splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) - { + private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) + { + + } } - - } } diff --git a/IOB-WIN/IOB-WIN.csproj b/IOB-WIN/IOB-WIN.csproj index 380f56f9..e5525b54 100644 --- a/IOB-WIN/IOB-WIN.csproj +++ b/IOB-WIN/IOB-WIN.csproj @@ -151,6 +151,7 @@ + @@ -287,6 +288,12 @@ Always + + Always + + + Always + Always