diff --git a/THermo.Active.Thermocamera/ThermocameraComunicator.cs b/THermo.Active.Thermocamera/ThermocameraComunicator.cs index 9c218a2a..d3e26ecb 100644 --- a/THermo.Active.Thermocamera/ThermocameraComunicator.cs +++ b/THermo.Active.Thermocamera/ThermocameraComunicator.cs @@ -84,7 +84,8 @@ namespace Thermo.Active.Thermocamera int sleepTime = 500; byte[] bytesToRead = new byte[NUM_CHAR_MSG]; - if (!accessor.CanRead) return false; + if (!accessor.CanRead) + return false; //Read Pre-Command while (response != RES) @@ -102,11 +103,15 @@ namespace Thermo.Active.Thermocamera //Elaborate String string textRecieved = Encoding.UTF8.GetString(bytesToRead); - if (textRecieved == null) return false; + if (textRecieved == null) + return false; string[] textSplitted = textRecieved.Replace("\0", string.Empty).Split(';'); - if (textSplitted.Length < 2) return false; - if (textSplitted[0] != command) return false; + if (textSplitted.Length < 2) + return false; + + if (textSplitted[0] != command) + return false; char[] bufferToClean = Enumerable.Repeat('\0', NUM_CHAR_MSG).ToArray(); accessor.WriteArray(0, bufferToClean, 0, bufferToClean.Length); @@ -171,7 +176,7 @@ namespace Thermo.Active.Thermocamera if (!readCommand(accessorResp, tempCommand, timeoutMS, out response)) return false; - string[] respSplitted = response.Replace(",",".").Split(';'); + string[] respSplitted = response.Replace(",", ".").Split(';'); int idxResp = 0; foreach (var item in points) { @@ -244,7 +249,7 @@ namespace Thermo.Active.Thermocamera return false; if (!readCommand(accessorResp, tempCommand, timeoutMS, out response)) return false; - if (response != "1;") + if (!response.StartsWith("1;")) return false; return true; } @@ -266,7 +271,7 @@ namespace Thermo.Active.Thermocamera return false; if (!readCommand(accessorResp, tempCommand, timeoutMS, out response)) return false; - if (response != "True;") + if (!response.StartsWith("True;")) return false; } else diff --git a/Thermo.Active.Config/Config/serverConfig.xml b/Thermo.Active.Config/Config/serverConfig.xml index 1452ba2f..46b0dcee 100644 --- a/Thermo.Active.Config/Config/serverConfig.xml +++ b/Thermo.Active.Config/Config/serverConfig.xml @@ -59,11 +59,11 @@ flirImgX - 800 + 1000 flirImgY - 1002 + 803 resistSizeX @@ -87,7 +87,7 @@ ThermoCameraXpos - 68 + 93 ThermoCameraYpos diff --git a/Thermo.Active.Config/ServerConfigController.cs b/Thermo.Active.Config/ServerConfigController.cs index 74411ce6..8ee9f64a 100644 --- a/Thermo.Active.Config/ServerConfigController.cs +++ b/Thermo.Active.Config/ServerConfigController.cs @@ -598,6 +598,8 @@ namespace Thermo.Active.Config int ResistId = 0; int oldRow = 0; int currIdBoard = 0; + int maxCol = 0; + int maxRow = 0; RiskBoardConfig = new List(); RiskResistConfig = new List(); RiskChannelConfig = new List(); @@ -651,8 +653,8 @@ namespace Thermo.Active.Config SetpointThermo = 0, MaxPower = riferimento.Potenza, NumResist = 1, + refPosDistance = 999999, refPos = new ThermoPoint(), // imposto default a 0 - Dimensione = riferimento.Dimensione, // 2020.07.27 applicato x tutti CalcIchMin = true //riferimento.Modello.Contains("Quarzo") || riferimento.Modello.Contains("Alogena") }); @@ -679,6 +681,7 @@ namespace Thermo.Active.Config else { numCol++; + maxCol = numCol > maxCol ? numCol : maxCol; } // cerco il TIPO... @@ -690,8 +693,10 @@ namespace Thermo.Active.Config Row = resistenza.Riga, Column = numCol, IdChannel = resistenza.Canale, - Dimension = riferimento.Dimensione + Dimension = riferimento.Dimensione, + IdReflector = riflettore.Tipo }); ; + maxRow = resistenza.Riga > maxRow ? resistenza.Riga : maxRow; } } @@ -717,6 +722,88 @@ namespace Thermo.Active.Config // ciclo ora per calcolare TUTTE le posizioni di riferimento dei canali (prendendo il centro delle resistenze) Dictionary newPos = new Dictionary(); var listChSup = RiskChannelConfig.Where(x => x.IdReflector == 0); + + // spazzo riga x riga da elenco resistenze... + var listResist = RiskResistConfig.Where(x => x.IdReflector == 0); + int currRow = -1; + double currX = 0; + for (int rigaCorr = 0; rigaCorr <= maxRow; rigaCorr++) + { + for (int colCorr = 0; colCorr <= maxCol; colCorr++) + { + var currResist = listResist.FirstOrDefault(x => x.Row == rigaCorr && x.Column == colCorr); + if (currResist != null) + { + // se cambio riga --> mi metto a metà della prima cella + if (currResist.Row != currRow) + { + currX = (currResist.Dimension * resistSizeX) / 2; + currRow = currResist.Row; + } + else + { + // calcolo coordinata X CumSum + currX += (currResist.Dimension * resistSizeX); + } + //// reset distanza + //actDist = warmerPlanSizeX + warmerPlanSizeY; + //minDist = warmerPlanSizeX + warmerPlanSizeY; + + // tutti i calcoli in coordinate mm del riscaldo + punto = new ThermoPoint() { X = (int)currX, Y = currResist.Row * resistSizeY + resistSizeY / 2 }; + puntoFlirImg = new ThermoPoint(); + actDist = ThermoPoint.distance(punto, centro); + // cerco i dati del canale attuale... + var currChannel = RiskChannelConfig.FirstOrDefault(x => x.IdChannel == currResist.IdChannel); + if (currChannel.refPosDistance > actDist) + { + // riscalo il punto per la dimensione della FLIR + puntoFlirImg.X = punto.X * flirImgX / warmerPlanSizeX; + puntoFlirImg.Y = punto.Y * flirImgY / warmerPlanSizeY; + currChannel.refPos = puntoFlirImg; + currChannel.refPosDistance = actDist; + } + } + } + } + + int zero = 0; +#if false + foreach (var currResist in listResist.OrderBy(x => x.Row).OrderBy(x => x.Column)) + { + // se cambio riga --> mi metto a metà della prima cella + if (currResist.Row != currRow) + { + currX = (currResist.Dimension * resistSizeX) / 2; + currRow = currResist.Row; + } + else + { + // calcolo coordinata X CumSum + currX += (currResist.Dimension * resistSizeX); + } + //// reset distanza + //actDist = warmerPlanSizeX + warmerPlanSizeY; + //minDist = warmerPlanSizeX + warmerPlanSizeY; + + // tutti i calcoli in coordinate mm del riscaldo + punto = new ThermoPoint() { X = (int)currX, Y = currResist.Row * resistSizeY + resistSizeY / 2 }; + puntoFlirImg = new ThermoPoint(); + actDist = ThermoPoint.distance(punto, centro); + // cerco i dati del canale attuale... + var currChannel = RiskChannelConfig.FirstOrDefault(x => x.IdChannel == currResist.IdChannel); + if (currChannel.refPosDistance > actDist) + { + // riscalo il punto per la dimensione della FLIR + puntoFlirImg.X = punto.X * flirImgX / warmerPlanSizeX; + puntoFlirImg.Y = punto.Y * flirImgY / warmerPlanSizeY; + currChannel.refPos = puntoFlirImg; + currChannel.refPosDistance = actDist; + } + } +#endif + +#if false foreach (var currChannel in listChSup) { // reset distanza @@ -745,6 +832,7 @@ namespace Thermo.Active.Config } } } +#endif } /// diff --git a/Thermo.Active.Core/ThreadsFunctions.cs b/Thermo.Active.Core/ThreadsFunctions.cs index e2023b7e..26c4fb77 100644 --- a/Thermo.Active.Core/ThreadsFunctions.cs +++ b/Thermo.Active.Core/ThreadsFunctions.cs @@ -32,15 +32,25 @@ using System.Drawing; public static class ThreadsFunctions { - public static int axisRtCounter = 0; - public static int recipeRtCounter = 0; - public static int modulesRtCounter = 0; - public static bool reconnectionIsRunning = false; - - private static ConcurrentDictionary Timers = new ConcurrentDictionary(); - private static ConcurrentDictionary Counter = new ConcurrentDictionary(); + #region Private Fields private static Thread ConnThread; + private static ConcurrentDictionary Counter = new ConcurrentDictionary(); + private static ConcurrentDictionary Timers = new ConcurrentDictionary(); + + #endregion Private Fields + + #region Public Fields + + public static int axisRtCounter = 0; + public static int modulesRtCounter = 0; + public static int recipeRtCounter = 0; + public static bool reconnectionIsRunning = false; + + #endregion Public Fields + + #region Private Methods + /// /// restituisce il periodo di campionamento SE configurato, altrimenti 1000 ms /// @@ -56,8 +66,167 @@ public static class ThreadsFunctions return answ; } + #endregion Private Methods + #region Functions + /// + /// Manage action for conf request + /// + public static void ManageConfRequest() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + try + { + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Manage status command + libraryError = ncAdapter.ManageConfRequest(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("confReq"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException ex) + { + ncAdapter.Dispose(); + } + } + + /// + /// Manage Requesto from PLC for FLir Image --> temp readout + /// 1) check if pending request + /// 2) give ack + /// 3) request image to ext sw + /// 4) request temp sampling from ext sw + /// + /// + public static void ManageFlirCamera() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + bool flirImageReq = false; + sw.Restart(); + int tOut = 30000; + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // check if there is a photo request pending + libraryError = ncAdapter.checkFlirImageRequest(out flirImageReq); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + if (flirImageReq) + { + bool done = false; + // if requested --> give ack! + ncAdapter.ManageFlirStrobe(); + // requesto photo from library + done = ThermocameraComunicator.getInstance().takePicture(tOut); + if (done) + { + // init + Dictionary actualTemp = new Dictionary(); + Dictionary chPoints = new Dictionary(); + // recupero punti centrali resistenze + ncAdapter.GetWarmersChannelCenterPoints(out chPoints); + // richiesta temperature per i punti + done = ThermocameraComunicator.getInstance().readMultiTemperatures(chPoints, tOut, out actualTemp); + // salvo dati temp sul PLC + ncAdapter.WriteRecipeWarmChTCamTempAct(actualTemp); + // give PLC strobe for uploaded Actual TEMP from image + ncAdapter.SendTCamImageReadyStrb(); + } + } + } + else + RestoreConnection(); + + sw.Stop(); + + // Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("FlirCamera"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + /// + /// Manage status/command words for actions + /// + public static void ManageStatusCommand() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + try + { + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Manage status command + libraryError = ncAdapter.ManageStatusCommand(); + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("statusCommand"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException ex) + { + ncAdapter.Dispose(); + } + } + public static void ManageWatchdog() { NcAdapter ncAdapter = new NcAdapter(); @@ -103,88 +272,7 @@ public static class ThreadsFunctions ncAdapter.Dispose(); } } - /// - /// Manage status/command words for actions - /// - public static void ManageStatusCommand() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Manage status command - libraryError = ncAdapter.ManageStatusCommand(); - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("statusCommand"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException ex) - { - ncAdapter.Dispose(); - } - } - /// - /// Manage action for conf request - /// - public static void ManageConfRequest() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Manage status command - libraryError = ncAdapter.ManageConfRequest(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("confReq"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException ex) - { - ncAdapter.Dispose(); - } - } public static void ReadAlarms() { NcAdapter ncAdapter = new NcAdapter(); @@ -228,13 +316,14 @@ public static class ThreadsFunctions ncAdapter.Dispose(); } } - public static void ReadPowerOnData() + + public static void ReadAreaData() { NcAdapter ncAdapter = new NcAdapter(); Stopwatch sw = new Stopwatch(); - try { + // Try connection CmsError libraryError = ncAdapter.Connect(); if (libraryError.errorCode != 0) ManageLibraryError(libraryError); @@ -242,26 +331,26 @@ public static class ThreadsFunctions while (true) { sw.Restart(); + // Check if client is connected if (ncAdapter.numericalControl.NC_IsConnected()) { - // Get Data from NC - libraryError = ncAdapter.GetPowerOnData(out DTOPowerOnDataModel powerOnData); - if (libraryError.errorCode != 0) + // Get new data from PLC... info x area lastra... la % di X / Y + libraryError = ncAdapter.GetWarmMaterialArea(out Dictionary currAreaPerc); + if (libraryError.IsError()) ManageLibraryError(libraryError); - else - // Send through signalR - MessageServices.Current.Publish(SEND_POWER_ON_DATA, null, powerOnData); + // pubblico + MessageServices.Current.Publish(SEND_THERMO_AREA_DATA, null, currAreaPerc); } else RestoreConnection(); + sw.Stop(); - //Update thread timer + // Update thread timer UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("powerOn"), (int)sw.ElapsedMilliseconds)); + Thread.Sleep(CalcSleepTime(samplMsec("area"), (int)sw.ElapsedMilliseconds)); } } catch (ThreadAbortException) @@ -269,192 +358,7 @@ public static class ThreadsFunctions ncAdapter.Dispose(); } } - public static void ReadProcessesPPStatus() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get Data from NC - libraryError = ncAdapter.GetProcessesData(out DTOProcessesDataModel processesPPData); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - else - { - // Send processes through signalR - MessageServices.Current.Publish(SEND_PROCESSES_DATA, null, processesPPData); - } - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - - // Wait - Thread.Sleep(CalcSleepTime(200, (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadEnabledFunctionality() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get Data from NC - libraryError = ncAdapter.GetFunctionsMappedWithNC(out List functionsAccessList); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - else - // Send through signalR - MessageServices.Current.Publish(SEND_FUNCTIONALITY_DATA, null, functionsAccessList); - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("functionEnab"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadExpiredMaintenances() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get Data from database and PLC - libraryError = ncAdapter.GetExpiredMaintenances(out List expiredMaintenances); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - else - // Send through signalR - MessageServices.Current.Publish(SEND_EXPIRED_MAINTENANCES_DATA, null, expiredMaintenances); - - // 2020.06.18 commentata da indicazione di Lucio Maranta (NON dovrebbe servire ora) -#if false - //Manage Candies - libraryError = ncAdapter.ManageCandies(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); -#endif - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("expMan"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - catch (Exception ex) - { - - } - } - public static void ReadUserSoftKeysData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get softkey data from config and PLC - libraryError = ncAdapter.GetUserSoftKeys(out List softKeys); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - else - // Send through signalR - MessageServices.Current.Publish(SEND_USER_SOFTKEYS_DATA, null, softKeys); - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("userSK"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } /// /// Lettura valori ASSI (tutti i disponibili) /// @@ -507,7 +411,8 @@ public static class ThreadsFunctions ncAdapter.Dispose(); } } - public static void ReadScadaData() + + public static void ReadEnabledFunctionality() { NcAdapter ncAdapter = new NcAdapter(); Stopwatch sw = new Stopwatch(); @@ -523,17 +428,15 @@ public static class ThreadsFunctions { sw.Restart(); - // Check if client is connected if (ncAdapter.numericalControl.NC_IsConnected()) { - List scadaToRead = ProductionScadaSchema.Concat(SubscribedScada).ToList(); - - // Get new data from PLC - libraryError = ncAdapter.ReadScadasData(scadaToRead, out List scadas); - if (libraryError.IsError()) + // Get Data from NC + libraryError = ncAdapter.GetFunctionsMappedWithNC(out List functionsAccessList); + if (libraryError.errorCode != 0) ManageLibraryError(libraryError); - - MessageServices.Current.Publish(SEND_SCADA_DATA, null, scadas); + else + // Send through signalR + MessageServices.Current.Publish(SEND_FUNCTIONALITY_DATA, null, functionsAccessList); } else RestoreConnection(); @@ -542,8 +445,9 @@ public static class ThreadsFunctions //Update thread timer UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait - Thread.Sleep(CalcSleepTime(samplMsec("scada"), (int)sw.ElapsedMilliseconds)); + Thread.Sleep(CalcSleepTime(samplMsec("functionEnab"), (int)sw.ElapsedMilliseconds)); } } catch (ThreadAbortException) @@ -551,6 +455,62 @@ public static class ThreadsFunctions ncAdapter.Dispose(); } } + + public static void ReadExpiredMaintenances() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get Data from database and PLC + libraryError = ncAdapter.GetExpiredMaintenances(out List expiredMaintenances); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + else + // Send through signalR + MessageServices.Current.Publish(SEND_EXPIRED_MAINTENANCES_DATA, null, expiredMaintenances); + + // 2020.06.18 commentata da indicazione di Lucio Maranta (NON dovrebbe servire ora) +#if false + //Manage Candies + libraryError = ncAdapter.ManageCandies(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); +#endif + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("expMan"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + catch (Exception ex) + { + } + } + public static void ReadGaugeData() { NcAdapter ncAdapter = new NcAdapter(); @@ -570,7 +530,6 @@ public static class ThreadsFunctions // Check if client is connected if (ncAdapter.numericalControl.NC_IsConnected()) { - // Get new data from PLC libraryError = ncAdapter.ReadGaugeData(out Dictionary currentLiveProd); if (libraryError.IsError()) @@ -594,456 +553,7 @@ public static class ThreadsFunctions ncAdapter.Dispose(); } } - public static void ReadProdPanelData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get new data from PLC (and log if changed...) - libraryError = ncAdapter.ReadProdPanel(out DTOThermoPanelProd currentProdPanel); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - - MessageServices.Current.Publish(SEND_THERMO_PROD_PANEL_DATA, null, currentProdPanel); - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait 500 ms - Thread.Sleep(CalcSleepTime(samplMsec("prodPanel"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadProdInfoData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get new data from PLC (and log if changed...) - libraryError = ncAdapter.ReadProdInfoData(out DTOProdInfo prodInfoData); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - - MessageServices.Current.Publish(SEND_THERMO_PROD_INFO_DATA, null, prodInfoData); - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("prodInfo"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadProdCycleData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get new data from PLC - libraryError = ncAdapter.ReadProdCycleData(out ThermoModels.ProdCycleModel prodCycleData); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - - MessageServices.Current.Publish(SEND_THERMO_PROD_CYCLE_DATA, null, prodCycleData); - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("prodCycle"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadRecipeData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - // ogni n counter leggo anche dati NON RT - recipeRtCounter--; - bool onlyRt = recipeRtCounter > 0; - //check reset... - recipeRtCounter = recipeRtCounter < 0 ? 4 : recipeRtCounter; - - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get new data from PLC - libraryError = ncAdapter.ReadRecipeData(onlyRt, false, out Dictionary currRecipe); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - - MessageServices.Current.Publish(SEND_THERMO_RECIPE_FULL, null, currRecipe); - - // ora gestisco la overview! - libraryError = ncAdapter.GetRecipeOverview(out Dictionary currOverview); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - - MessageServices.Current.Publish(SEND_THERMO_RECIPE_OVERWIEW, null, currOverview); - - // ora gestisco la lettura della overview di "modificata - DTORecipeStatus message = new DTORecipeStatus() - { - recipeName = NcAdapter.RecipeLiveData.RecipeName, - hasChanged = NcAdapter.RecipeLiveData.hasChanged - }; - - MessageServices.Current.Publish(SEND_THERMO_RECIPE_CHANGED, null, message); - - // verifico se dal PLC è segnalato che i setpointHMI sono invalidati, nel qual caso INVIO - bool setpointHmiInvalidated = false; - libraryError = ncAdapter.checkSetpointInvalidated(out setpointHmiInvalidated); - if (setpointHmiInvalidated) - { - // ora gestisco l'ack della richiesta - libraryError = ncAdapter.doAckSetpointInvalidated(); - } - // pubblico booleana dei setpointHMI invalidati - MessageServices.Current.Publish(SEND_THERMO_RECIPE_SETPOINTHMI_CHANGED, null, setpointHmiInvalidated); - - } - else - RestoreConnection(); - - sw.Stop(); - - // Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("recipe"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadWarmersData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - int readCount = 0; - bool useCache = false; - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // every 10 reads all data... - useCache = (readCount != 0); - // Get new data from PLC - libraryError = ncAdapter.ReadWarmers(useCache, out Dictionary currWarmers); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - // pubblico - MessageServices.Current.Publish(SEND_THERMO_WARMERS_DATA, null, currWarmers); - readCount++; - // ciclo resettato ogni 20 - readCount = readCount % 20; - } - else - RestoreConnection(); - - sw.Stop(); - - // Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("warmers"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - /// - /// Manage Requesto from PLC for FLir Image --> temp readout - /// 1) check if pending request - /// 2) give ack - /// 3) request image to ext sw - /// 4) request temp sampling from ext sw - /// - /// - public static void ManageFlirCamera() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - bool flirImageReq = false; - sw.Restart(); - int tOut = 10000; - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // check if there is a photo request pending - libraryError = ncAdapter.checkFlirImageRequest(out flirImageReq); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - - if (flirImageReq) - { - bool done = false; - // if requested --> give ack! - ncAdapter.ManageFlirStrobe(); - // requesto photo from library - done = ThermocameraComunicator.getInstance().takePicture(tOut); - if (done) - { - // init - Dictionary actualTemp = new Dictionary(); - Dictionary chPoints = new Dictionary(); - // recupero punti centrali resistenze - ncAdapter.GetWarmersChannelCenterPoints(out chPoints); - // richiesta temperature per i punti - done = ThermocameraComunicator.getInstance().readMultiTemperatures(chPoints, tOut, out actualTemp); - // salvo dati temp sul PLC - ncAdapter.WriteRecipeWarmChTCamTempAct(actualTemp); - // give PLC strobe for uploaded Actual TEMP from image - ncAdapter.SendTCamImageReadyStrb(); - } - } - - } - else - RestoreConnection(); - - sw.Stop(); - - // Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("FlirCamera"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadAreaData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get new data from PLC... info x area lastra... la % di X / Y - libraryError = ncAdapter.GetWarmMaterialArea(out Dictionary currAreaPerc); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - // pubblico - MessageServices.Current.Publish(SEND_THERMO_AREA_DATA, null, currAreaPerc); - } - else - RestoreConnection(); - - sw.Stop(); - - // Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("area"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadModulesData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - // Check if client is connected - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // Get new data from PLC - libraryError = ncAdapter.ReadModulesBlock(out Dictionary currModules); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - - MessageServices.Current.Publish(SEND_THERMO_MODULE_DATA, null, currModules); - } - else - RestoreConnection(); - - sw.Stop(); - - // Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("modules"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } - public static void ReadMComandsData() - { - NcAdapter ncAdapter = new NcAdapter(); - Stopwatch sw = new Stopwatch(); - - try - { - // Try connection - CmsError libraryError = ncAdapter.Connect(); - if (libraryError.errorCode != 0) - ManageLibraryError(libraryError); - - while (true) - { - sw.Restart(); - - if (ncAdapter.numericalControl.NC_IsConnected()) - { - // solo x S7Net... - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - libraryError = ncAdapter.GetM156Data(out List m156Data); - if (libraryError.IsError()) - ManageLibraryError(libraryError); - else - MessageServices.Current.Publish(SEND_M156_DATA, null, m156Data); - } - - } - else - RestoreConnection(); - - sw.Stop(); - - //Update thread timer - UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); - - // Wait - Thread.Sleep(CalcSleepTime(samplMsec("mCommands"), (int)sw.ElapsedMilliseconds)); - } - } - catch (ThreadAbortException) - { - ncAdapter.Dispose(); - } - } public static void ReadM154Data() { NcAdapter ncAdapter = new NcAdapter(); @@ -1100,7 +610,6 @@ public static class ThreadsFunctions //if (CmsConnectConfig.Enabled) if (ServerStartupConfig.CmsConnectReady) { - if (m154.Parameters.Count() >= 2 && m154.Parameters[0] == "SOUR") { // Convert tag string in Pascal Case and add to result string @@ -1218,21 +727,539 @@ public static class ThreadsFunctions ncAdapter.Dispose(); } } + + public static void ReadMComandsData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // solo x S7Net... + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + libraryError = ncAdapter.GetM156Data(out List m156Data); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + else + MessageServices.Current.Publish(SEND_M156_DATA, null, m156Data); + } + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("mCommands"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadModulesData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get new data from PLC + libraryError = ncAdapter.ReadModulesBlock(out Dictionary currModules); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + MessageServices.Current.Publish(SEND_THERMO_MODULE_DATA, null, currModules); + } + else + RestoreConnection(); + + sw.Stop(); + + // Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("modules"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadPowerOnData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get Data from NC + libraryError = ncAdapter.GetPowerOnData(out DTOPowerOnDataModel powerOnData); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + else + // Send through signalR + MessageServices.Current.Publish(SEND_POWER_ON_DATA, null, powerOnData); + } + else + RestoreConnection(); + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("powerOn"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadProcessesPPStatus() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get Data from NC + libraryError = ncAdapter.GetProcessesData(out DTOProcessesDataModel processesPPData); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + else + { + // Send processes through signalR + MessageServices.Current.Publish(SEND_PROCESSES_DATA, null, processesPPData); + } + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + + // Wait + Thread.Sleep(CalcSleepTime(200, (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadProdCycleData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get new data from PLC + libraryError = ncAdapter.ReadProdCycleData(out ThermoModels.ProdCycleModel prodCycleData); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + MessageServices.Current.Publish(SEND_THERMO_PROD_CYCLE_DATA, null, prodCycleData); + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("prodCycle"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadProdInfoData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get new data from PLC (and log if changed...) + libraryError = ncAdapter.ReadProdInfoData(out DTOProdInfo prodInfoData); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + MessageServices.Current.Publish(SEND_THERMO_PROD_INFO_DATA, null, prodInfoData); + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("prodInfo"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadProdPanelData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get new data from PLC (and log if changed...) + libraryError = ncAdapter.ReadProdPanel(out DTOThermoPanelProd currentProdPanel); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + MessageServices.Current.Publish(SEND_THERMO_PROD_PANEL_DATA, null, currentProdPanel); + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait 500 ms + Thread.Sleep(CalcSleepTime(samplMsec("prodPanel"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadRecipeData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + // ogni n counter leggo anche dati NON RT + recipeRtCounter--; + bool onlyRt = recipeRtCounter > 0; + //check reset... + recipeRtCounter = recipeRtCounter < 0 ? 4 : recipeRtCounter; + + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get new data from PLC + libraryError = ncAdapter.ReadRecipeData(onlyRt, false, out Dictionary currRecipe); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + MessageServices.Current.Publish(SEND_THERMO_RECIPE_FULL, null, currRecipe); + + // ora gestisco la overview! + libraryError = ncAdapter.GetRecipeOverview(out Dictionary currOverview); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + MessageServices.Current.Publish(SEND_THERMO_RECIPE_OVERWIEW, null, currOverview); + + // ora gestisco la lettura della overview di "modificata + DTORecipeStatus message = new DTORecipeStatus() + { + recipeName = NcAdapter.RecipeLiveData.RecipeName, + hasChanged = NcAdapter.RecipeLiveData.hasChanged + }; + + MessageServices.Current.Publish(SEND_THERMO_RECIPE_CHANGED, null, message); + + // verifico se dal PLC è segnalato che i setpointHMI sono invalidati, nel qual caso INVIO + bool setpointHmiInvalidated = false; + libraryError = ncAdapter.checkSetpointInvalidated(out setpointHmiInvalidated); + if (setpointHmiInvalidated) + { + // ora gestisco l'ack della richiesta + libraryError = ncAdapter.doAckSetpointInvalidated(); + } + // pubblico booleana dei setpointHMI invalidati + MessageServices.Current.Publish(SEND_THERMO_RECIPE_SETPOINTHMI_CHANGED, null, setpointHmiInvalidated); + } + else + RestoreConnection(); + + sw.Stop(); + + // Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("recipe"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadScadaData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + List scadaToRead = ProductionScadaSchema.Concat(SubscribedScada).ToList(); + + // Get new data from PLC + libraryError = ncAdapter.ReadScadasData(scadaToRead, out List scadas); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + + MessageServices.Current.Publish(SEND_SCADA_DATA, null, scadas); + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("scada"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadUserSoftKeysData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + while (true) + { + sw.Restart(); + + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // Get softkey data from config and PLC + libraryError = ncAdapter.GetUserSoftKeys(out List softKeys); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + else + // Send through signalR + MessageServices.Current.Publish(SEND_USER_SOFTKEYS_DATA, null, softKeys); + } + else + RestoreConnection(); + + sw.Stop(); + + //Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("userSK"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + + public static void ReadWarmersData() + { + NcAdapter ncAdapter = new NcAdapter(); + Stopwatch sw = new Stopwatch(); + try + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + + int readCount = 0; + bool useCache = false; + while (true) + { + sw.Restart(); + + // Check if client is connected + if (ncAdapter.numericalControl.NC_IsConnected()) + { + // every 10 reads all data... + useCache = (readCount != 0); + // Get new data from PLC + libraryError = ncAdapter.ReadWarmers(useCache, out Dictionary currWarmers); + if (libraryError.IsError()) + ManageLibraryError(libraryError); + // pubblico + MessageServices.Current.Publish(SEND_THERMO_WARMERS_DATA, null, currWarmers); + readCount++; + // ciclo resettato ogni 20 + readCount = readCount % 20; + } + else + RestoreConnection(); + + sw.Stop(); + + // Update thread timer + UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds); + // Wait + Thread.Sleep(CalcSleepTime(samplMsec("warmers"), (int)sw.ElapsedMilliseconds)); + } + } + catch (ThreadAbortException) + { + ncAdapter.Dispose(); + } + } + public static void SetupCmsConnect() { NcAdapter ncAdapter = new NcAdapter(); try { - - //Write all the datamodel + //Write all the datamodel if (!RedisController.WriteDatamodel(CMSConnectDataModel)) ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE); - //Write all the default entries + //Write all the default entries if (!RedisController.WriteDefaultEntry(CMSConnectEntry)) ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE); - //Write the Active Version + //Write the Active Version if (!RedisController.WriteActiveVersion(SupportFunctions.GetSoftwareVersionAndBuildDate())) ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE); @@ -1240,14 +1267,13 @@ public static class ThreadsFunctions if (!RedisController.WriteFakeOverrides(1)) ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE); - List availableLanguages = LanguageController.GetLanguageListFromDirectory(); if (availableLanguages == null) return; ICollection cultureInfos = new List(); - // Get nc available language + // Get nc available language CmsError libraryError = ncAdapter.numericalControl.NC_GetAvailableLanguages(ref cultureInfos); if (libraryError.IsError()) ManageLibraryError(libraryError); @@ -1291,7 +1317,6 @@ public static class ThreadsFunctions else if (availableLanguages.Count < 3 && defAlarmsNamesIt != null) if (!RedisController.WriteAlarmsConfigCurr(defAlarmsNamesIt)) ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE); - } catch (ThreadAbortException) { @@ -1303,6 +1328,106 @@ public static class ThreadsFunctions #region SupportFunctions + private static int CalcSleepTime(int maxSleep, int execTime) + { + int sleep = 0; + // Check if the execution time is greater than the half of the max sleep time + if (maxSleep - execTime < maxSleep / 2) + { + sleep = maxSleep; + } + else + { + sleep = maxSleep - execTime; + } + + return sleep; + } + + private static bool ClientIsRunning() + { + Process[] p = Process.GetProcessesByName(CLIENT_EXE_NAME_NOEXT); + foreach (Process pr in p) + { + if (pr.MainWindowHandle != IntPtr.Zero) + { + ShowWindow(pr.MainWindowHandle, 9); + SetForegroundWindow(pr.MainWindowHandle); + return true; + } + } + return false; + } + + private static void clientProcess() + { + string CMSClientPath = ""; + // Check if the system is 64/32 bit + if (Environment.Is64BitOperatingSystem && File.Exists(CLIENT_PATH_64)) + CMSClientPath = CLIENT_PATH_64; + else if (File.Exists(CLIENT_PATH_86)) + CMSClientPath = CLIENT_PATH_86; + + if (!String.IsNullOrEmpty(CMSClientPath)) + { + Process pr = Process.Start(CMSClientPath, null); + + if (ServerStartupConfig.AutoOpenCmsClient) + { + pr.WaitForExit(); + MessageServices.Current.Publish(SEND_STOP_SERVER); + } + } + } + + private static Dictionary GetPlcAlarmsTranslations(string language) + { + using (NcAdapter ncAdapter = new NcAdapter()) + { + Dictionary returnValue = new Dictionary(); + + Dictionary messages = new Dictionary(); + // Read data from CN + ncAdapter.numericalControl.NC_GetTranslatedPlcMessages(language, ref messages); // Avoid checking error because in the worst case "messages" is empty + + // Id start from 1 + for (int i = 1; i <= 1024; i++) + { + // Get configurated alarms + var tmpAlarmConfig = InitialAlarmsConfig.Where(x => x.PlcId == i).FirstOrDefault(); + // Default string + string message = string.Format(NOT_CONFIGURATED_ALARM_MESSAGE, i); + // If is configurated + if (tmpAlarmConfig != null) + { + // Find translated string + message = messages.Where(x => x.Key == tmpAlarmConfig.AlarmId).FirstOrDefault().Value; + if (message == null) + message = string.Format(NOT_FOUND_ALARM_MESSAGE, i); + } + // Add to dictionary + returnValue.Add(i.ToString("D6") + "|900", message); + } + return returnValue; + } + } + + [DllImport("user32.dll")] + private static extern bool SetForegroundWindow(IntPtr hWnd); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + private static void StatReset() + { + foreach (var value in Counter) + { + Timers[value.Key] = 0; + Counter[value.Key] = 0; + } + } + private static void TryNcConnection() { // Stop all the NC threads @@ -1340,25 +1465,46 @@ public static class ThreadsFunctions reconnectionIsRunning = false; } } - public static void RestoreConnection() + + internal static void StatThread() { - if (reconnectionIsRunning == false) - { // Set thread as running state - reconnectionIsRunning = true; + while (true) + { + foreach (var value in Counter) + { + if (ThreadsHandler.RunningThreadStatus.ContainsKey(value.Key) && Counter[value.Key] != 0) + { + ThreadsHandler.RunningThreadStatus[value.Key] = $"{(Timers[value.Key] / Counter[value.Key])} ms x {Counter[value.Key]}"; + Timers[value.Key] = 0; + Counter[value.Key] = 0; + } + } - // Start reconnection thread - ConnThread = new Thread(() => - TryNcConnection() - ); + MessageServices.Current.Publish(SEND_THREADS_STATUS, null, ThreadsHandler.RunningThreadStatus); - ConnThread.Start(); + Thread.Sleep(2000); } } + + internal static void UpdateStat(string functionName, long timer) + { + if (!Timers.ContainsKey(functionName)) + Timers.TryAdd(functionName, timer); + else + Timers[functionName] += timer; + + if (!Counter.ContainsKey(functionName)) + Counter.TryAdd(functionName, 1); + else + Counter[functionName]++; + } + public static void AbortNcConnection() { if (ConnThread != null && ConnThread.IsAlive) ConnThread.Abort(); } + public static void ManageLibraryError(CmsError libraryError) { switch (libraryError.errorCode) @@ -1390,144 +1536,31 @@ public static class ThreadsFunctions break; } } - internal static void UpdateStat(string functionName, long timer) + + public static void RestoreConnection() { - if (!Timers.ContainsKey(functionName)) - Timers.TryAdd(functionName, timer); - else - Timers[functionName] += timer; + if (reconnectionIsRunning == false) + { // Set thread as running state + reconnectionIsRunning = true; + // Start reconnection thread + ConnThread = new Thread(() => + TryNcConnection() + ); - if (!Counter.ContainsKey(functionName)) - Counter.TryAdd(functionName, 1); - else - Counter[functionName]++; - } - internal static void StatThread() - { - while (true) - { - foreach (var value in Counter) - { - if (ThreadsHandler.RunningThreadStatus.ContainsKey(value.Key) && Counter[value.Key] != 0) - { - ThreadsHandler.RunningThreadStatus[value.Key] = $"{(Timers[value.Key] / Counter[value.Key])} ms x {Counter[value.Key]}"; - Timers[value.Key] = 0; - Counter[value.Key] = 0; - } - } - - MessageServices.Current.Publish(SEND_THREADS_STATUS, null, ThreadsHandler.RunningThreadStatus); - - Thread.Sleep(2000); + ConnThread.Start(); } } - private static void StatReset() - { - foreach (var value in Counter) - { - Timers[value.Key] = 0; - Counter[value.Key] = 0; - } - } - private static int CalcSleepTime(int maxSleep, int execTime) - { - int sleep = 0; - // Check if the execution time is greater than the half of the max sleep time - if (maxSleep - execTime < maxSleep / 2) - { - sleep = maxSleep; - } - else - { - sleep = maxSleep - execTime; - } - return sleep; - } public static void StartCMSClient() { //Setup the Path Variable if (!ClientIsRunning()) { - ThreadsHandler.StartClient = new Thread(() => clientProcess()); ThreadsHandler.StartClient.Start(); } } - private static void clientProcess() - { - string CMSClientPath = ""; - // Check if the system is 64/32 bit - if (Environment.Is64BitOperatingSystem && File.Exists(CLIENT_PATH_64)) - CMSClientPath = CLIENT_PATH_64; - else if (File.Exists(CLIENT_PATH_86)) - CMSClientPath = CLIENT_PATH_86; - - if (!String.IsNullOrEmpty(CMSClientPath)) - { - Process pr = Process.Start(CMSClientPath, null); - - if (ServerStartupConfig.AutoOpenCmsClient) - { - pr.WaitForExit(); - MessageServices.Current.Publish(SEND_STOP_SERVER); - } - } - } - private static bool ClientIsRunning() - { - Process[] p = Process.GetProcessesByName(CLIENT_EXE_NAME_NOEXT); - foreach (Process pr in p) - { - if (pr.MainWindowHandle != IntPtr.Zero) - { - ShowWindow(pr.MainWindowHandle, 9); - SetForegroundWindow(pr.MainWindowHandle); - return true; - } - } - return false; - } - private static Dictionary GetPlcAlarmsTranslations(string language) - { - using (NcAdapter ncAdapter = new NcAdapter()) - { - Dictionary returnValue = new Dictionary(); - - Dictionary messages = new Dictionary(); - // Read data from CN - ncAdapter.numericalControl.NC_GetTranslatedPlcMessages(language, ref messages); // Avoid checking error because in the worst case "messages" is empty - - // Id start from 1 - for (int i = 1; i <= 1024; i++) - { - // Get configurated alarms - var tmpAlarmConfig = InitialAlarmsConfig.Where(x => x.PlcId == i).FirstOrDefault(); - // Default string - string message = string.Format(NOT_CONFIGURATED_ALARM_MESSAGE, i); - // If is configurated - if (tmpAlarmConfig != null) - { - // Find translated string - message = messages.Where(x => x.Key == tmpAlarmConfig.AlarmId).FirstOrDefault().Value; - if (message == null) - message = string.Format(NOT_FOUND_ALARM_MESSAGE, i); - } - // Add to dictionary - returnValue.Add(i.ToString("D6") + "|900", message); - } - return returnValue; - } - } - - - [DllImport("user32.dll")] - static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); #endregion SupportFunctions } \ No newline at end of file diff --git a/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs b/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs index d54210a7..e1d93fbc 100644 --- a/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs +++ b/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs @@ -18,7 +18,6 @@ namespace Thermo.Active.Model.ConfigModels #region Public Properties public bool CalcIchMin { get; set; } = false; - public int Dimensione { get; set; } = 1; public int IdChannel { get; set; } = 0; public int IdReflector { get; set; } = 0; public int MaxPower { get; set; } = 0; @@ -29,6 +28,11 @@ namespace Thermo.Active.Model.ConfigModels /// public ThermoPoint refPos { get; set; } = new ThermoPoint(); + /// + /// Distanza del punto di riferimento dal centro della piastra + /// + public double refPosDistance { get; set; } = 0; + public int SetpointRecipe { get; set; } = 0; public int SetpointThermo { get; set; } = 0; @@ -50,11 +54,12 @@ namespace Thermo.Active.Model.ConfigModels { #region Public Fields - public int Column; - public int Dimension; - public int Id; - public int IdChannel; - public int Row; + public int Column { get; set; } = 0; + public int Dimension { get; set; } = 0; + public int Id { get; set; } = 0; + public int IdChannel { get; set; } = 0; + public int IdReflector { get; set; } = 0; + public int Row { get; set; } = 0; #endregion Public Fields }