diff --git a/MP-IO/Controllers/IOBController.cs b/MP-IO/Controllers/IOBController.cs index f4284443..257c52e3 100644 --- a/MP-IO/Controllers/IOBController.cs +++ b/MP-IO/Controllers/IOBController.cs @@ -13,15 +13,11 @@ namespace MP_IO.Controllers { #region Public Methods - /// - /// SALVA x macchina KVP parametro/valore: + /// SALVA x macchina KVP parametro/valore: /// /// GET: IOB/addOptPar/SIMUL_03?pName=PZREQ&pValue=1000 /// - /// - /// - /// - /// + /// public string addOptPar(string id, string pName, string pValue) { string answ = ""; @@ -39,8 +35,7 @@ namespace MP_IO.Controllers return answ; } - /// - /// AGGIUNGE TASK richiesto x macchina: + /// AGGIUNGE TASK richiesto x macchina: /// /// GET: IOB/addTask2Exe/3010?taskName=startSetup&taskVal=T190406101512 /// GET: IOB/addTask2Exe/3010?taskName=stopSetup&taskVal=T190406101512 @@ -48,10 +43,7 @@ namespace MP_IO.Controllers /// GET: IOB/addTask2Exe/SIMUL_03?taskName=setComm&taskVal=ODL_0000123 /// GET: IOB/addTask2Exe/SIMUL_03?taskName=setArt&taskVal=ART_0000321 /// - /// - /// - /// - /// + /// public string addTask2Exe(string id, string taskName, string taskVal) { string answ = ""; @@ -79,7 +71,6 @@ namespace MP_IO.Controllers return answ; } - // GET: IOB/enabled/SIMUL_03 public string enabled(string id) { @@ -106,90 +97,6 @@ namespace MP_IO.Controllers return answ; } - /// - /// Processa una chiamata POST per l'invio di un array Json di oggetti rawTransfer (generiche info da deserializzare) - /// POST: IOB/rawTransfJson/SIMUL_03 - /// - /// ID dell'IOB - /// - [HttpPost] - public string rawTransfJson(string id) - { - int insDone = 0; - string answ = ""; - // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... - string content = ""; - System.Web.HttpContext.Current.Request.InputStream.Position = 0; - using (var reader = new StreamReader( - Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) - { - content = reader.ReadToEnd(); - } - //Rest - System.Web.HttpContext.Current.Request.InputStream.Position = 0; - // se ho dati... - if (content != "") - { - DataLayer DataLayerObj = new DataLayer(); - // deserializzo come un dictionary generico di oggetti rawDataType/string - List receivedData = new List(); - // procedo a deserializzare in blocco l'oggetto... - try - { - // deserializzo. - receivedData = JsonConvert.DeserializeObject>(content); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in fase deserializzazione rawTransfJson{Environment.NewLine}{exc}"); - answ = "NO"; - } - // se ho qualcosa da processare... - if (receivedData != null) - { - try - { - foreach (var item in receivedData) - { - - // per ora salvo su REDIS ultimo x tipo - DataLayerObj.lastRawTrasfData = JsonConvert.SerializeObject(item.mesContent); - //DataLayerObj.lastRawTrasfData = item.mesContent; - - // !!! FixMe ToDo fare - // deserializzazione e salvataggio su MongoDB - // salvataggio su tab RawTrasf su DB IS - - // in base al tipo processo... - switch (item.mesType) - { - case rawTransfType.ND: - break; - case rawTransfType.IcoelBatch: - break; - case rawTransfType.IcoelVarInfo: - break; - default: - break; - } - insDone++; - } - // se vuoto --> OK! - if (string.IsNullOrEmpty(answ)) - { - answ = $"OK {insDone} processed"; - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in fase invio valori rawTransfJson{Environment.NewLine}{exc}"); - answ = "NO"; - } - } - } - return answ; - } - /// /// Processa una chiamata POST per l'invio di un array Json di oggetti input (EVENTI) /// POST: IOB/evListJson/SIMUL_03 @@ -353,7 +260,8 @@ namespace MP_IO.Controllers try { List currParams = DataLayerObj.getCurrObjItems(id); - // ora per ogni valore RICEVUTO costruisco un oggetto in innovazioni da inviare...x salvare in stato parametri... + // ora per ogni valore RICEVUTO costruisco un oggetto in innovazioni da + // inviare...x salvare in stato parametri... List innovazioni = new List(); foreach (var item in receivedData.fluxData) { @@ -365,7 +273,8 @@ namespace MP_IO.Controllers // aggiorno valore e data trovato.value = item.valore; trovato.lastRead = DateTime.Now; - // se fosse un valore WRITE e mi ha dato un valore vuoto --> mando un fix x riscrittura + // se fosse un valore WRITE e mi ha dato un valore vuoto --> mando + // un fix x riscrittura if (trovato.writable && string.IsNullOrEmpty(item.valore)) { logger.lg.scriviLog($"flogJson | verifica parametri | {trovato.uid} | reqVal: {trovato.reqValue}"); @@ -401,136 +310,36 @@ namespace MP_IO.Controllers return answ; } - - // GET: IOB/ulog/SIMUL_03?flux=PROG&valore=P0001&dtEve=20161223180600000&dtCurr=20161223180600000&cnt=999&matrOpr=0=0&label=&valNum - public string ulog(string id, string flux, string valore, string dtEve, string dtCurr, string cnt, string matrOpr, string label, string valNum) - { - string answ = ""; - // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi - if (cnt == null) - { - cnt = "0"; - } - - DateTime dataOraEvento = DateTime.Now; - if (memLayer.ML.CRI("_logLevel") > 6) - { - logger.lg.scriviLog($"ulog | Valori letti: idxMacchina: {id} | flux: {flux} valore: {valore} | matrOpr: {matrOpr} | label: {label} | valNum: {valNum}", tipoLog.INFO); - } - try - { - DataLayer DataLayerObj = new DataLayer(); - int count = 0; - int nMatrOpr = 0; - int nValNum = 0; - Int32.TryParse(cnt, out count); - Int32.TryParse(matrOpr, out nMatrOpr); - Int32.TryParse(valNum, out nValNum); - answ = DataLayerObj.processUserLog(id, flux, valore, dtEve, dtCurr, count, nMatrOpr, label, nValNum); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in ulog{Environment.NewLine}{exc}"); - answ = "NO"; - } - return answ; - } /// - /// Processa una chiamata POST per l'invio di una List Json 1+ UserAction (contiene controlli, scarti, dichiarazioni) - /// POST: IOB/ulogJson/SIMUL_03 - /// - /// ID dell'IOB - /// - [HttpPost] - public string ulogJson(string id) - { - int insDone = 0; - string answ = "-"; - // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... - string content = ""; - System.Web.HttpContext.Current.Request.InputStream.Position = 0; - using (var reader = new StreamReader( - Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) - { - content = reader.ReadToEnd(); - } - //Rest - System.Web.HttpContext.Current.Request.InputStream.Position = 0; - // se ho dati... - if (content != "") - { - DataLayer DataLayerObj = new DataLayer(); - // procedo a deserializzare in blocco l'oggetto... - ulogJsonPayload receivedData = new ulogJsonPayload(); - try - { - // deserializzo. - receivedData = JsonConvert.DeserializeObject(content); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in fase deserializzazione ulogJson{Environment.NewLine}{exc}"); - answ = "NO"; - } - // se ho qualcosa da processare... - if (receivedData != null) - { - // per ogni valore --> salvo! - try - { - foreach (var item in receivedData.fluxData) - { - // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000 - answ = DataLayerObj.processUserLog(id, item.flux, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt, item.matrOpr, item.label, item.valNum); - } - // se vuoto --> OK! - if (string.IsNullOrEmpty(answ)) - { - answ = $"OK {insDone} processed"; - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in fase invio valori ulogJson{Environment.NewLine}{exc}"); - answ = "NO"; - } - } - } - return answ; - - } - - /// - /// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità RIMANENTE), e CONFERMA produzione... + /// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità RIMANENTE), + /// e CONFERMA produzione... /// /// GET: IOB/forceSplitOdl/SIMUL_03 - /// /// /// /// Esito chiamata (OK/vuoto) public string forceSplitOdl(string id) { - // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); DataLayer DataLayerObj = new DataLayer(); return DataLayerObj.AutoStartOdl(id, true, true, 100, ""); } - /// - /// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità RIMANENTE), e CONFERMA produzione... + /// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità + /// RIMANENTE), e CONFERMA produzione... /// /// GET: IOB/forceSplitOdl/SIMUL_03?doConfirm=true&qtyFromLast=true&roundStep=150&extOrderCode=ABCDE1234 /// - /// - /// id impianto - /// - /// - /// - /// Cod esterno da legare all'ODL x tracciare lotti prod + /// id impianto Cod esterno da legare all'ODL x tracciare lotti prod /// Esito chiamata (OK/vuoto) public string forceSplitOdlFull(string id, bool doConfirm, bool qtyFromLast, int? roundStep, string keyRichiesta = "") { - // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); DataLayer DataLayerObj = new DataLayer(); if (roundStep == null) @@ -544,7 +353,6 @@ namespace MP_IO.Controllers /// Recupera COUNTER x macchina: /// /// GET: IOB/getCounter/5 - /// /// /// /// @@ -568,7 +376,6 @@ namespace MP_IO.Controllers /// Recupera COUNTER x macchina dal CONTEGGIO dei TCRecorded: /// /// GET: IOB/getCounterTCRec/5 - /// /// /// /// @@ -592,13 +399,13 @@ namespace MP_IO.Controllers /// Recupera DATI correnti x macchina: /// /// GET: IOB/getCurrData/SIMUL_03 - /// /// /// /// Json contenente la riga di stato macchina public string getCurrData(string id) { - // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); string answ = ""; // scrivo keep alive!!! (se necessario, altrimenti è in cache...) @@ -620,13 +427,13 @@ namespace MP_IO.Controllers /// Recupera ODL corrente x macchina: /// /// GET: IOB/getCurrODL/SIMUL_03 - /// /// /// /// public string getCurrODL(string id) { - // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); string answ = ""; try @@ -650,7 +457,8 @@ namespace MP_IO.Controllers /// public string getCurrOdlRow(string id) { - // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); string answ = ""; DS_ProdTempi.ODLDataTable currData = null; @@ -676,7 +484,8 @@ namespace MP_IO.Controllers /// public string getCurrOdlStart(string id) { - // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); DateTime answ = new DateTime(DateTime.Now.Year - 1, 12, 31); // chiamo metodo redis/db... @@ -705,7 +514,8 @@ namespace MP_IO.Controllers /// public string getCurrStatoRow(string id) { - // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); string answ = ""; DS_applicazione.StatoMacchineDataTable currData = null; @@ -764,14 +574,16 @@ namespace MP_IO.Controllers } /// - /// Restituisce il valore dello stato di IDLE della macchina, quindi SOLO SE NON é in lavoro e già convertito in minuti... + /// Restituisce il valore dello stato di IDLE della macchina, quindi SOLO SE NON é in lavoro + /// e già convertito in minuti... /// GET: IOB/getIdlePeriod/SIMUL_01 /// /// /// public int getIdlePeriod(string id) { - // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il carattere "|" che poi trasformiamo ora in "#" + // attenzione! poiché nell'URL il carattere "#" fiene filtrato ci aspettiamo il + // carattere "|" che poi trasformiamo ora in "#" id = id.Replace("|", "#"); int answ = 0; DataLayer DataLayerObj = new DataLayer(); @@ -801,7 +613,8 @@ namespace MP_IO.Controllers } /// - /// Restituisce il (primo) codice IOB da dover gestire (se un IOBMAN chiede di gestirne uno in +...) + /// Restituisce il (primo) codice IOB da dover gestire (se un IOBMAN chiede di gestirne uno + /// in +...) /// /// IP del Gateway /// @@ -809,7 +622,8 @@ namespace MP_IO.Controllers { string answ = ""; - // !!!FARE!!! temporanemanete genera a caso vuoto o 3000 x permettere test... altrimenti gestisce VERA coda... secondi pari... + // !!!FARE!!! temporanemanete genera a caso vuoto o 3000 x permettere test... altrimenti + // gestisce VERA coda... secondi pari... int resto = 0; Math.DivRem(DateTime.Now.Second, 2, out resto); if (resto == 0) @@ -888,7 +702,8 @@ namespace MP_IO.Controllers } /// - /// restituisce elenco parametri CHE RICHIEDONO scrittura su PLC come una List Json di oggetti objItem + /// restituisce elenco parametri CHE RICHIEDONO scrittura su PLC come una List Json di + /// oggetti objItem /// GET: IOB/getObjItems2Write/SIMUL_03 /// /// ID dell'IOB @@ -928,7 +743,6 @@ namespace MP_IO.Controllers /// Recupera TASK richiesto x macchina: /// /// GET: IOB/getOptPar/SIMUL_03 - /// /// /// /// Json contenente 1..n task da eseguire @@ -954,7 +768,6 @@ namespace MP_IO.Controllers /// Recupera TASK richiesto x macchina: /// /// GET: IOB/getTask2Exe/SIMUL_03 - /// /// /// /// Json contenente 1..n task da eseguire @@ -1087,11 +900,96 @@ namespace MP_IO.Controllers return answ; } + /// + /// Processa una chiamata POST per l'invio di un array Json di oggetti rawTransfer + /// (generiche info da deserializzare) + /// POST: IOB/rawTransfJson/SIMUL_03 + /// + /// ID dell'IOB + /// + [HttpPost] + public string rawTransfJson(string id) + { + int insDone = 0; + string answ = ""; + // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... + string content = ""; + System.Web.HttpContext.Current.Request.InputStream.Position = 0; + using (var reader = new StreamReader( + Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) + { + content = reader.ReadToEnd(); + } + //Rest + System.Web.HttpContext.Current.Request.InputStream.Position = 0; + // se ho dati... + if (content != "") + { + DataLayer DataLayerObj = new DataLayer(); + // deserializzo come un dictionary generico di oggetti rawDataType/string + List receivedData = new List(); + // procedo a deserializzare in blocco l'oggetto... + try + { + // deserializzo. + receivedData = JsonConvert.DeserializeObject>(content); + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in fase deserializzazione rawTransfJson{Environment.NewLine}{exc}"); + answ = "NO"; + } + // se ho qualcosa da processare... + if (receivedData != null) + { + try + { + foreach (var item in receivedData) + { + // per ora salvo su REDIS ultimo x tipo + DataLayerObj.lastRawTrasfData = JsonConvert.SerializeObject(item.mesContent); + //DataLayerObj.lastRawTrasfData = item.mesContent; + + // !!! FixMe ToDo fare deserializzazione e salvataggio su MongoDB + // salvataggio su tab RawTrasf su DB IS + + // in base al tipo processo... + switch (item.mesType) + { + case rawTransfType.ND: + break; + + case rawTransfType.IcoelBatch: + break; + + case rawTransfType.IcoelVarInfo: + break; + + default: + break; + } + insDone++; + } + // se vuoto --> OK! + if (string.IsNullOrEmpty(answ)) + { + answ = $"OK {insDone} processed"; + } + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in fase invio valori rawTransfJson{Environment.NewLine}{exc}"); + answ = "NO"; + } + } + } + return answ; + } + /// /// ELIMINA TASK richiesto x macchina: /// /// GET: IOB/remOptPar/SIMUL_03?pName=PZREQ - /// /// /// /// @@ -1116,7 +1014,6 @@ namespace MP_IO.Controllers /// ELIMINA TASK richiesto x macchina: /// /// GET: IOB/remTask2Exe/SIMUL_03?taskName=T180326160502 - /// /// /// /// @@ -1151,7 +1048,6 @@ namespace MP_IO.Controllers /// Effettua RESET dell'ODL corrente x macchina: /// /// GET: IOB/resetCurrODL/5 - /// /// /// /// @@ -1177,7 +1073,8 @@ namespace MP_IO.Controllers } else { - // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... + // questa classe è derivata da Controller.Response... x cui recupero lo stream in + // altro modo... string content = ""; System.Web.HttpContext.Current.Request.InputStream.Position = 0; using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) @@ -1207,7 +1104,8 @@ namespace MP_IO.Controllers } /// - /// Processa una chiamata POST per l'invio di un array Json di oggetti di conf DataItems (es per MTC) + /// Processa una chiamata POST per l'invio di un array Json di oggetti di conf DataItems (es + /// per MTC) /// PUT: IOB/saveDataItems/SIMUL_03 /// /// ID dell'IOB @@ -1223,7 +1121,8 @@ namespace MP_IO.Controllers } else { - // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... + // questa classe è derivata da Controller.Response... x cui recupero lo stream in + // altro modo... string content = ""; System.Web.HttpContext.Current.Request.InputStream.Position = 0; using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) @@ -1256,10 +1155,10 @@ namespace MP_IO.Controllers } /// - /// SALVA in blocco un incremento pezzi x macchina restituendo il valore appena inviato o, se mancasse chaive redis, del valore da DB + /// SALVA in blocco un incremento pezzi x macchina restituendo il valore appena inviato o, + /// se mancasse chaive redis, del valore da DB /// /// GET: IOB/savePzCountInc/5?qty=10 - /// /// /// codice macchina /// num peziz da salvare in blocco @@ -1291,10 +1190,8 @@ namespace MP_IO.Controllers /// /// [HttpPost] - //public string sendAlarmBankUpdate(string id) public string sendAlarmBankUpdate(string id, string memAddr, int index, int currStatus) { - DataLayer DataLayerObj = new DataLayer(); // esempio valido x MAPO string answ = ""; @@ -1305,7 +1202,8 @@ namespace MP_IO.Controllers } else { - // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... + // questa classe è derivata da Controller.Response... x cui recupero lo stream in + // altro modo... string content = ""; System.Web.HttpContext.Current.Request.InputStream.Position = 0; using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) @@ -1340,16 +1238,11 @@ namespace MP_IO.Controllers return answ; // esempio GWMS - } - - /// - /// Salva MAC adress + IP dopo il reboot - /// GET: IOB/sendReboot?idxMacchina=5&mac=18:C0:4D:37:3C:8C - /// - /// IP del Gateway - /// + /// Salva MAC adress + IP dopo il reboot + /// GET: IOB/sendReboot?idxMacchina=5&mac=18:C0:4D:37:3C:8C IP + /// del Gateway public string sendReboot(string idxMacchina, string mac) { string answ = "NO"; @@ -1396,10 +1289,10 @@ namespace MP_IO.Controllers } /// - /// SALVA Counter x macchina restituendo il valore appena inviato o, se mancasse chiave redis, del valore da DB + /// SALVA Counter x macchina restituendo il valore appena inviato o, se mancasse chiave + /// redis, del valore da DB /// /// GET: IOB/setCounter/5?counter=10 - /// /// /// cod macchina /// contapezzi da salvare @@ -1490,7 +1383,8 @@ namespace MP_IO.Controllers } else { - // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... + // questa classe è derivata da Controller.Response... x cui recupero lo stream in + // altro modo... string content = ""; System.Web.HttpContext.Current.Request.InputStream.Position = 0; using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) @@ -1548,6 +1442,125 @@ namespace MP_IO.Controllers return answ; } + //[HttpPost] + //public string takeFlogSnapshot(string id, int maxSec) + //{ + // string answ = ""; + // string caller = "takeFlogSnapshot(id)"; + + // answ = doSaveFLSnapshot(id, maxSec, caller); + // return answ; + //} + + [HttpPost] + public string takeFlogSnapshot(string id) + { + string answ = ""; + string caller = "takeFlogSnapshot(id)"; + + answ = doSaveFLSnapshot(id, 10, caller); + return answ; + } + + // GET: IOB/ulog/SIMUL_03?flux=PROG&valore=P0001&dtEve=20161223180600000&dtCurr=20161223180600000&cnt=999&matrOpr=0=0&label=&valNum + public string ulog(string id, string flux, string valore, string dtEve, string dtCurr, string cnt, string matrOpr, string label, string valNum) + { + string answ = ""; + // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi + if (cnt == null) + { + cnt = "0"; + } + + DateTime dataOraEvento = DateTime.Now; + if (memLayer.ML.CRI("_logLevel") > 6) + { + logger.lg.scriviLog($"ulog | Valori letti: idxMacchina: {id} | flux: {flux} valore: {valore} | matrOpr: {matrOpr} | label: {label} | valNum: {valNum}", tipoLog.INFO); + } + try + { + DataLayer DataLayerObj = new DataLayer(); + int count = 0; + int nMatrOpr = 0; + int nValNum = 0; + Int32.TryParse(cnt, out count); + Int32.TryParse(matrOpr, out nMatrOpr); + Int32.TryParse(valNum, out nValNum); + answ = DataLayerObj.processUserLog(id, flux, valore, dtEve, dtCurr, count, nMatrOpr, label, nValNum); + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in ulog{Environment.NewLine}{exc}"); + answ = "NO"; + } + return answ; + } + + /// + /// Processa una chiamata POST per l'invio di una List Json 1+ UserAction (contiene + /// controlli, scarti, dichiarazioni) + /// POST: IOB/ulogJson/SIMUL_03 + /// + /// ID dell'IOB + /// + [HttpPost] + public string ulogJson(string id) + { + int insDone = 0; + string answ = "-"; + // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... + string content = ""; + System.Web.HttpContext.Current.Request.InputStream.Position = 0; + using (var reader = new StreamReader( + Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) + { + content = reader.ReadToEnd(); + } + //Rest + System.Web.HttpContext.Current.Request.InputStream.Position = 0; + // se ho dati... + if (content != "") + { + DataLayer DataLayerObj = new DataLayer(); + // procedo a deserializzare in blocco l'oggetto... + ulogJsonPayload receivedData = new ulogJsonPayload(); + try + { + // deserializzo. + receivedData = JsonConvert.DeserializeObject(content); + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in fase deserializzazione ulogJson{Environment.NewLine}{exc}"); + answ = "NO"; + } + // se ho qualcosa da processare... + if (receivedData != null) + { + // per ogni valore --> salvo! + try + { + foreach (var item in receivedData.fluxData) + { + // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000 + answ = DataLayerObj.processUserLog(id, item.flux, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt, item.matrOpr, item.label, item.valNum); + } + // se vuoto --> OK! + if (string.IsNullOrEmpty(answ)) + { + answ = $"OK {insDone} processed"; + } + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in fase invio valori ulogJson{Environment.NewLine}{exc}"); + answ = "NO"; + } + } + } + return answ; + } + /// /// Processa una chiamata POST per l'invio di un SET di file "a nome" di un IOB, formato MapoSDK.fileEmbed /// PUT: IOB/uploadFile/SIMUL_03 @@ -1608,7 +1621,8 @@ namespace MP_IO.Controllers } else { - // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo... + // questa classe è derivata da Controller.Response... x cui recupero lo stream in + // altro modo... string content = ""; System.Web.HttpContext.Current.Request.InputStream.Position = 0; using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true)) @@ -1641,7 +1655,39 @@ namespace MP_IO.Controllers return answ; } - #endregion Public Methods + + #region Private Methods + + /// + /// Effettua vera chiamata x salvataggio snapshot dati FluxLog + /// + /// + /// + /// + /// + private static string doSaveFLSnapshot(string id, int maxSec, string caller) + { + string answ; + DateTime dataOraEvento = DateTime.Now; + if (memLayer.ML.CRI("_logLevel") > 6) + { + logger.lg.scriviLog($"{caller} | Richiesta snapshot dati FluxLog macchina: idxMacchina: {id} ", tipoLog.INFO); + } + try + { + DataLayer DataLayerObj = new DataLayer(); + answ = DataLayerObj.takeFlogSnapshot(id, maxSec); + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in {caller}{Environment.NewLine}{exc}"); + answ = "NO"; + } + + return answ; + } + + #endregion Private Methods } } \ No newline at end of file diff --git a/MP-SITE/excelExportEventi.aspx.designer.cs b/MP-SITE/excelExportEventi.aspx.designer.cs index 574f0069..2e098517 100644 --- a/MP-SITE/excelExportEventi.aspx.designer.cs +++ b/MP-SITE/excelExportEventi.aspx.designer.cs @@ -1,32 +1,34 @@ //------------------------------------------------------------------------------ -// -// Codice generato da uno strumento. +// +// This code was generated by a tool. // -// Le modifiche a questo file possono causare un comportamento non corretto e verranno perse se -// il codice viene rigenerato. -// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// //------------------------------------------------------------------------------ namespace MP_SITE { + + public partial class excelExportEventi { /// - /// Controllo gvEventi. + /// gvEventi control. /// /// - /// Campo generato automaticamente. - /// Per la modifica, spostare la dichiarazione di campo dal file di progettazione al file code-behind. + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.GridView gvEventi; /// - /// Controllo ods_EventList. + /// ods_EventList control. /// /// - /// Campo generato automaticamente. - /// Per la modifica, spostare la dichiarazione di campo dal file di progettazione al file code-behind. + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ObjectDataSource ods_EventList; } diff --git a/MP-SITE/excelExportStati.aspx b/MP-SITE/excelExportStati.aspx index aecbe9dd..f39c6d25 100644 --- a/MP-SITE/excelExportStati.aspx +++ b/MP-SITE/excelExportStati.aspx @@ -8,7 +8,7 @@ - diff --git a/MP-SITE/excelExportStati.aspx.designer.cs b/MP-SITE/excelExportStati.aspx.designer.cs index ad01f662..c5100874 100644 --- a/MP-SITE/excelExportStati.aspx.designer.cs +++ b/MP-SITE/excelExportStati.aspx.designer.cs @@ -1,10 +1,10 @@ //------------------------------------------------------------------------------ -// -// Codice generato da uno strumento. +// +// This code was generated by a tool. // -// Le modifiche a questo file possono causare un comportamento non corretto e verranno perse se -// il codice viene rigenerato. -// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// //------------------------------------------------------------------------------ namespace MP_SITE @@ -15,20 +15,20 @@ namespace MP_SITE { /// - /// Controllo gvStati. + /// gvStati control. /// /// - /// Campo generato automaticamente. - /// Per la modifica, spostare la dichiarazione di campo dal file di progettazione al file code-behind. + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.GridView gvStati; /// - /// Controllo ods_DiarioDiBordo. + /// ods_DiarioDiBordo control. /// /// - /// Campo generato automaticamente. - /// Per la modifica, spostare la dichiarazione di campo dal file di progettazione al file code-behind. + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ObjectDataSource ods_DiarioDiBordo; } diff --git a/MP-Site/Web.config b/MP-Site/Web.config index be7e37af..37e6dd72 100644 --- a/MP-Site/Web.config +++ b/MP-Site/Web.config @@ -30,16 +30,16 @@ - - - - - + + + + + - - - + + + diff --git a/MapoDb/DS_applicazione.Designer.cs b/MapoDb/DS_applicazione.Designer.cs index ea2d0bba..f62bc355 100644 --- a/MapoDb/DS_applicazione.Designer.cs +++ b/MapoDb/DS_applicazione.Designer.cs @@ -28802,7 +28802,7 @@ SELECT IdxMacchina, dtEvento, CodFlux, Valore, Cnt FROM FluxLog WHERE (CodFlux = [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "17.0.0.0")] private void InitCommandCollection() { - this._commandCollection = new global::System.Data.SqlClient.SqlCommand[6]; + this._commandCollection = new global::System.Data.SqlClient.SqlCommand[7]; this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); this._commandCollection[0].Connection = this.Connection; this._commandCollection[0].CommandText = "SELECT * FROM dbo.FluxLog"; @@ -28858,6 +28858,13 @@ SELECT IdxMacchina, dtEvento, CodFlux, Valore, Cnt FROM FluxLog WHERE (CodFlux = this._commandCollection[5].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@CodFlux", global::System.Data.SqlDbType.NVarChar, 50, global::System.Data.ParameterDirection.Input, 0, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._commandCollection[5].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Valore", global::System.Data.SqlDbType.NVarChar, 250, global::System.Data.ParameterDirection.Input, 0, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._commandCollection[5].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Count", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 10, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._commandCollection[6] = new global::System.Data.SqlClient.SqlCommand(); + this._commandCollection[6].Connection = this.Connection; + this._commandCollection[6].CommandText = "dbo.stp_FL_TakeSnapshot"; + this._commandCollection[6].CommandType = global::System.Data.CommandType.StoredProcedure; + this._commandCollection[6].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@RETURN_VALUE", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.ReturnValue, 10, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._commandCollection[6].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IdxMacchina", global::System.Data.SqlDbType.NVarChar, 50, global::System.Data.ParameterDirection.Input, 0, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); + this._commandCollection[6].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@MaxSec", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 10, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] @@ -29302,6 +29309,40 @@ SELECT IdxMacchina, dtEvento, CodFlux, Valore, Cnt FROM FluxLog WHERE (CodFlux = } return returnValue; } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "17.0.0.0")] + [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] + public virtual int takeSnapshot(string IdxMacchina, global::System.Nullable MaxSec) { + global::System.Data.SqlClient.SqlCommand command = this.CommandCollection[6]; + if ((IdxMacchina == null)) { + command.Parameters[1].Value = global::System.DBNull.Value; + } + else { + command.Parameters[1].Value = ((string)(IdxMacchina)); + } + if ((MaxSec.HasValue == true)) { + command.Parameters[2].Value = ((int)(MaxSec.Value)); + } + else { + command.Parameters[2].Value = global::System.DBNull.Value; + } + global::System.Data.ConnectionState previousConnectionState = command.Connection.State; + if (((command.Connection.State & global::System.Data.ConnectionState.Open) + != global::System.Data.ConnectionState.Open)) { + command.Connection.Open(); + } + int returnValue; + try { + returnValue = command.ExecuteNonQuery(); + } + finally { + if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { + command.Connection.Close(); + } + } + return returnValue; + } } /// diff --git a/MapoDb/DS_applicazione.xsd b/MapoDb/DS_applicazione.xsd index b1ee7546..1d3d9084 100644 --- a/MapoDb/DS_applicazione.xsd +++ b/MapoDb/DS_applicazione.xsd @@ -2611,6 +2611,18 @@ SELECT IdxMacchina, dtEvento, CodFlux, Valore, Cnt FROM FluxLog WHERE (CodFlux = + + + + dbo.stp_FL_TakeSnapshot + + + + + + + + @@ -2918,7 +2930,7 @@ FROM v_AlarmLog - + dbo.stp_AL_getFiltCount @@ -2950,7 +2962,7 @@ FROM v_AlarmLog - + dbo.stp_AL_insertQuery @@ -3004,22 +3016,22 @@ FROM v_AlarmLog - + - + - - + + @@ -3032,107 +3044,107 @@ FROM v_AlarmLog - + - + - + - + - + - + - + - + - - + + - - - - + + + + - + - - - + + + - - - - + + + + - + @@ -3145,61 +3157,61 @@ FROM v_AlarmLog - - + + - + - - + + - + - + - - - + + + - - + + - + @@ -3212,8 +3224,8 @@ FROM v_AlarmLog - - + + @@ -3226,35 +3238,35 @@ FROM v_AlarmLog - + - - - - - + + + + + - - - - + + + + - + @@ -3267,29 +3279,29 @@ FROM v_AlarmLog - + - + - - + + - + @@ -3302,24 +3314,24 @@ FROM v_AlarmLog - + - - - + + + - - + + @@ -3332,8 +3344,8 @@ FROM v_AlarmLog - - + + @@ -3346,34 +3358,34 @@ FROM v_AlarmLog - - - - - + + + + + - - + + - + - - + + @@ -3386,15 +3398,15 @@ FROM v_AlarmLog - - + + - + @@ -3407,52 +3419,52 @@ FROM v_AlarmLog - - - + + + - - - - - - + + + + + + - + - - + + - + - - - + + + @@ -3465,30 +3477,30 @@ FROM v_AlarmLog - - + + - - + + - + - + @@ -3501,30 +3513,30 @@ FROM v_AlarmLog - - + + - + - + - - + + @@ -3537,77 +3549,77 @@ FROM v_AlarmLog - + - - - - + + + + - + - - - + + + - + - - + + - + - + - + - + - - + + @@ -3620,73 +3632,73 @@ FROM v_AlarmLog - + - + - - + + - + - - - - - - - - - - - - - - + + + + + + + + + + + + + + - + - - - - + + + + - + @@ -3696,89 +3708,89 @@ FROM v_AlarmLog - + - + - - + + - + - + - + - + - + - + - + - + - + - + - - + + @@ -3788,41 +3800,41 @@ FROM v_AlarmLog - + - - - + + + - + - - + + - + - + @@ -3832,46 +3844,46 @@ FROM v_AlarmLog - + - - - - + + + + - + - - - + + + - - + + - - - + + + @@ -4008,33 +4020,33 @@ FROM v_AlarmLog - + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MapoDb/DS_applicazione.xss b/MapoDb/DS_applicazione.xss index 0af29da3..7c726c10 100644 --- a/MapoDb/DS_applicazione.xss +++ b/MapoDb/DS_applicazione.xss @@ -4,7 +4,7 @@ Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. --> - + diff --git a/MapoDb/DataLayer.cs b/MapoDb/DataLayer.cs index f4e326ac..fe85fa4b 100644 --- a/MapoDb/DataLayer.cs +++ b/MapoDb/DataLayer.cs @@ -1,13 +1,13 @@ -using System; +using MapoSDK; +using Newtonsoft.Json; +using SteamWare; +using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Reflection; using System.Threading; -using MapoSDK; -using Newtonsoft.Json; -using SteamWare; namespace MapoDb { @@ -16,15 +16,6 @@ namespace MapoDb /// public class DataLayer { - #region Protected Fields - - /// - /// indica conferma con rettifica (evento 121) - /// - protected bool confRett = memLayer.ML.CRB("confRett"); - - #endregion Protected Fields - #region Public Fields /// @@ -36,60 +27,115 @@ namespace MapoDb public DS_applicazioneTableAdapters.AnagraficaGruppiTableAdapter taAG; public DS_applicazioneTableAdapters.AlarmLogTableAdapter taAlarmLog; + public DS_ProdTempiTableAdapters.AnagArticoliTableAdapter taAnagArt; + public DS_applicazioneTableAdapters.AnagraficaEventiTableAdapter taAnagEventi; + public DS_applicazioneTableAdapters.AnagraficaStatiTableAdapter taAnagStati; + public DS_applicazioneTableAdapters.AnagTagsTableAdapter taAnagTags; + public DS_ArcaTableAdapters.GiacenzeTableAdapter taArcaGiac; + public DS_IntServTableAdapters.ProduzioneAs400TableAdapter taAs400; + public DS_ProdTempiTableAdapters.CalendFesteFerieTableAdapter taCalFF; + public DS_UtilityTableAdapters.CommentiTableAdapter taComm; + public DS_ProdTempiTableAdapters.DatiConfermatiTableAdapter taDatiConf; + public DS_ProdTempiTableAdapters.DatiMacchineTableAdapter taDatiMacchine; + public DS_ProdTempiTableAdapters.DatiProduzioneTableAdapter taDatiProd; + public DS_ProdTempiTableAdapters.stp_repDonati_getDatiProdMacchinaTableAdapter taDatiProdMacch; + public DS_ProdTempiTableAdapters.stp_repDonati_getDatiProdMacchinaPeriodoTableAdapter taDatiProdMacchPer; + public DS_ProdTempiTableAdapters.stp_repDonati_getLastStatoDurataMacchinaTableAdapter taDatiStatoMacch; + public DS_applicazioneTableAdapters.DiarioDichiarazioniTableAdapter taDiarioDich; + public DS_applicazioneTableAdapters.EventListTableAdapter taEventi; + public DS_applicazioneTableAdapters.FluxLogTableAdapter taFL; + public DS_IntServTableAdapters.TransitoDatiTableAdapter taIS_TrDati; + public DS_IntServTableAdapters.IstanzeKITTableAdapter taIstK; + public DS_applicazioneTableAdapters.KeepAliveTableAdapter taKeepAlive; + public DS_ProdTempiTableAdapters.Macchine2SlaveTableAdapter taM2S; + public DS_applicazioneTableAdapters.MacchineTableAdapter taMacchine; + public DS_PlanTableAdapters.MachineParamsTableAdapter taMacParams; + public DS_MAGTableAdapters.ElencoLottiTableAdapter taMagELotti; + public DS_ProdTempiTableAdapters.MappaStatoExplTableAdapter taMSE; + public DS_ProdTempiTableAdapters.ODLTableAdapter taODL; + public DS_applicazioneTableAdapters.AnagraficaOperatoriTableAdapter taOp; + public DS_applicazioneTableAdapters.AnagraficaOperatori2insTableAdapter taOp2ins; + public DS_PlanTableAdapters.CalDispTableAdapter taPlanCalDisp; + public DS_PlanTableAdapters.CalStopTableAdapter taPlanCalStop; + public DS_PlanTableAdapters.RichiesteTableAdapter taPlanRichieste; + public DS_ProdTempiTableAdapters.PromesseODLTableAdapter taPODL; + public DS_ProdTempiTableAdapters.PostazioniMapoTableAdapter taPostazioni; + public DS_PlanTableAdapters.PromesseINTableAdapter taPromIn; + public DS_PlanTableAdapters.PromesseOUTTableAdapter taPromOut; + public DS_ProdTempiTableAdapters.stp_PzProd_getByMacchinaTableAdapter taPzProd2conf; + public DS_ProdTempiTableAdapters.RegistroControlliTableAdapter taRC; + public DS_applicazioneTableAdapters.RemoteRebootLogTableAdapter taRemReb; + public DS_ProdTempiTableAdapters.RegistroScartiTableAdapter taRS; + public DS_UtilityTableAdapters.v_selArticoliTableAdapter taSelArt; + public DS_UtilityTableAdapters.v_selMacchineTableAdapter taSelMacc; + public DS_UtilityTableAdapters.v_selODLTableAdapter taSelOdlFree; + public DS_applicazioneTableAdapters.SignalLogTableAdapter taSigLog; + public DS_SheetTechTableAdapters.ST_ActualTableAdapter taSTA; + public DS_SheetTechTableAdapters.ST_ActualRowTableAdapter taSTAR; + public DS_applicazioneTableAdapters.DiarioDiBordoTableAdapter taStati; + public DS_applicazioneTableAdapters.StatoMacchineTableAdapter taStatoMacchine; + public DS_ProdTempiTableAdapters.StatoProdTableAdapter taStatoProd; + public DS_SheetTechTableAdapters.ST_CheckTableAdapter taSTChk; + public DS_ProdTempiTableAdapters.TempiCicloRilevatiTableAdapter taTempiCicloRilevati; + public DS_ProdTempiTableAdapters.stp_TempoByIdxMaccPeriodClassTableAdapter taTempoByClass; + public DS_IntServTableAdapters.TKS_SearchTableAdapter taTKS; + public DS_applicazioneTableAdapters.TransizioneIngressiTableAdapter taTranIngr; + public DS_ProdTempiTableAdapters.TurniMacchinaTableAdapter taTurniMacc; + public DS_IntServTableAdapters.WipSetupKitTableAdapter taWKS; #endregion Public Fields @@ -128,16 +174,17 @@ namespace MapoDb { get => mHash($"CACHE:CheckArtUsed"); } - public static string redKeyTabCheckArt - { - get => mHash($"CACHE:TabCheckArt"); - } public static string redKeyRawTransfData { get => mHash($"RAW:TRANSFER"); } + public static string redKeyTabCheckArt + { + get => mHash($"CACHE:TabCheckArt"); + } + /// /// Cognome Nome da MatrOpr in sessione /// @@ -176,7 +223,6 @@ namespace MapoDb } } - /// /// Dati RawTransfer serializzati in REDIS (get/set) /// @@ -218,440 +264,6 @@ namespace MapoDb #endregion Public Properties - #region Private Methods - - private static T ConvertDataRowToGenericType(DataRow row) where T : class, new() - { - Type entityType = typeof(T); - T objEntity = new T(); - foreach (DataColumn column in row.Table.Columns) - { - object value = row[column.ColumnName]; - if (value == DBNull.Value) value = null; - PropertyInfo property = entityType.GetProperty(column.ColumnName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public); - try - { - if (property != null && property.CanWrite) - property.SetValue(objEntity, value, null); - } - catch (Exception ex) - { - throw ex; - } - } - return objEntity; - } - - /// - /// registra su REDIS eventuale superamento numero limite di call x il metodo in oggetto - /// - /// - private static void saveCallRec(string callCountKey) - { - // conto la richiesta nel contatore REDIS - long nCall = memLayer.ML.setRCntI(mHash($"COUNT:pCall:{callCountKey}")); - //... se == nCall2Log scrivo su log e resetto - long nCall2Log = memLayer.ML.cdvi("nCall2Log"); - if (nCall >= nCall2Log) - { - // loggo - logger.lg.scriviLog($"{callCountKey}: {nCall} call received", tipoLog.INFO); - // resetto! - memLayer.ML.resetRCnt(mHash($"COUNT:pCall:{callCountKey}")); - } - } - - /// - /// verifica se sia necessario inserire un cambio di stato impianto in modalità batch - /// - /// - /// - /// - /// - /// - /// - /// - /// - private void checkCambiaStatoBatch(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet) - { - int _logLevel = memLayer.ML.CRI("_logLevel"); - DS_applicazione.TransizioneStatiDataTable tabTransStati; - DS_applicazione.TransizioneStatiRow rigaTransStati; - switch (tipoInput) - { - case tipoInputEvento.barcode: - // effettuo cambio stato INDIPENDENTEMENTE da stato precedente - try - { - tabTransStati = MapoDbObj.taTranSt.GetUserForcedTransitions(IdxMacchina, IdxTipo); - if (tabTransStati != null) - { - if (tabTransStati.Count > 0) - { - rigaTransStati = tabTransStati[0]; - // solo se cambia stato... - if (rigaTransStati.IdxStato != rigaTransStati.next_IdxStato) - { - MapoDbObj.taDiario.InsStatoBatch(IdxMacchina, InizioStato, rigaTransStati.next_IdxStato, CodArt, Value, MatrOpr, pallet); - // aggiorno MSE - taMSE.forceRecalc(0, IdxMacchina); - } - } - else - { - if (_logLevel > 6) - { - logger.lg.scriviLog($"Non trovata riga per: BARCODE | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}", tipoLog.INFO); - } - } - } - } - catch (Exception exc) - { - // non dovrebbe succedere... input utente da barcode dovrebbero TUTTI essere inseriti in tab transizione con famiglia 1... - logger.lg.scriviLog($"Errore controllo transizione stato x evento barcode: BARCODE | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - } - break; - - case tipoInputEvento.hw: - // verifico se ci sia necessità di cambio stato - try - { - tabTransStati = MapoDbObj.taTranSt.GetHwTransitions(IdxMacchina, IdxTipo); - if (tabTransStati != null) - { - if (tabTransStati.Count > 0) - { - rigaTransStati = tabTransStati[0]; - if (rigaTransStati != null) - { - // solo se cambia stato... - if (rigaTransStati.IdxStato != rigaTransStati.next_IdxStato) - { - MapoDbObj.taDiario.InsStatoBatch(IdxMacchina, InizioStato, rigaTransStati.next_IdxStato, CodArt, Value, MatrOpr, pallet); - } - } - } - else - { - if (_logLevel > 6) - { - logger.lg.scriviLog($"Non trovata riga per: HW | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}", tipoLog.INFO); - } - } - } - } - catch (Exception exc) - { - // non trovo riga [0]... NON scrivo! - logger.lg.scriviLog($"Errore controllo transizione stato x evento barcode: HW | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - } - break; - } - } - - /// - /// sistemazione timeout comandi nei tableadapter - /// - private void fixCommandTimeout() - { - int sqlLongCommandTimeout = memLayer.ML.CRI("sqlLongCommandTimeout") > 1 ? memLayer.ML.CRI("sqlLongCommandTimeout") : 300; - SetAllCommandTimeouts(taComm, sqlLongCommandTimeout); - } - - /// - /// Recupero dati stato prod da macchina... - /// - /// - /// - /// - /// - private bool getStatoProd(string idxMacchina, ref DS_ProdTempi.StatoProdDataTable datiProdAct, DateTime dataRif) - { - bool answ = false; - try - { - // recupero con stored NUOVA... - //2020.01.31 NUOVO oggetto (NON singleton) - DataLayer man = new DataLayer(); - datiProdAct = man.taStatoProd.GetData(idxMacchina, dataRif); - if (datiProdAct.Rows.Count > 0) - { - // solo SE ho idxODL (altrimenti loggo errore) - if (datiProdAct[0].IdxOdl > 0) - { - answ = true; - } - else - { - // verifico se ho già questo errore attivo IN REDIS (altrimenti reinvio) - logger.lg.scriviLog($"pzCounterTC: Non trovato currODL x idxMacchina {idxMacchina} ", $"idxMacchina {idxMacchina} | IdxOdl {datiProdAct[0].IdxOdl} | pzTot {datiProdAct[0].PzTotODL} | dataRif {dataRif}", tipoLog.WARNING); - } - } - else - { - logger.lg.scriviLog($"pzCounterTC: Non trovate righe in currODL {idxMacchina}", $"Non trovate righe in currODL x idxMacchina {idxMacchina}: datiProdAct vuota", tipoLog.WARNING); - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"[pzCounterTC] Eccezione in pzCounterTC x idxMacchina {idxMacchina}", $"[pzCounterTC] Eccezione in pzCounterTC x idxMacchina {idxMacchina}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - } - return answ; - } - - /// - /// Calcola l'effettivo valore da passare alla macchina a stati INGRESSI data conf Macchine2FamigliaIngressi - /// - /// - /// - /// - private string preProcInput(string idxMacchina, string valore) - { - string newVal = ""; - try - { - // variabili - int valINT = 0; - int BitFilt = 0; - int BSR = 0; - bool ExplodeBit = false; - int NumBit = 0; - int newValInt = 0; - // recupero parametri... - int.TryParse(mDatiMacchinaVal(idxMacchina, "BitFilt"), out BitFilt); - int.TryParse(mDatiMacchinaVal(idxMacchina, "BSR"), out BSR); - Boolean.TryParse(mDatiMacchinaVal(idxMacchina, "ExplodeBit"), out ExplodeBit); - int.TryParse(mDatiMacchinaVal(idxMacchina, "NumBit"), out NumBit); // non usato (x ora) - // recupero valore - valINT = int.Parse(valore, NumberStyles.HexNumber); - // filtro - newValInt = utility.bMaskInt(valINT, BitFilt); - // effettuo eventuale BitShiftRight - if (BSR > 0) - { - newValInt = newValInt >> BSR; - } - // effettuo eventuale esplosione in BIT esclusivi - if (ExplodeBit) - { - newValInt = Convert.ToInt32(1 << newValInt); - } - // riconverto a STRING HEX!!! - newVal = newValInt.ToString("X"); - } - catch - { - newVal = valore; - } - - return newVal; - } - - private void SetAllCommandTimeouts(object adapter, int timeout) - { - var commands = adapter.GetType().InvokeMember( - "CommandCollection", - BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic, - null, adapter, new object[0]); - var sqlCommand = (SqlCommand[])commands; - foreach (var cmd in sqlCommand) - { - cmd.CommandTimeout = timeout; - } - } - - /// - /// cerca codice in anagrafica macchine ed eventualmente inserisce nuova macchina - /// - /// - private void verificaIdxMacchina(string IdxMacchina) - { - bool needDB = false; - if (!memLayer.ML.CRB("disable_verificaIdxMacchina")) - { - if (memLayer.ML.CRB("IOB_RedEnab")) - { - try - { - // esecuzione in REDIS...cerco status macchina... - if (mDatiMacchine(IdxMacchina).Count == 0) - { - needDB = true; - } - } - catch { } - } - // ...oppure segno richiesta DB... - else - { - needDB = true; - } - if (needDB) - { - // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione NUOVO oggetto - if (memLayer.ML.CRB("disable_singleton")) - { - taMacchine = new DS_applicazioneTableAdapters.MacchineTableAdapter(); - MapoDbObj.taMSM = new DS_applicazioneTableAdapters.MicroStatoMacchinaTableAdapter(); - } - // verifico esistenza macchina - if (taMacchine.GetByIdx(IdxMacchina).Rows.Count == 0) - { - // inserisco nuova macchina... - taMacchine.Insert(IdxMacchina, "9999", IdxMacchina, "Macchina non codificata", "-", "http://", "nd", "col", 0, 0); - } - // verifico ci sia un microstato macchina... - if (MapoDbObj.taMSM.getByIdxMacchina(IdxMacchina).Rows.Count == 0) - { - // inserisco nuovo stato... - MapoDbObj.taMSM.Insert(IdxMacchina, 0, DateTime.Now, "00"); - } - } - } - } - - #endregion Private Methods - - #region Protected Methods - - /// - /// init dei table adapters - /// - protected void initTA() - { - // istanzio oggetto - taAG = new DS_applicazioneTableAdapters.AnagraficaGruppiTableAdapter(); - taAlarmLog = new DS_applicazioneTableAdapters.AlarmLogTableAdapter(); - taAnagArt = new DS_ProdTempiTableAdapters.AnagArticoliTableAdapter(); - taAnagEventi = new DS_applicazioneTableAdapters.AnagraficaEventiTableAdapter(); - taAnagStati = new DS_applicazioneTableAdapters.AnagraficaStatiTableAdapter(); - taAnagTags = new DS_applicazioneTableAdapters.AnagTagsTableAdapter(); - taAs400 = new DS_IntServTableAdapters.ProduzioneAs400TableAdapter(); - taArcaGiac = new DS_ArcaTableAdapters.GiacenzeTableAdapter(); - taCalFF = new DS_ProdTempiTableAdapters.CalendFesteFerieTableAdapter(); - taComm = new DS_UtilityTableAdapters.CommentiTableAdapter(); - taDatiConf = new DS_ProdTempiTableAdapters.DatiConfermatiTableAdapter(); - taDatiMacchine = new DS_ProdTempiTableAdapters.DatiMacchineTableAdapter(); - taDatiProd = new DS_ProdTempiTableAdapters.DatiProduzioneTableAdapter(); - taDatiProdMacch = new DS_ProdTempiTableAdapters.stp_repDonati_getDatiProdMacchinaTableAdapter(); - taDatiProdMacchPer = new DS_ProdTempiTableAdapters.stp_repDonati_getDatiProdMacchinaPeriodoTableAdapter(); - taDatiStatoMacch = new DS_ProdTempiTableAdapters.stp_repDonati_getLastStatoDurataMacchinaTableAdapter(); - taDiarioDich = new DS_applicazioneTableAdapters.DiarioDichiarazioniTableAdapter(); - taEventi = new DS_applicazioneTableAdapters.EventListTableAdapter(); - taFL = new DS_applicazioneTableAdapters.FluxLogTableAdapter(); - taIS_TrDati = new DS_IntServTableAdapters.TransitoDatiTableAdapter(); - taIstK = new DS_IntServTableAdapters.IstanzeKITTableAdapter(); - taKeepAlive = new DS_applicazioneTableAdapters.KeepAliveTableAdapter(); - taM2S = new DS_ProdTempiTableAdapters.Macchine2SlaveTableAdapter(); - taMacchine = new DS_applicazioneTableAdapters.MacchineTableAdapter(); - taMacParams = new DS_PlanTableAdapters.MachineParamsTableAdapter(); - taMagELotti = new DS_MAGTableAdapters.ElencoLottiTableAdapter(); - taMSE = new DS_ProdTempiTableAdapters.MappaStatoExplTableAdapter(); - taODL = new DS_ProdTempiTableAdapters.ODLTableAdapter(); - taOp = new DS_applicazioneTableAdapters.AnagraficaOperatoriTableAdapter(); - taOp2ins = new DS_applicazioneTableAdapters.AnagraficaOperatori2insTableAdapter(); - taPlanCalDisp = new DS_PlanTableAdapters.CalDispTableAdapter(); - taPlanCalStop = new DS_PlanTableAdapters.CalStopTableAdapter(); - taPlanRichieste = new DS_PlanTableAdapters.RichiesteTableAdapter(); - taPODL = new DS_ProdTempiTableAdapters.PromesseODLTableAdapter(); - taPostazioni = new DS_ProdTempiTableAdapters.PostazioniMapoTableAdapter(); - taPromIn = new DS_PlanTableAdapters.PromesseINTableAdapter(); - taPromOut = new DS_PlanTableAdapters.PromesseOUTTableAdapter(); - taPzProd2conf = new DS_ProdTempiTableAdapters.stp_PzProd_getByMacchinaTableAdapter(); - taRC = new DS_ProdTempiTableAdapters.RegistroControlliTableAdapter(); - taRemReb = new DS_applicazioneTableAdapters.RemoteRebootLogTableAdapter(); - taRS = new DS_ProdTempiTableAdapters.RegistroScartiTableAdapter(); - taSelArt = new DS_UtilityTableAdapters.v_selArticoliTableAdapter(); - taSelMacc = new DS_UtilityTableAdapters.v_selMacchineTableAdapter(); - taSelOdlFree = new DS_UtilityTableAdapters.v_selODLTableAdapter(); - taSigLog = new DS_applicazioneTableAdapters.SignalLogTableAdapter(); - taSTA = new DS_SheetTechTableAdapters.ST_ActualTableAdapter(); - taSTAR = new DS_SheetTechTableAdapters.ST_ActualRowTableAdapter(); - taStati = new DS_applicazioneTableAdapters.DiarioDiBordoTableAdapter(); - taStatoMacchine = new DS_applicazioneTableAdapters.StatoMacchineTableAdapter(); - taStatoProd = new DS_ProdTempiTableAdapters.StatoProdTableAdapter(); - taSTChk = new DS_SheetTechTableAdapters.ST_CheckTableAdapter(); - taTempiCicloRilevati = new DS_ProdTempiTableAdapters.TempiCicloRilevatiTableAdapter(); - taTempoByClass = new DS_ProdTempiTableAdapters.stp_TempoByIdxMaccPeriodClassTableAdapter(); - taTKS = new DS_IntServTableAdapters.TKS_SearchTableAdapter(); - taTranIngr = new DS_applicazioneTableAdapters.TransizioneIngressiTableAdapter(); - taTurniMacc = new DS_ProdTempiTableAdapters.TurniMacchinaTableAdapter(); - taWKS = new DS_IntServTableAdapters.WipSetupKitTableAdapter(); - } - - /// - /// effettua setup dei connection strings da web.config delal singola applicazione - /// - protected virtual void setupConnectionStringBase() - { - string connectionString = memLayer.ML.confReadString("MoonProConnectionString"); - string connectionStringIS = memLayer.ML.confReadString("MoonProConnectionStringIS"); - string connectionStringArca = memLayer.ML.confReadString("MoonProConnectionStringArca"); - string connectionStringES3 = memLayer.ML.confReadString("MoonProConnectionStringES3"); - string connectionStringMAG = memLayer.ML.confReadString("MoonProConnectionStringMAG"); - // connections del db - taAG.Connection.ConnectionString = connectionString; - taAlarmLog.Connection.ConnectionString = connectionString; - taAnagArt.Connection.ConnectionString = connectionString; - taAnagEventi.Connection.ConnectionString = connectionString; - taAnagStati.Connection.ConnectionString = connectionString; - taAnagTags.Connection.ConnectionString = connectionString; - taAs400.Connection.ConnectionString = connectionStringIS; - taArcaGiac.Connection.ConnectionString = connectionStringArca; - taCalFF.Connection.ConnectionString = connectionString; - taComm.Connection.ConnectionString = connectionString; - taDatiConf.Connection.ConnectionString = connectionString; - taDatiMacchine.Connection.ConnectionString = connectionString; - taDatiProd.Connection.ConnectionString = connectionString; - taDatiProdMacch.Connection.ConnectionString = connectionString; - taDatiProdMacchPer.Connection.ConnectionString = connectionString; - taDatiStatoMacch.Connection.ConnectionString = connectionString; - taDiarioDich.Connection.ConnectionString = connectionString; - taEventi.Connection.ConnectionString = connectionString; - taFL.Connection.ConnectionString = connectionString; - taIS_TrDati.Connection.ConnectionString = connectionStringIS; - taIstK.Connection.ConnectionString = connectionStringIS; - taKeepAlive.Connection.ConnectionString = connectionString; - taM2S.Connection.ConnectionString = connectionString; - taMacchine.Connection.ConnectionString = connectionString; - taMacParams.Connection.ConnectionString = connectionStringES3; - taMagELotti.Connection.ConnectionString = connectionStringMAG; - taMSE.Connection.ConnectionString = connectionString; - taODL.Connection.ConnectionString = connectionString; - taOp.Connection.ConnectionString = connectionString; - taOp2ins.Connection.ConnectionString = connectionString; - taPlanCalDisp.Connection.ConnectionString = connectionStringES3; - taPlanCalStop.Connection.ConnectionString = connectionStringES3; - taPlanRichieste.Connection.ConnectionString = connectionStringES3; - taPODL.Connection.ConnectionString = connectionString; - taPostazioni.Connection.ConnectionString = connectionString; - taPromIn.Connection.ConnectionString = connectionStringES3; - taPromOut.Connection.ConnectionString = connectionStringES3; - taPzProd2conf.Connection.ConnectionString = connectionString; - taRC.Connection.ConnectionString = connectionString; - taRemReb.Connection.ConnectionString = connectionString; - taRS.Connection.ConnectionString = connectionString; - taSelArt.Connection.ConnectionString = connectionString; - taSelMacc.Connection.ConnectionString = connectionString; - taSelOdlFree.Connection.ConnectionString = connectionString; - taSigLog.Connection.ConnectionString = connectionString; - taSTA.Connection.ConnectionString = connectionString; - taSTAR.Connection.ConnectionString = connectionString; - taStati.Connection.ConnectionString = connectionString; - taStatoMacchine.Connection.ConnectionString = connectionString; - taStatoProd.Connection.ConnectionString = connectionString; - taSTChk.Connection.ConnectionString = connectionString; - taTempiCicloRilevati.Connection.ConnectionString = connectionString; - taTempoByClass.Connection.ConnectionString = connectionString; - taTKS.Connection.ConnectionString = connectionStringIS; - taTranIngr.Connection.ConnectionString = connectionString; - taTurniMacc.Connection.ConnectionString = connectionString; - taWKS.Connection.ConnectionString = connectionStringIS; - } - - #endregion Protected Methods - #region Public Methods /// @@ -734,11 +346,8 @@ namespace MapoDb return mHash(string.Format("ExeTask:{0}", idxMacchina)); } - /// - /// Hash dati relativi all'associazione macchina <--> IOB - /// - /// Macchina PRINCIPALE - /// + /// Hash dati relativi all'associazione macchina <--> IOB Macchina PRINCIPALE public static string hM2IOB(string IdxMacchina) { return mHash(string.Format("hM2IOB:{0}", IdxMacchina)); @@ -755,7 +364,8 @@ namespace MapoDb } /// - /// Hash dati STATE MACHINE INGRESSI x la FAMIGLIA INGRESSI specificata (per completare poi manca singolo micro stato corrente + valore letto x definire chiave) + /// Hash dati STATE MACHINE INGRESSI x la FAMIGLIA INGRESSI specificata (per completare poi + /// manca singolo micro stato corrente + valore letto x definire chiave) /// /// /// @@ -775,6 +385,16 @@ namespace MapoDb return mHash($"LIVE:{idxMacchina}:{bufferName}"); } + /// + /// Hash dati LIVE x la macchina specificata + /// + /// + /// + public static string LiveCurrValHash(string idxMacchina) + { + return mHash($"LIVE:{idxMacchina}:CURR_VAL"); + } + /// /// KEY x i dati del FLog della machina specificata /// @@ -786,16 +406,6 @@ namespace MapoDb return mHash($"FLOG:{idxMacchina}:{flog}"); } - /// - /// Hash dati LIVE x la macchina specificata - /// - /// - /// - public static string LiveCurrValHash(string idxMacchina) - { - return mHash($"LIVE:{idxMacchina}:CURR_VAL"); - } - /// /// Hash dati MemoryMap x la macchina specificata /// @@ -807,7 +417,8 @@ namespace MapoDb } /// - /// Hash Redis contenente i dati MP di una specifico TYPE (es StatusMacchina, StateMachineIngressi, ...) + /// Hash Redis contenente i dati MP di una specifico TYPE (es StatusMacchina, + /// StateMachineIngressi, ...) /// /// /// @@ -837,7 +448,8 @@ namespace MapoDb } /// - /// Hash dati SAVED (EXE) TASK x la macchina specificata x poter ripristinare in caso di perdita valore WRITE + /// Hash dati SAVED (EXE) TASK x la macchina specificata x poter ripristinare in caso di + /// perdita valore WRITE /// /// /// @@ -870,7 +482,8 @@ namespace MapoDb } /// - /// verifica se sia da reinviare un task alla macchina dall'elenco di quelli salvati (in modalità upsert) se non scaduti + /// verifica se sia da reinviare un task alla macchina dall'elenco di quelli salvati (in + /// modalità upsert) se non scaduti /// /// /// @@ -1030,7 +643,9 @@ namespace MapoDb /// macchina /// effettuare conferma qty /// imposta la qty prox ODL da ODL che si chiude - /// STEP x cui arrotondare la quantità prox ODL (corrente come riferimento) + /// + /// STEP x cui arrotondare la quantità prox ODL (corrente come riferimento) + /// /// Cod ext da associare all'ODL /// public string AutoStartOdl(string idxMacchina, bool doConfirm, bool qtyFromLast, int roundStep = 100, string keyRichiesta = "") @@ -1217,11 +832,11 @@ namespace MapoDb // ...oppure dritto su DB else { - // esecuzione in DB... - // recupero CodArticolo corretto + // esecuzione in DB... recupero CodArticolo corretto try { - // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione NUOVO oggetto + // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione + // NUOVO oggetto if (memLayer.ML.CRB("disable_singleton")) { // 2017.07.10 forzo init x errori "sovrapposizioni" @@ -1282,7 +897,8 @@ namespace MapoDb // ...oppure dritto su DB else { - // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione NUOVO oggetto + // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione + // NUOVO oggetto if (memLayer.ML.CRB("disable_singleton")) { // 2017.06.09 forzo init x errori "sovrapposizioni" @@ -1308,7 +924,8 @@ namespace MapoDb { logger.lg.scriviLog(string.Format("[ChkMiSt_6a] - Salvo Update Microstato:{0}macchina: {1} | valore seriale: {2} | next micro stato: {3}", Environment.NewLine, idxMacchina, valINT, rigaTransIn.next_IdxMicroStato), tipoLog.INFO); } - // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione NUOVO oggetto + // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione + // NUOVO oggetto if (memLayer.ML.CRB("disable_singleton")) { // 2017.06.09 forzo init x errori "sovrapposizioni" @@ -1441,7 +1058,8 @@ namespace MapoDb } /// - /// Effettua conferma prod macchina dell'intero periodo da confermare (ultima conferma --> adesso) + /// Effettua conferma prod macchina dell'intero periodo da confermare (ultima conferma + /// --> adesso) /// /// idx macchina da confermare /// 0=periodo, 1 = giorno, 2 = turno @@ -1467,12 +1085,15 @@ namespace MapoDb } /// - /// Effettua conferma prod macchina dell'intero periodo da confermare (ultima conferma --> adesso) + /// Effettua conferma prod macchina dell'intero periodo da confermare (ultima conferma + /// --> adesso) /// /// idx macchina da confermare /// 0=periodo, 1 = giorno, 2 = turno /// qta pezzi BUONI da confermare - /// qta pezzi LASCIATI alla macchina da confermare (2 eventi 121 rettifica neg/pos) + /// + /// qta pezzi LASCIATI alla macchina da confermare (2 eventi 121 rettifica neg/pos) + /// /// qta pezzi SCARTO da confermare /// DataOra in cui registrare approvazione /// @@ -1494,7 +1115,8 @@ namespace MapoDb } /// - /// Restituisce il valore dell'ODL corrente (ODL deve esserci per gestione contapezzi, senza ODL NO invio/gestione ODL) + /// Restituisce il valore dell'ODL corrente (ODL deve esserci per gestione contapezzi, senza + /// ODL NO invio/gestione ODL) /// /// /// @@ -1525,7 +1147,8 @@ namespace MapoDb } /// - /// Restituisce il valore dell'ODL corrente (ODL deve esserci per gestione contapezzi, senza ODL NO invio/gestione ODL) + /// Restituisce il valore dell'ODL corrente (ODL deve esserci per gestione contapezzi, senza + /// ODL NO invio/gestione ODL) /// /// /// indica se forzare lettura da db (true) o meno @@ -1533,7 +1156,8 @@ namespace MapoDb public string currODL(string idxMacchina, bool forceDb) { string answ = ""; - // faccio comunque verifica se sia stato letto da poco il valore... x cui anche a fronte di richiesta lettura da DB per 3 sec tengo buono valore in cache redis... + // faccio comunque verifica se sia stato letto da poco il valore... x cui anche a fronte + // di richiesta lettura da DB per 3 sec tengo buono valore in cache redis... string rKey = memLayer.ML.redHash($"ODL:{idxMacchina}"); string _idxOdl = memLayer.ML.getRSV(rKey); if (forceDb) @@ -1934,7 +1558,8 @@ namespace MapoDb if (tc == 0) { tc = 99.9M; - // scrivo log per indicare mancato caricamento dati tc dichiarato e conseguente errore sul timer - 2/11/2012 EN&CV + // scrivo log per indicare mancato caricamento dati tc dichiarato e conseguente + // errore sul timer - 2/11/2012 EN&CV logger.lg.scriviLog(string.Format("Impostato TC Tempo Ciclo a 99' (99.9M) causa mancato inserimento tempo ciclo dichiarato")); } return tc; @@ -2249,7 +1874,8 @@ namespace MapoDb string answ = ""; DateTime dataOraEvento = DateTime.Now; DateTime dtEvento, dtCorrente; - // controllo: se ho valori dt x evento e orario DIVERSI per acquisitore IOB calcolo dataOraEvento corretto + // controllo: se ho valori dt x evento e orario DIVERSI per acquisitore IOB calcolo + // dataOraEvento corretto if (dtEve != dtCurr) { Int64 delta = 0; @@ -2314,112 +1940,6 @@ namespace MapoDb return answ; } - - /// - /// Processa registrazione UserLog da IOB - /// - /// Macchina - /// Flusso: DI/RC/RC - /// valore = note/valString - /// data evento - /// data corrente - /// contatore invio - /// Matricola Operatore - /// label = causale scarto / tagCode - /// valNum = esitoOk (0/1) / Quantità di scarto associata - /// - public string processUserLog(string idxMacchina, string flux, string valore, string dtEve, string dtCurr, int contatore, int matrOpr, string label, int valNum) - { - // instanzio un nuovo oggetto MapoDb - MapoDb connDb = new MapoDb(); - // scrivo keep alive!!! (se necessario, altrimenti è in cache...) - connDb.scriviKeepAlive(idxMacchina, DateTime.Now); - // 2017.09.14 trimmo eventualmente lo zero finale dalle date SE supera i millisecondi... - dtEve = dtEve.Length > 17 ? dtEve.Substring(0, 17) : dtEve; - dtCurr = dtCurr.Length > 17 ? dtCurr.Substring(0, 17) : dtCurr; - // registro conteggio impiego chiamate REDIS - if (memLayer.ML.CRB("IOB_RedEnab")) - { - saveCallRec("processUserLog"); - } - string answ = ""; - DateTime dataOraEvento = DateTime.Now; - DateTime dtEvento, dtCorrente; - // controllo: se ho valori dt x evento e orario DIVERSI per acquisitore IOB calcolo dataOraEvento corretto - if (dtEve != dtCurr) - { - Int64 delta = 0; - try - { - // se ho meno decimali x evento rispetto dtCorrente... - if (dtEve.Length < dtCurr.Length) - { - dtEve = dtEve.PadRight(dtCurr.Length, '0'); - } - delta = Convert.ToInt64(dtCurr) - Convert.ToInt64(dtEve); - // se meno di 60'000 ms ... - if (delta < 59999) - { - dataOraEvento = dataOraEvento.AddMilliseconds(-delta); - } - else - { - // in questo caso elimino i MS dalle stringhe e converto i datetime.... - CultureInfo provider = CultureInfo.InvariantCulture; - string format = "yyyyMMddHHmmssfff"; - dtEvento = DateTime.ParseExact(dtEve, format, provider); - dtCorrente = DateTime.ParseExact(dtCurr, format, provider); - Int64 tiks = dtCorrente.Ticks - dtEvento.Ticks; - dataOraEvento = dataOraEvento.AddTicks(-tiks); - } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("processUserLog | Errore calcolo ms evento/ora corrente da device remoto:{0}dtEve : {1}{0}dtCurr: {2}{0}{3}", Environment.NewLine, dtEve, dtCurr, exc), tipoLog.EXCEPTION); - } - } - // inizio processing vero e proprio INPUT... - if (string.IsNullOrEmpty(idxMacchina)) - { - string errore = "processUserLog | Errore: macchina mancante"; - logger.lg.scriviLog(errore, tipoLog.INFO); - answ = errore; - } - else - { - if (string.IsNullOrEmpty(flux)) - { - string errore = "processUserLog | Errore: parametro flux vuoto"; - logger.lg.scriviLog(errore, tipoLog.INFO); - answ = errore; - } - else - { - // 2020.01.31 nuovo OBJ - DataLayer DLMan = new DataLayer(); - // in base al flusso decido dove e cosa scrivere... - switch (flux) - { - case "DI": - DLMan.taDiarioDich.insertQuery(label, idxMacchina, dataOraEvento, matrOpr, valore); - break; - case "RC": - bool esitoOk = valNum != 0; - DLMan.taRC.insertQuery(idxMacchina, matrOpr, esitoOk, valore, dataOraEvento); - break; - case "RS": - DLMan.taRS.insertQuery(idxMacchina, dataOraEvento, label, valNum, valore, matrOpr); - break; - default: - break; - } - // registro in risposta che è andato tutto bene... - answ = "OK"; - } - } - return answ; - } - /// /// Processa input da IOB eventualmente registrando i segnali inviati /// @@ -2453,7 +1973,8 @@ namespace MapoDb } DateTime dataOraEvento = DateTime.Now; DateTime dtEvento, dtCorrente; - // controllo: se ho valori dt x evento e orario DIVERSI per acquisitore IOB calcolo dataOraEvento corretto + // controllo: se ho valori dt x evento e orario DIVERSI per acquisitore IOB calcolo + // dataOraEvento corretto if (dtEve != dtCurr) { // delta è un calcolo MOLTO approssimativo della differenza temporale... @@ -2515,7 +2036,8 @@ namespace MapoDb { if (idxMacchina != "" && valore != "") { - // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione NUOVO oggetto + // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la + // gestione NUOVO oggetto if (memLayer.ML.CRB("disable_singleton")) { // instanzio un nuovo oggetto MapoDb @@ -2530,22 +2052,26 @@ namespace MapoDb { // scrivo keep alive!!! (se necessario, altrimenti è in cache...) connDb.scriviKeepAlive(idxMacchina, DateTime.Now); - // verifico se sia una macchina MULTI ed in tal caso calcolo i SUB-systems e CHIAMERO' alla fine pure loro.... + // verifico se sia una macchina MULTI ed in tal caso calcolo i + // SUB-systems e CHIAMERO' alla fine pure loro.... if (isMulti(idxMacchina)) { // inizio preprocessing string newVal = ""; - // processo OGNI macchina a stati dell'impianto... (KEY: IdxMacchina / IdxMacchina#qualcosa, Val = IdxFamIn) + // processo OGNI macchina a stati dell'impianto... (KEY: + // IdxMacchina / IdxMacchina#qualcosa, Val = IdxFamIn) foreach (var item in mTabMSMI(idxMacchina)) { newVal = preProcInput(item.Key, valore); - // ora processo e salvo il valore del microstato... INTERNAMENTE gestisce i casi DB/REDIS secondo necessità + // ora processo e salvo il valore del microstato... + // INTERNAMENTE gestisce i casi DB/REDIS secondo necessità checkMicroStato(item.Key, newVal, dataOraEvento, contatore); } } else { - // ora processo e salvo il valore del microstato... INTERNAMENTE gestisce i casi DB/REDIS secondo necessità + // ora processo e salvo il valore del microstato... INTERNAMENTE + // gestisce i casi DB/REDIS secondo necessità checkMicroStato(idxMacchina, valore, dataOraEvento, contatore); } // registro in risposta che è andato tutto bene... @@ -2573,12 +2099,14 @@ namespace MapoDb { // scrivo keep alive!!! (se encessario, altrimenti è in cache...) MapoDbObj.scriviKeepAlive(idxMacchina, DateTime.Now); - // verifico se sia una macchina MULTI ed in tal caso calcolo i SUB-systems e CHIAMERO' alla fine pure loro.... + // verifico se sia una macchina MULTI ed in tal caso calcolo i + // SUB-systems e CHIAMERO' alla fine pure loro.... if (MapoDbObj.isMulti(idxMacchina)) { // inizio preprocessing string newVal = ""; - // processo OGNI macchina a stati dell'impianto... (KEY: IdxMacchina / IdxMacchina#qualcosa, Val = IdxFamIn) + // processo OGNI macchina a stati dell'impianto... (KEY: + // IdxMacchina / IdxMacchina#qualcosa, Val = IdxFamIn) foreach (var item in getMSMI_DB(idxMacchina)) { newVal = preProcInput(item.Key, valore); @@ -2750,6 +2278,115 @@ namespace MapoDb return answ; } + /// + /// Processa registrazione UserLog da IOB + /// + /// Macchina + /// Flusso: DI/RC/RC + /// valore = note/valString + /// data evento + /// data corrente + /// contatore invio + /// Matricola Operatore + /// label = causale scarto / tagCode + /// valNum = esitoOk (0/1) / Quantità di scarto associata + /// + public string processUserLog(string idxMacchina, string flux, string valore, string dtEve, string dtCurr, int contatore, int matrOpr, string label, int valNum) + { + // instanzio un nuovo oggetto MapoDb + MapoDb connDb = new MapoDb(); + // scrivo keep alive!!! (se necessario, altrimenti è in cache...) + connDb.scriviKeepAlive(idxMacchina, DateTime.Now); + // 2017.09.14 trimmo eventualmente lo zero finale dalle date SE supera i millisecondi... + dtEve = dtEve.Length > 17 ? dtEve.Substring(0, 17) : dtEve; + dtCurr = dtCurr.Length > 17 ? dtCurr.Substring(0, 17) : dtCurr; + // registro conteggio impiego chiamate REDIS + if (memLayer.ML.CRB("IOB_RedEnab")) + { + saveCallRec("processUserLog"); + } + string answ = ""; + DateTime dataOraEvento = DateTime.Now; + DateTime dtEvento, dtCorrente; + // controllo: se ho valori dt x evento e orario DIVERSI per acquisitore IOB calcolo + // dataOraEvento corretto + if (dtEve != dtCurr) + { + Int64 delta = 0; + try + { + // se ho meno decimali x evento rispetto dtCorrente... + if (dtEve.Length < dtCurr.Length) + { + dtEve = dtEve.PadRight(dtCurr.Length, '0'); + } + delta = Convert.ToInt64(dtCurr) - Convert.ToInt64(dtEve); + // se meno di 60'000 ms ... + if (delta < 59999) + { + dataOraEvento = dataOraEvento.AddMilliseconds(-delta); + } + else + { + // in questo caso elimino i MS dalle stringhe e converto i datetime.... + CultureInfo provider = CultureInfo.InvariantCulture; + string format = "yyyyMMddHHmmssfff"; + dtEvento = DateTime.ParseExact(dtEve, format, provider); + dtCorrente = DateTime.ParseExact(dtCurr, format, provider); + Int64 tiks = dtCorrente.Ticks - dtEvento.Ticks; + dataOraEvento = dataOraEvento.AddTicks(-tiks); + } + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("processUserLog | Errore calcolo ms evento/ora corrente da device remoto:{0}dtEve : {1}{0}dtCurr: {2}{0}{3}", Environment.NewLine, dtEve, dtCurr, exc), tipoLog.EXCEPTION); + } + } + // inizio processing vero e proprio INPUT... + if (string.IsNullOrEmpty(idxMacchina)) + { + string errore = "processUserLog | Errore: macchina mancante"; + logger.lg.scriviLog(errore, tipoLog.INFO); + answ = errore; + } + else + { + if (string.IsNullOrEmpty(flux)) + { + string errore = "processUserLog | Errore: parametro flux vuoto"; + logger.lg.scriviLog(errore, tipoLog.INFO); + answ = errore; + } + else + { + // 2020.01.31 nuovo OBJ + DataLayer DLMan = new DataLayer(); + // in base al flusso decido dove e cosa scrivere... + switch (flux) + { + case "DI": + DLMan.taDiarioDich.insertQuery(label, idxMacchina, dataOraEvento, matrOpr, valore); + break; + + case "RC": + bool esitoOk = valNum != 0; + DLMan.taRC.insertQuery(idxMacchina, matrOpr, esitoOk, valore, dataOraEvento); + break; + + case "RS": + DLMan.taRS.insertQuery(idxMacchina, dataOraEvento, label, valNum, valore, matrOpr); + break; + + default: + break; + } + // registro in risposta che è andato tutto bene... + answ = "OK"; + } + } + return answ; + } + /// /// Restituisce il contapezzi salvato per la macchina /// @@ -3192,7 +2829,7 @@ namespace MapoDb /// Processa registrazione ODL corrente x macchina /// /// - /// cod ODL in produzione, se "" --> non c'è... + /// cod ODL in produzione, se "" --> non c'è... /// public string saveCurrODL(string idxMacchina, string currODL) { @@ -3459,7 +3096,8 @@ namespace MapoDb } /// - /// scrive una riga di evento inviato da Barcode nel db SENZA operatore e pallet (mette a 0 e "-") + /// scrive una riga di evento inviato da Barcode nel db SENZA operatore e pallet (mette a 0 + /// e "-") /// /// codice macchina /// idx evento @@ -3568,6 +3206,30 @@ namespace MapoDb return inserito; } + /// + /// Invia una mail al destinatario con oggetto e contenuto + /// + /// + /// + /// + /// + public bool sendEmail(string destinatario, string oggetto, string corpo) + { + bool fatto = false; + try + { + // compongo la stringa + string mittente = memLayer.ML.CRS("_fromEmail"); + gestEmail.geAuth.mandaEmail(mittente, destinatario, oggetto, corpo); + fatto = true; + } + catch (Exception exc) + { + logger.lg.scriviLog($"Eccezione in sendEmail{Environment.NewLine}{exc}", tipoLog.ERROR); + } + return fatto; + } + /// /// invia una mail al destinatario x linkare nuovi devices tramite URL /// @@ -3604,31 +3266,6 @@ namespace MapoDb return fatto; } - - /// - /// Invia una mail al destinatario con oggetto e contenuto - /// - /// - /// - /// - /// - public bool sendEmail(string destinatario, string oggetto, string corpo) - { - bool fatto = false; - try - { - // compongo la stringa - string mittente = memLayer.ML.CRS("_fromEmail"); - gestEmail.geAuth.mandaEmail(mittente, destinatario, oggetto, corpo); - fatto = true; - } - catch (Exception exc) - { - logger.lg.scriviLog($"Eccezione in sendEmail{Environment.NewLine}{exc}", tipoLog.ERROR); - } - return fatto; - } - /// /// Invia email di avviso che ci sono dei TC da confermare /// @@ -3716,7 +3353,7 @@ namespace MapoDb } /// - /// Salvataggio su della mappa di memoria dell'IOB x ulteriori impieghi + /// Salvataggio su della mappa di memoria dell'IOB x ulteriori impieghi /// /// /// @@ -3735,7 +3372,8 @@ namespace MapoDb } /// - /// Restituisce il valore booleano se la macchina sia abilitata all'inserimento COMPLETO nel Signal Log + /// Restituisce il valore booleano se la macchina sia abilitata all'inserimento COMPLETO nel + /// Signal Log /// /// /// @@ -3759,6 +3397,36 @@ namespace MapoDb return answ; } + /// + /// Effettua chaimata DB x snapshot del FluxLog della macchina richiesta (insieme set ultimi dati) + /// + /// IdxMacchina + /// + /// Dimensione della finestra temporale da ultimo record indietro x salvare valori + /// + /// + public string takeFlogSnapshot(string id, int windSize) + { + string answ = "ND"; + // instanzio un nuovo oggetto MapoDb + MapoDb connDb = new MapoDb(); + // scrivo keep alive!!! (se necessario, altrimenti è in cache...) + connDb.scriviKeepAlive(id, DateTime.Now); + + try + { + // ora chiamo la stored di duplicazione + DataLayer DLMan = new DataLayer(); + DLMan.taFL.takeSnapshot(id, windSize); + answ = "OK"; + } + catch (Exception exc) + { + logger.lg.scriviLog($"takeFlogSnapshot:{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + return answ; + } + /// /// Aggiornamento parametro per macchina /// @@ -3854,5 +3522,450 @@ namespace MapoDb } #endregion Public Methods + + #region Protected Fields + + /// + /// indica conferma con rettifica (evento 121) + /// + protected bool confRett = memLayer.ML.CRB("confRett"); + + #endregion Protected Fields + + #region Protected Methods + + /// + /// init dei table adapters + /// + protected void initTA() + { + // istanzio oggetto + taAG = new DS_applicazioneTableAdapters.AnagraficaGruppiTableAdapter(); + taAlarmLog = new DS_applicazioneTableAdapters.AlarmLogTableAdapter(); + taAnagArt = new DS_ProdTempiTableAdapters.AnagArticoliTableAdapter(); + taAnagEventi = new DS_applicazioneTableAdapters.AnagraficaEventiTableAdapter(); + taAnagStati = new DS_applicazioneTableAdapters.AnagraficaStatiTableAdapter(); + taAnagTags = new DS_applicazioneTableAdapters.AnagTagsTableAdapter(); + taAs400 = new DS_IntServTableAdapters.ProduzioneAs400TableAdapter(); + taArcaGiac = new DS_ArcaTableAdapters.GiacenzeTableAdapter(); + taCalFF = new DS_ProdTempiTableAdapters.CalendFesteFerieTableAdapter(); + taComm = new DS_UtilityTableAdapters.CommentiTableAdapter(); + taDatiConf = new DS_ProdTempiTableAdapters.DatiConfermatiTableAdapter(); + taDatiMacchine = new DS_ProdTempiTableAdapters.DatiMacchineTableAdapter(); + taDatiProd = new DS_ProdTempiTableAdapters.DatiProduzioneTableAdapter(); + taDatiProdMacch = new DS_ProdTempiTableAdapters.stp_repDonati_getDatiProdMacchinaTableAdapter(); + taDatiProdMacchPer = new DS_ProdTempiTableAdapters.stp_repDonati_getDatiProdMacchinaPeriodoTableAdapter(); + taDatiStatoMacch = new DS_ProdTempiTableAdapters.stp_repDonati_getLastStatoDurataMacchinaTableAdapter(); + taDiarioDich = new DS_applicazioneTableAdapters.DiarioDichiarazioniTableAdapter(); + taEventi = new DS_applicazioneTableAdapters.EventListTableAdapter(); + taFL = new DS_applicazioneTableAdapters.FluxLogTableAdapter(); + taIS_TrDati = new DS_IntServTableAdapters.TransitoDatiTableAdapter(); + taIstK = new DS_IntServTableAdapters.IstanzeKITTableAdapter(); + taKeepAlive = new DS_applicazioneTableAdapters.KeepAliveTableAdapter(); + taM2S = new DS_ProdTempiTableAdapters.Macchine2SlaveTableAdapter(); + taMacchine = new DS_applicazioneTableAdapters.MacchineTableAdapter(); + taMacParams = new DS_PlanTableAdapters.MachineParamsTableAdapter(); + taMagELotti = new DS_MAGTableAdapters.ElencoLottiTableAdapter(); + taMSE = new DS_ProdTempiTableAdapters.MappaStatoExplTableAdapter(); + taODL = new DS_ProdTempiTableAdapters.ODLTableAdapter(); + taOp = new DS_applicazioneTableAdapters.AnagraficaOperatoriTableAdapter(); + taOp2ins = new DS_applicazioneTableAdapters.AnagraficaOperatori2insTableAdapter(); + taPlanCalDisp = new DS_PlanTableAdapters.CalDispTableAdapter(); + taPlanCalStop = new DS_PlanTableAdapters.CalStopTableAdapter(); + taPlanRichieste = new DS_PlanTableAdapters.RichiesteTableAdapter(); + taPODL = new DS_ProdTempiTableAdapters.PromesseODLTableAdapter(); + taPostazioni = new DS_ProdTempiTableAdapters.PostazioniMapoTableAdapter(); + taPromIn = new DS_PlanTableAdapters.PromesseINTableAdapter(); + taPromOut = new DS_PlanTableAdapters.PromesseOUTTableAdapter(); + taPzProd2conf = new DS_ProdTempiTableAdapters.stp_PzProd_getByMacchinaTableAdapter(); + taRC = new DS_ProdTempiTableAdapters.RegistroControlliTableAdapter(); + taRemReb = new DS_applicazioneTableAdapters.RemoteRebootLogTableAdapter(); + taRS = new DS_ProdTempiTableAdapters.RegistroScartiTableAdapter(); + taSelArt = new DS_UtilityTableAdapters.v_selArticoliTableAdapter(); + taSelMacc = new DS_UtilityTableAdapters.v_selMacchineTableAdapter(); + taSelOdlFree = new DS_UtilityTableAdapters.v_selODLTableAdapter(); + taSigLog = new DS_applicazioneTableAdapters.SignalLogTableAdapter(); + taSTA = new DS_SheetTechTableAdapters.ST_ActualTableAdapter(); + taSTAR = new DS_SheetTechTableAdapters.ST_ActualRowTableAdapter(); + taStati = new DS_applicazioneTableAdapters.DiarioDiBordoTableAdapter(); + taStatoMacchine = new DS_applicazioneTableAdapters.StatoMacchineTableAdapter(); + taStatoProd = new DS_ProdTempiTableAdapters.StatoProdTableAdapter(); + taSTChk = new DS_SheetTechTableAdapters.ST_CheckTableAdapter(); + taTempiCicloRilevati = new DS_ProdTempiTableAdapters.TempiCicloRilevatiTableAdapter(); + taTempoByClass = new DS_ProdTempiTableAdapters.stp_TempoByIdxMaccPeriodClassTableAdapter(); + taTKS = new DS_IntServTableAdapters.TKS_SearchTableAdapter(); + taTranIngr = new DS_applicazioneTableAdapters.TransizioneIngressiTableAdapter(); + taTurniMacc = new DS_ProdTempiTableAdapters.TurniMacchinaTableAdapter(); + taWKS = new DS_IntServTableAdapters.WipSetupKitTableAdapter(); + } + + /// + /// effettua setup dei connection strings da web.config delal singola applicazione + /// + protected virtual void setupConnectionStringBase() + { + string connectionString = memLayer.ML.confReadString("MoonProConnectionString"); + string connectionStringIS = memLayer.ML.confReadString("MoonProConnectionStringIS"); + string connectionStringArca = memLayer.ML.confReadString("MoonProConnectionStringArca"); + string connectionStringES3 = memLayer.ML.confReadString("MoonProConnectionStringES3"); + string connectionStringMAG = memLayer.ML.confReadString("MoonProConnectionStringMAG"); + // connections del db + taAG.Connection.ConnectionString = connectionString; + taAlarmLog.Connection.ConnectionString = connectionString; + taAnagArt.Connection.ConnectionString = connectionString; + taAnagEventi.Connection.ConnectionString = connectionString; + taAnagStati.Connection.ConnectionString = connectionString; + taAnagTags.Connection.ConnectionString = connectionString; + taAs400.Connection.ConnectionString = connectionStringIS; + taArcaGiac.Connection.ConnectionString = connectionStringArca; + taCalFF.Connection.ConnectionString = connectionString; + taComm.Connection.ConnectionString = connectionString; + taDatiConf.Connection.ConnectionString = connectionString; + taDatiMacchine.Connection.ConnectionString = connectionString; + taDatiProd.Connection.ConnectionString = connectionString; + taDatiProdMacch.Connection.ConnectionString = connectionString; + taDatiProdMacchPer.Connection.ConnectionString = connectionString; + taDatiStatoMacch.Connection.ConnectionString = connectionString; + taDiarioDich.Connection.ConnectionString = connectionString; + taEventi.Connection.ConnectionString = connectionString; + taFL.Connection.ConnectionString = connectionString; + taIS_TrDati.Connection.ConnectionString = connectionStringIS; + taIstK.Connection.ConnectionString = connectionStringIS; + taKeepAlive.Connection.ConnectionString = connectionString; + taM2S.Connection.ConnectionString = connectionString; + taMacchine.Connection.ConnectionString = connectionString; + taMacParams.Connection.ConnectionString = connectionStringES3; + taMagELotti.Connection.ConnectionString = connectionStringMAG; + taMSE.Connection.ConnectionString = connectionString; + taODL.Connection.ConnectionString = connectionString; + taOp.Connection.ConnectionString = connectionString; + taOp2ins.Connection.ConnectionString = connectionString; + taPlanCalDisp.Connection.ConnectionString = connectionStringES3; + taPlanCalStop.Connection.ConnectionString = connectionStringES3; + taPlanRichieste.Connection.ConnectionString = connectionStringES3; + taPODL.Connection.ConnectionString = connectionString; + taPostazioni.Connection.ConnectionString = connectionString; + taPromIn.Connection.ConnectionString = connectionStringES3; + taPromOut.Connection.ConnectionString = connectionStringES3; + taPzProd2conf.Connection.ConnectionString = connectionString; + taRC.Connection.ConnectionString = connectionString; + taRemReb.Connection.ConnectionString = connectionString; + taRS.Connection.ConnectionString = connectionString; + taSelArt.Connection.ConnectionString = connectionString; + taSelMacc.Connection.ConnectionString = connectionString; + taSelOdlFree.Connection.ConnectionString = connectionString; + taSigLog.Connection.ConnectionString = connectionString; + taSTA.Connection.ConnectionString = connectionString; + taSTAR.Connection.ConnectionString = connectionString; + taStati.Connection.ConnectionString = connectionString; + taStatoMacchine.Connection.ConnectionString = connectionString; + taStatoProd.Connection.ConnectionString = connectionString; + taSTChk.Connection.ConnectionString = connectionString; + taTempiCicloRilevati.Connection.ConnectionString = connectionString; + taTempoByClass.Connection.ConnectionString = connectionString; + taTKS.Connection.ConnectionString = connectionStringIS; + taTranIngr.Connection.ConnectionString = connectionString; + taTurniMacc.Connection.ConnectionString = connectionString; + taWKS.Connection.ConnectionString = connectionStringIS; + } + + #endregion Protected Methods + + #region Private Methods + + private static T ConvertDataRowToGenericType(DataRow row) where T : class, new() + { + Type entityType = typeof(T); + T objEntity = new T(); + foreach (DataColumn column in row.Table.Columns) + { + object value = row[column.ColumnName]; + if (value == DBNull.Value) value = null; + PropertyInfo property = entityType.GetProperty(column.ColumnName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public); + try + { + if (property != null && property.CanWrite) + property.SetValue(objEntity, value, null); + } + catch (Exception ex) + { + throw ex; + } + } + return objEntity; + } + + /// + /// registra su REDIS eventuale superamento numero limite di call x il metodo in oggetto + /// + /// + private static void saveCallRec(string callCountKey) + { + // conto la richiesta nel contatore REDIS + long nCall = memLayer.ML.setRCntI(mHash($"COUNT:pCall:{callCountKey}")); + //... se == nCall2Log scrivo su log e resetto + long nCall2Log = memLayer.ML.cdvi("nCall2Log"); + if (nCall >= nCall2Log) + { + // loggo + logger.lg.scriviLog($"{callCountKey}: {nCall} call received", tipoLog.INFO); + // resetto! + memLayer.ML.resetRCnt(mHash($"COUNT:pCall:{callCountKey}")); + } + } + + /// + /// verifica se sia necessario inserire un cambio di stato impianto in modalità batch + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void checkCambiaStatoBatch(tipoInputEvento tipoInput, string IdxMacchina, DateTime InizioStato, int IdxTipo, string CodArt, string Value, int MatrOpr, string pallet) + { + int _logLevel = memLayer.ML.CRI("_logLevel"); + DS_applicazione.TransizioneStatiDataTable tabTransStati; + DS_applicazione.TransizioneStatiRow rigaTransStati; + switch (tipoInput) + { + case tipoInputEvento.barcode: + // effettuo cambio stato INDIPENDENTEMENTE da stato precedente + try + { + tabTransStati = MapoDbObj.taTranSt.GetUserForcedTransitions(IdxMacchina, IdxTipo); + if (tabTransStati != null) + { + if (tabTransStati.Count > 0) + { + rigaTransStati = tabTransStati[0]; + // solo se cambia stato... + if (rigaTransStati.IdxStato != rigaTransStati.next_IdxStato) + { + MapoDbObj.taDiario.InsStatoBatch(IdxMacchina, InizioStato, rigaTransStati.next_IdxStato, CodArt, Value, MatrOpr, pallet); + // aggiorno MSE + taMSE.forceRecalc(0, IdxMacchina); + } + } + else + { + if (_logLevel > 6) + { + logger.lg.scriviLog($"Non trovata riga per: BARCODE | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}", tipoLog.INFO); + } + } + } + } + catch (Exception exc) + { + // non dovrebbe succedere... input utente da barcode dovrebbero TUTTI essere + // inseriti in tab transizione con famiglia 1... + logger.lg.scriviLog($"Errore controllo transizione stato x evento barcode: BARCODE | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + break; + + case tipoInputEvento.hw: + // verifico se ci sia necessità di cambio stato + try + { + tabTransStati = MapoDbObj.taTranSt.GetHwTransitions(IdxMacchina, IdxTipo); + if (tabTransStati != null) + { + if (tabTransStati.Count > 0) + { + rigaTransStati = tabTransStati[0]; + if (rigaTransStati != null) + { + // solo se cambia stato... + if (rigaTransStati.IdxStato != rigaTransStati.next_IdxStato) + { + MapoDbObj.taDiario.InsStatoBatch(IdxMacchina, InizioStato, rigaTransStati.next_IdxStato, CodArt, Value, MatrOpr, pallet); + } + } + } + else + { + if (_logLevel > 6) + { + logger.lg.scriviLog($"Non trovata riga per: HW | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}", tipoLog.INFO); + } + } + } + } + catch (Exception exc) + { + // non trovo riga [0]... NON scrivo! + logger.lg.scriviLog($"Errore controllo transizione stato x evento barcode: HW | IdxMacchina: {IdxMacchina} | IdxTipo: {IdxTipo} | CodArt: {CodArt} | Value: {Value} | MatrOpr: {MatrOpr} | pallet: {pallet}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + break; + } + } + + /// + /// sistemazione timeout comandi nei tableadapter + /// + private void fixCommandTimeout() + { + int sqlLongCommandTimeout = memLayer.ML.CRI("sqlLongCommandTimeout") > 1 ? memLayer.ML.CRI("sqlLongCommandTimeout") : 300; + SetAllCommandTimeouts(taComm, sqlLongCommandTimeout); + } + + /// + /// Recupero dati stato prod da macchina... + /// + /// + /// + /// + /// + private bool getStatoProd(string idxMacchina, ref DS_ProdTempi.StatoProdDataTable datiProdAct, DateTime dataRif) + { + bool answ = false; + try + { + // recupero con stored NUOVA... + //2020.01.31 NUOVO oggetto (NON singleton) + DataLayer man = new DataLayer(); + datiProdAct = man.taStatoProd.GetData(idxMacchina, dataRif); + if (datiProdAct.Rows.Count > 0) + { + // solo SE ho idxODL (altrimenti loggo errore) + if (datiProdAct[0].IdxOdl > 0) + { + answ = true; + } + else + { + // verifico se ho già questo errore attivo IN REDIS (altrimenti reinvio) + logger.lg.scriviLog($"pzCounterTC: Non trovato currODL x idxMacchina {idxMacchina} ", $"idxMacchina {idxMacchina} | IdxOdl {datiProdAct[0].IdxOdl} | pzTot {datiProdAct[0].PzTotODL} | dataRif {dataRif}", tipoLog.WARNING); + } + } + else + { + logger.lg.scriviLog($"pzCounterTC: Non trovate righe in currODL {idxMacchina}", $"Non trovate righe in currODL x idxMacchina {idxMacchina}: datiProdAct vuota", tipoLog.WARNING); + } + } + catch (Exception exc) + { + logger.lg.scriviLog($"[pzCounterTC] Eccezione in pzCounterTC x idxMacchina {idxMacchina}", $"[pzCounterTC] Eccezione in pzCounterTC x idxMacchina {idxMacchina}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + return answ; + } + + /// + /// Calcola l'effettivo valore da passare alla macchina a stati INGRESSI data conf Macchine2FamigliaIngressi + /// + /// + /// + /// + private string preProcInput(string idxMacchina, string valore) + { + string newVal = ""; + try + { + // variabili + int valINT = 0; + int BitFilt = 0; + int BSR = 0; + bool ExplodeBit = false; + int NumBit = 0; + int newValInt = 0; + // recupero parametri... + int.TryParse(mDatiMacchinaVal(idxMacchina, "BitFilt"), out BitFilt); + int.TryParse(mDatiMacchinaVal(idxMacchina, "BSR"), out BSR); + Boolean.TryParse(mDatiMacchinaVal(idxMacchina, "ExplodeBit"), out ExplodeBit); + int.TryParse(mDatiMacchinaVal(idxMacchina, "NumBit"), out NumBit); // non usato (x ora) + // recupero valore + valINT = int.Parse(valore, NumberStyles.HexNumber); + // filtro + newValInt = utility.bMaskInt(valINT, BitFilt); + // effettuo eventuale BitShiftRight + if (BSR > 0) + { + newValInt = newValInt >> BSR; + } + // effettuo eventuale esplosione in BIT esclusivi + if (ExplodeBit) + { + newValInt = Convert.ToInt32(1 << newValInt); + } + // riconverto a STRING HEX!!! + newVal = newValInt.ToString("X"); + } + catch + { + newVal = valore; + } + + return newVal; + } + + private void SetAllCommandTimeouts(object adapter, int timeout) + { + var commands = adapter.GetType().InvokeMember( + "CommandCollection", + BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic, + null, adapter, new object[0]); + var sqlCommand = (SqlCommand[])commands; + foreach (var cmd in sqlCommand) + { + cmd.CommandTimeout = timeout; + } + } + + /// + /// cerca codice in anagrafica macchine ed eventualmente inserisce nuova macchina + /// + /// + private void verificaIdxMacchina(string IdxMacchina) + { + bool needDB = false; + if (!memLayer.ML.CRB("disable_verificaIdxMacchina")) + { + if (memLayer.ML.CRB("IOB_RedEnab")) + { + try + { + // esecuzione in REDIS...cerco status macchina... + if (mDatiMacchine(IdxMacchina).Count == 0) + { + needDB = true; + } + } + catch { } + } + // ...oppure segno richiesta DB... + else + { + needDB = true; + } + if (needDB) + { + // 2017.07.11 se richiesto di NON usare singleton... riporto FUORI la gestione + // NUOVO oggetto + if (memLayer.ML.CRB("disable_singleton")) + { + taMacchine = new DS_applicazioneTableAdapters.MacchineTableAdapter(); + MapoDbObj.taMSM = new DS_applicazioneTableAdapters.MicroStatoMacchinaTableAdapter(); + } + // verifico esistenza macchina + if (taMacchine.GetByIdx(IdxMacchina).Rows.Count == 0) + { + // inserisco nuova macchina... + taMacchine.Insert(IdxMacchina, "9999", IdxMacchina, "Macchina non codificata", "-", "http://", "nd", "col", 0, 0); + } + // verifico ci sia un microstato macchina... + if (MapoDbObj.taMSM.getByIdxMacchina(IdxMacchina).Rows.Count == 0) + { + // inserisco nuovo stato... + MapoDbObj.taMSM.Insert(IdxMacchina, 0, DateTime.Now, "00"); + } + } + } + } + + #endregion Private Methods } } \ No newline at end of file diff --git a/MapoSDK/Enums.cs b/MapoSDK/Enums.cs index ec175d0f..744e2006 100644 --- a/MapoSDK/Enums.cs +++ b/MapoSDK/Enums.cs @@ -20,27 +20,6 @@ namespace MapoSDK error } - /// - /// Tipologia dato Raw Transfer - /// - /// serializzazione Native - /// [JsonConverter(typeof(JsonStringEnumConverter))] - /// serializzazione Newtonsoft json - /// [JsonConverter(typeof(StringEnumConverter))] - [JsonConverter(typeof(StringEnumConverter))] - public enum rawTransfType - { - ND = 0, - /// - /// Icoel: Batch info - /// - IcoelBatch, - /// - /// Icoel: Variety + layout info relative - /// - IcoelVarInfo - } - /// /// Tipo di IOB /// @@ -80,7 +59,7 @@ namespace MapoSDK InputRegister = 3, /// - /// ModBus Holding Register 4xxxxx (int[] convertibile a vari int/real) - OUT R/W + /// ModBus Holding Register 4xxxxx (int[] convertibile a vari int/real) - OUT R/W /// HoldingRegister = 4 } @@ -100,11 +79,21 @@ namespace MapoSDK /// Int, + /// + /// Tipo UInt16 reversed LowHigh + /// + IntLH, + /// /// Tipo Int32 intero 32bit /// DInt, + /// + /// Tipo UInt32 reversed LowHigh + /// + DIntLH, + /// /// Tipo UInt16, intero 16bit /// @@ -142,36 +131,73 @@ namespace MapoSDK /// /// Tipo FLOAT 32 bit con endiannes standard (es modbus) - /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ - /// Float - Big Endian (ABCD) + /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ Float - + /// Big Endian (ABCD) /// FloatABCD, /// /// Tipo FLOAT 32 bit con endiannes NON standard (es modbus) - /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ - /// Float - Mid-Big Endian (BADC) + /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ Float - + /// Mid-Big Endian (BADC) /// FloatBADC, /// /// Tipo FLOAT 32 bit con endiannes NON standard (es modbus) - /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ - /// Float - Mid-Little Endian (CDAB) + /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ Float - + /// Mid-Little Endian (CDAB) /// FloatCDAB, /// /// Tipo FLOAT 32 bit con endiannes NON standard (es modbus) - /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ - /// Float - Little Endian (DCBA) + /// https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ Float - + /// Little Endian (DCBA) /// FloatDCBA, /// - /// Valore bitmap, inteso come array di bit ognuno da trattare come uno stato on/off indipendente e sommabile (es allarmi) + /// Valore bitmap, inteso come array di bit ognuno da trattare come uno stato on/off + /// indipendente e sommabile (es allarmi) /// - BitMap + BitMap, + + /// + /// Tipo Byte 8 bit equivalente a BitMap + /// + Byte, + + /// + /// Tipo UInt16 intero senza segno 16bit + /// + UInt, + + /// + /// Tipo UInt32 intero senza segno 32bit + /// + UDInt + } + + /// + /// Tipologia dato Raw Transfer + /// + /// serializzazione Native [JsonConverter(typeof(JsonStringEnumConverter))] serializzazione + /// Newtonsoft json [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(StringEnumConverter))] + public enum rawTransfType + { + ND = 0, + + /// + /// Icoel: Batch info + /// + IcoelBatch, + + /// + /// Icoel: Variety + layout info relative + /// + IcoelVarInfo } /// @@ -251,7 +277,8 @@ namespace MapoSDK setProg, /// - /// Indica al PLC di impostare il numero di pezzi da produrre per la commessa (impostato come value) + /// Indica al PLC di impostare il numero di pezzi da produrre per la commessa (impostato + /// come value) /// setPzComm, @@ -306,7 +333,8 @@ namespace MapoSDK nd, /// - /// identifica una matricola operatore nel formato OPxxxxx (xxxxx è un intero che rappresenta la matricola, std fino a 8 cifre) + /// identifica una matricola operatore nel formato OPxxxxx (xxxxx è un intero che + /// rappresenta la matricola, std fino a 8 cifre) /// matrOperatore, @@ -326,7 +354,8 @@ namespace MapoSDK confermaProduzione, /// - /// identifica un cartellino di dichiarazione fermata nel formato FExxxx dove xxxx è idxEvento dichiarato... + /// identifica un cartellino di dichiarazione fermata nel formato FExxxx dove xxxx è + /// idxEvento dichiarato... /// dichiaraFermata,