using System; using System.Windows.Forms; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Globalization ; using ib.essetre.integration; using ib.essetre.integration.egaltech; public class Generator : ib.essetre.integration.IGenerator { private System.Threading.Thread _thread ; private static DataSet _ds = new DataSet() ; private static string _SqlConnectionStr = "" ; private struct Bar { public PatternInfo piInfo ; public int nBarState ; public string sBtlPath ; public bool bBtlOk ; } private struct MyProc { public bool bEnable ; public Process Proc ; public int nBar ; } //------------------------------------------------------------------------------------------------------------- public Generator() { } //------------------------------------------------------------------------------------------------------------- public void Run(InOutParameters parameters, ICallBack callback) { _thread = new Thread(() => DoJob( parameters, callback)) ; _thread.Start() ; } private delegate void dDoJob( InOutParameters parameters, ICallBack callback) ; // Proj // Creo progetto barra da pezzo private static void CreateRawPartProjectFromPart(integer nPartId) { EgtNew } //------------------------------------------------------------------------------------------------------------- // campo data ultima modifica nel DATABASE [lastModified] private static void DoJob( InOutParameters parameters, ICallBack callback) { bool bCancel = false ; callback.Progress( 0, "Init", ref bCancel) ; // creo progetti per ogni barra _SqlConnectionStr = parameters.ConnectionString ; String ExePath = GetExePath( parameters) ; String DataDir = GetDataDir( parameters) ; // Numero di barre int numBars = parameters.Patterns.Length ; if ( numBars == 0) return ; // Se modalità Cloud, allora conta solo la prima barra bool bCloud = ( parameters.UIMode == InOutParameters.UIModes.CLOUD) ; if ( bCloud) numBars = 1 ; // Numero di core logici da utilizzare (minimo tra presenti sul PC e imposti da INI) int nMaxThread = Math.Min( Environment.ProcessorCount, GetMaxInstances( parameters)) ; // Frazione di avanzamento del lavoro (in pu) double dProgress = 0 ; // Genero i Btl di tutte le barre Bar[] vBar = new Bar[ numBars + nMaxThread] ; for ( int i = 0; i < numBars; i++) { PatternInfo pattInfo = parameters.Patterns[i] ; BTL btlObject = new BTL() ; // Se il parametro IsFromProject è TRUE viene eseguita la query sulle tabelle Project, // se invece è FALSE viene eseguita la query sulle tabelle Production string sql = "" ; if ( pattInfo.IsFromProject) { sql = "SELECT E.projectId, " + "E.elementId, 0 cutId, processId, info1, info2, enabled, level, " + "inTools, outTools, isChecked, P.done, isoType, ax, ay, az, P.x, P.y, P.z, " + "P.flagDeleted, P.[group], [key], face, edge, des, " + "p01, p02, p03, p04, p05, p06, p07, p08, p09, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, " + "q01, q02, q03, q04, q05, q06, q07, q08, q09, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, " + "ox, oy, oz, xx, xy, xz, yx, yy, yz, " + "priority, processIdent, processingQuality, sag1, text, E.projectId, E.elementId, P.processId, 0 cutStart, 0 cutEnd, " + "E.inverted, E.rotated, 0 doneTime, 0 startAngle, 0 endAngle, -1 referenceCutId, E.length, E.width, E.height " + "FROM dbo.vw_Process AS P " + "RIGHT OUTER JOIN dbo.vw_Element AS E " + "ON P.projectId=E.projectId AND P.elementId=E.elementId " + "WHERE E.projectId = @firstId AND E.elementId = @secondId" ; } else { sql = "SELECT vw_Cut.productionId, " + "vw_Cut.patternId, vw_Cut.cutId, taskId, info1, info2, enabled, level, " + "inTools, outTools, isChecked, vw_Task.done, isoType, ax, ay, az, vw_Cut.x, vw_Cut.y, vw_Cut.z, " + "vw_Task.flagDeleted, [group], [key], face, edge, des, " + "p01, p02, p03, p04, p05, p06, p07, p08, p09, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, " + "q01, q02, q03, q04, q05, q06, q07, q08, q09, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, " + "ox, oy, oz, xx, xy, xz, yx, yy, yz, " + "priority, processIdent, processingQuality, sag1, text, vw_Cut.projectId, vw_Cut.elementId, cutStart, cutEnd, " + "inverted, rotated, doneTime, startAngle, endAngle, referenceCutId, length, width, height " + "FROM dbo.vw_Task " + "RIGHT OUTER JOIN dbo.vw_Cut " + "ON (vw_Task.cutId = vw_Cut.cutId AND vw_Task.patternId = vw_Cut.patternId AND vw_Task.productionId = vw_Cut.productionId) " + "WHERE vw_Cut.productionId = @firstId AND vw_Cut.patternId = @secondId" ; } // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection( _SqlConnectionStr)) { cn.Open() ; using (SqlCommand cmd = new SqlCommand( sql, cn)) { cmd.Parameters.Add( "@firstId", SqlDbType.Int) ; cmd.Parameters.Add( "@secondId", SqlDbType.Int) ; if ( pattInfo.IsFromProject) { cmd.Parameters["@firstId"].Value = pattInfo.ProjectId ; cmd.Parameters["@secondId"].Value = pattInfo.ElementId ; } else { cmd.Parameters["@firstId"].Value = pattInfo.ProductionId ; cmd.Parameters["@secondId"].Value = pattInfo.PatternId ; } var dataAdapter = new SqlDataAdapter( cmd) ; // Lettura DB e riempimento DataSet _ds.Clear() ; dataAdapter.Fill( _ds) ; } } // Verifica parametro isFromProject: nel caso Ordine viene ottenuta la lista dei Process, // nel caso Produzione viene ottenuta la lista dei Task if ( pattInfo.IsFromProject) GetListaProcesses( btlObject) ; else GetListaTasks( btlObject) ; // Recupero lo stato della barra int nBarState = 0 ; if ( ! pattInfo.IsFromProject) nBarState = GetBarStateP( btlObject.patternId, btlObject.productionId) ; // Dialog con Progress Bar dProgress += 0.1 / numBars ; string sProg = ( dProgress * 100).ToString("F1", CultureInfo.InvariantCulture) ; callback.Progress( (float) dProgress, " Progress: " + sProg + "%" + "\n", ref bCancel) ; if ( bCancel) { callback.Done( parameters) ; //fine return ; } // Scrittura del file BTL // Path completa del nome del file da salvare string BtlPath = GetBtlPath( DataDir, pattInfo) ; bool BtlOk = btlObject.WriteIntoFile( BtlPath, pattInfo.IsFromProject) ; // Se modalità cloud, scrittura del file di punti bool bErrOnCloud = false ; if ( bCloud) { if ( pattInfo.Cloud != null) { using ( var tw = new StreamWriter( Path.ChangeExtension( BtlPath, ".pnt"), false)) { for ( int j = 0 ; j < pattInfo.Cloud.Count() ; j++) { double dPosX = - pattInfo.Cloud[j].Y ; double dPosY = pattInfo.Cloud[j].X ; string sPosX = dPosX.ToString( "0.00", System.Globalization.CultureInfo.InvariantCulture) ; string sPosY = dPosY.ToString( "0.00", System.Globalization.CultureInfo.InvariantCulture) ; tw.WriteLine( sPosX + " " + sPosY) ; } } } else { BtlOk = false ; bErrOnCloud = true ; } } // Se scrittura Btl non riuscita if ( ! BtlOk) { // scrivo direttamente il file di errore int ErrCutId = ( pattInfo.IsFromProject ? pattInfo.ElementId : pattInfo.PatternId) ; using ( var tw = new StreamWriter( Path.ChangeExtension( BtlPath, ".txt"), false)) { tw.WriteLine( "ERR=10") ; tw.WriteLine( bErrOnCloud ? "Cloud without points" : "BTL without processes") ; tw.WriteLine( "CUTID=" + ErrCutId.ToString()) ; tw.WriteLine( "TASKID=0") ; } // elimino eventuale file Cn già presente if ( parameters.UIMode == InOutParameters.UIModes.HIDDEN) { string CncPath = Path.ChangeExtension( BtlPath, ".cnc") ; if ( File.Exists( CncPath)) File.Delete( CncPath) ; } } // altrimenti else { // cancello eventuale file di errore già presente string TxtPath = Path.ChangeExtension( BtlPath, ".txt") ; if ( File.Exists( TxtPath)) File.Delete( TxtPath) ; } // Salvo dati vBar[i].piInfo = pattInfo ; vBar[i].nBarState = nBarState ; vBar[i].sBtlPath = BtlPath ; vBar[i].bBtlOk = BtlOk ; } // Lancio in parallelo più processi (senza superare il numero di core logici presenti) MyProc[] vProc = new MyProc[nMaxThread] ; for ( int j = 0 ; j < nMaxThread ; ++ j) { vProc[j].nBar = -1 ; vProc[j].bEnable = true ; } // Processo i Btl in parallelo int nCurrBar = 0 ; int nDoneBar = 0 ; int nShiftBar = 0 ; int nActProc = 0 ; while ( nCurrBar < numBars + nShiftBar || nActProc > 0) { for ( int j = 0 ; j < nMaxThread ; ++ j) { if ( ! vProc[j].bEnable) continue ; bool bDone = false ; if ( vProc[j].nBar == -1) { if ( nCurrBar < numBars + nShiftBar) { if ( vBar[nCurrBar].bBtlOk) { vProc[j].Proc = new Process() ; vProc[j].Proc.StartInfo.FileName = ExePath ; int nMode = (int)parameters.UIMode ; if ( parameters.UIMode == InOutParameters.UIModes.HIDDEN && vBar[nCurrBar].nBarState != 0) nMode = 4 ; vProc[j].Proc.StartInfo.Arguments = "\"" + vBar[nCurrBar].sBtlPath + "\" " + parameters.MachineName + " " + nMode.ToString() ; vProc[j].Proc.StartInfo.UseShellExecute = false ; if ( vProc[j].Proc.Start()) { vProc[j].nBar = nCurrBar ; nCurrBar ++ ; nActProc ++ ; } } else { ProcessResults( vBar[nCurrBar].sBtlPath, vBar[nCurrBar].piInfo, parameters.UIMode) ; bDone = true ; nCurrBar ++ ; } } } else { if ( vProc[j].Proc.HasExited) { // se terminato con successo if ( vProc[j].Proc.ExitCode == 0) { // salvo il risultato ProcessResults( vBar[vProc[j].nBar].sBtlPath, vBar[vProc[j].nBar].piInfo, parameters.UIMode) ; bDone = true ; vProc[j].nBar = -1 ; nActProc -- ; } // se superato il numero di processi eseguibili in parallelo else if ( vProc[j].Proc.ExitCode == 1) { // aggiungo il pezzo in coda if ( numBars + nShiftBar < numBars + nMaxThread) { vBar[numBars + nShiftBar] = vBar[vProc[j].nBar] ; nShiftBar ++ ; } // disabilito il processo vProc[j].bEnable = false ; vProc[j].nBar = -1 ; nActProc -- ; } // altrimenti (errore generico di esecuzione) else { // salvo il risultato ProcessResults( vBar[vProc[j].nBar].sBtlPath, vBar[vProc[j].nBar].piInfo, parameters.UIMode) ; bDone = true ; vProc[j].nBar = -1 ; nActProc -- ; } } else vProc[j].Proc.Refresh() ; } if ( bDone) { // Dialog con Progress Bar dProgress += ( 0.9 / numBars) ; nDoneBar ++ ; string sProg = ( dProgress * 100 ).ToString("F1", CultureInfo.InvariantCulture) ; callback.Progress((float)dProgress, " Progress: " + sProg + "%" + "\n" + " Count: " + nDoneBar + " / " + numBars, ref bCancel); if ( bCancel ) { callback.Done( parameters) ; // fine return ; } } Thread.Sleep( 1) ; } // Verifico che i processi non siano andati tutti in errore bool bAllKO = true ; for ( int j = 0 ; j < nMaxThread ; ++ j) { if ( vProc[j].bEnable) bAllKO = false ; } if ( bAllKO) { MessageBox.Show( "Execution error (all processes are disabled)") ; break ; } Thread.Sleep( 10) ; } callback.Progress( 1, "End", ref bCancel) ; Thread.Sleep( 300) ; callback.Done( parameters) ; // fine } //------------------------------------------------------------------------------------------------------------- public void Abort() { //non implementata al momento } //------------------------------------------------------------------------------------------------------------- private static void ProcessResults( string BtlPath, PatternInfo pattInfo, InOutParameters.UIModes UIMode) { if ( UIMode == InOutParameters.UIModes.SHOWUI || UIMode == InOutParameters.UIModes.SIMULAZIONE) return ; bool bErrors = false ; int nLastErr = 0 ; string sLastMsg = "" ; int nCurrCutId = 0 ; Dictionary dctErr = new Dictionary() ; Dictionary dctRot = new Dictionary() ; int nTotTime = 0 ; if ( File.Exists( Path.ChangeExtension( BtlPath, ".txt"))) { int nErr = 0 ; string sMsg = "" ; double dRot = 0 ; int cutId = 0 ; int taskId = 0 ; string[] lines = System.IO.File.ReadAllLines( Path.ChangeExtension( BtlPath, ".txt")) ; foreach ( string line in lines) { if ( line.StartsWith( "ERR=")) { int? nVal = GetVal(line, "ERR") ; nErr = ( nVal != null ? nVal.Value : 0) ; sMsg = "" ; cutId = 0 ; taskId = 0 ; } else if ( line.StartsWith( "ROT=")) { int? nVal = GetVal( line, "ROT") ; int nRot = ( nVal != null ? nVal.Value : 0) ; dRot = (( 4 - nRot) % 4) * 90 ; } else if ( line.StartsWith( "CUTID=")) { int? nVal = GetVal( line, "CUTID") ; cutId = ( nVal != null ? nVal.Value : 0) ; if ( cutId != nCurrCutId) { nCurrCutId = cutId ; dctErr.Clear() ; dctRot.Clear() ; } } else if ( line.StartsWith( "TASKID=")) { int? nVal = GetVal( line, "TASKID") ; taskId = ( nVal != null ? nVal.Value : 0) ; PatternInfo.Results resExe = PatternInfo.Results.OK ; if ( nErr == 22) { resExe = PatternInfo.Results.COLLISION ; bErrors = true ; // se non assegnata a feature la dichiaro globale if ( cutId == 0 || taskId == 0) { nLastErr = nErr ; sLastMsg = sMsg ; } } else if ( nErr > 0) { resExe = PatternInfo.Results.WARNING ; bErrors = true ; // se non assegnata a feature la dichiaro globale if ( cutId == 0 || taskId == 0) { nLastErr = nErr ; sLastMsg = sMsg ; } } // gestione errore per feature identificata if ( taskId != 0) { // verifiche per feature con più parti if ( dctErr.TryGetValue( taskId, out PatternInfo.Results resCurrExe)) { if ( resExe > resCurrExe) { dctErr[taskId] = resExe ; pattInfo.SetTaskState( cutId, taskId, resExe, sMsg) ; } } else { dctErr[taskId] = resExe ; pattInfo.SetTaskState( cutId, taskId, resExe, sMsg) ; } } // altrimenti per feature generica else { pattInfo.SetTaskState( cutId, taskId, resExe, sMsg) ; } // gestione rotazione per feature identificata if ( taskId != 0) { // verifiche per feature con più parti if ( dctRot.TryGetValue( taskId, out double dCurrRot)) { if ( Math.Abs( dRot) > 1) { if ( Math.Abs( dCurrRot) < 1) dctRot[taskId] = dRot ; } else { dRot = dCurrRot ; } } else { dctRot.Add( taskId, dRot) ; } } // imposto la rotazione if ( pattInfo.IsFromProject) pattInfo.SetProcessInfoChosen( cutId, taskId, dRot, 0, false) ; else pattInfo.SetTaskInfoChosen( cutId, taskId, dRot, 0, false) ; } else if ( line.StartsWith( "TIME=")) { int? nVal = GetVal( line, "TIME") ; nTotTime = ( nVal != null ? nVal.Value : 0) ; } else if ( ! string.IsNullOrWhiteSpace( line) && line != "---") sMsg = line ; } } else { bErrors = true ; nLastErr = 25 ; sLastMsg = "Execution Error" ; } pattInfo.IsDone = true ; if ( ! bErrors) { pattInfo.Result = PatternInfo.Results.OK ; pattInfo.DetailResult = PatternInfo.DetailResults.MEMORY ; } else { // Sezione oltre i limiti if ( nLastErr == 17) { pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_WARNING ; pattInfo.Message = sLastMsg ; } // Errore nel calcolo lavorazione o movimento carrelli else if ( nLastErr == 19) { pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_ERROR ; pattInfo.Message = sLastMsg ; } // Collisione non assegnata ad una feature else if ( nLastErr == 22) { pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_COLLISION ; pattInfo.Message = sLastMsg ; } // Extra corsa assi else if ( nLastErr == 23) { pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_ERROR ; pattInfo.Message = sLastMsg ; } // Carri che scivolano sulla trave else if ( nLastErr == 24) { pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_ERROR ; pattInfo.Message = sLastMsg ; } // Errore generico else if ( nLastErr == 25) { pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_ERROR ; pattInfo.Message = sLastMsg ; } // Altro else { pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.MEMORY ; } } pattInfo.EstimatedTime = nTotTime ; // Lettura OutputFilename e scrittura nel parametro stringa Iso (caso UIModes.HIDDEN) if ( ! bErrors && ( UIMode == InOutParameters.UIModes.HIDDEN || UIMode == InOutParameters.UIModes.CLOUD)) { string CncPath = Path.ChangeExtension( BtlPath, ".cnc") ; if ( File.Exists( CncPath)) { string lines = System.IO.File.ReadAllText(CncPath) ; pattInfo.Iso = lines ; pattInfo.Result = PatternInfo.Results.OK ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_OK ; } else { pattInfo.Iso = "" ; pattInfo.Result = PatternInfo.Results.ERROR ; pattInfo.DetailResult = PatternInfo.DetailResults.ALL_ERROR ; } } } //------------------------------------------------------------------------------------------------------------- // Il seguente metodo prende i record visualizzati in ds (Caso: Produzione) e li carica in un oggetto BTL public static void GetListaTasks( BTL btlObject) { DataTable dTab = _ds.Tables[0] ; Int32 listaTasksCount = dTab.Rows.Count ; if ( listaTasksCount == 0) return ; DataRow dRow0 = dTab.Rows[0] ; btlObject.projectNumber = dRow0["projectId"].ToString() ; btlObject.barLength = GetBarLengthP( (int)dRow0["patternId"], (int)dRow0["productionId"]).ToString( "F3", CultureInfo.InvariantCulture) ; btlObject.barLoad90 = GetBarLoad90P( (int)dRow0["patternId"], (int)dRow0["productionId"]).ToString( CultureInfo.InvariantCulture) ; btlObject.panelLength = GetBarLengthP( (int)dRow0["patternId"], (int)dRow0["productionId"]).ToString( "F3", CultureInfo.InvariantCulture) ; btlObject.panelWidth = GetBarWidthP( (int)dRow0["patternId"], (int)dRow0["productionId"]).ToString( "F3", CultureInfo.InvariantCulture) ; btlObject.productionId = (int)dRow0["productionId"] ; btlObject.patternId = (int)dRow0["patternId"] ; btlObject.parts = new List() ; List ListaCutParts = GetListaCutIdP() ; for ( int c = 0 ; c < ListaCutParts.Count ; c++) { BTL.Part readPart = new BTL.Part() ; bool bFirst = true ; for ( int f = 0; f < listaTasksCount; f++) { DataRow dRowF = dTab.Rows[f] ; if ( (int)dRowF["cutId"] != ListaCutParts[c]) continue ; if ( bFirst) { readPart.singleMemberNumber = GetElementSN( (int)dRowF["elementId"], (int)dRowF["projectId"]) ; readPart.count = "1" ; readPart.length = dRowF["length"].ToString() ; readPart.height = dRowF["height"].ToString() ; readPart.width = dRowF["width"].ToString() ; readPart.x = (double)dRowF["x"] ; readPart.z = (double)dRowF["z"] ; readPart.inverted = (double)dRowF["inverted"] ; readPart.rotated = (double)dRowF["rotated"] ; readPart.cutId = (int)dRowF["cutId"] ; bFirst = false ; readPart.features = new List() ; } if ( string.IsNullOrEmpty( dRowF["taskId"].ToString())) continue ; BTL.Feature readFeature = new BTL.Feature() { taskId = dRowF["taskId"].ToString(), processKey = dRowF["group"].ToString() + "-" + dRowF["key"].ToString().Substring( 1, 3) + "-" + dRowF["face"].ToString(), designation = dRowF["des"].ToString(), processIdent = dRowF["processIdent"].ToString(), sag1 = dRowF["sag1"].ToString(), text = dRowF["text"].ToString(), process = ( Convert.ToInt16( dRowF["enabled"]) == 1) ? "YES" : "NO", processParameters = new List( 46) { dRowF["p01"].ToString(), dRowF["p02"].ToString(), dRowF["p03"].ToString(), dRowF["p04"].ToString(), dRowF["p05"].ToString(), dRowF["p06"].ToString(), dRowF["p07"].ToString(), dRowF["p08"].ToString(), dRowF["p09"].ToString(), dRowF["p10"].ToString(), dRowF["p11"].ToString(), dRowF["p12"].ToString(), dRowF["p13"].ToString(), dRowF["p14"].ToString(), dRowF["p15"].ToString(), dRowF["p16"].ToString(), dRowF["p17"].ToString(), dRowF["p18"].ToString(), dRowF["p19"].ToString(), dRowF["p20"].ToString(), dRowF["p21"].ToString(), dRowF["p22"].ToString(), dRowF["p23"].ToString(), dRowF["p24"].ToString(), dRowF["p25"].ToString(), dRowF["p26"].ToString(), dRowF["q01"].ToString(), dRowF["q02"].ToString(), dRowF["q03"].ToString(), dRowF["q04"].ToString(), dRowF["q05"].ToString(), dRowF["q06"].ToString(), dRowF["q07"].ToString(), dRowF["q08"].ToString(), dRowF["q09"].ToString(), dRowF["q10"].ToString(), dRowF["q11"].ToString(), dRowF["q12"].ToString(), dRowF["q13"].ToString(), dRowF["q14"].ToString(), dRowF["q15"].ToString(), dRowF["q16"].ToString(), dRowF["q17"].ToString(), dRowF["q18"].ToString(), dRowF["q19"].ToString(), dRowF["q20"].ToString() }, processReference = new List( 9) { dRowF["ox"].ToString(), dRowF["oy"].ToString(), dRowF["oz"].ToString(), dRowF["xx"].ToString(), dRowF["xy"].ToString(), dRowF["xz"].ToString(), dRowF["yx"].ToString(), dRowF["yy"].ToString(), dRowF["yz"].ToString() }, } ; readPart.features.Add( readFeature) ; } btlObject.parts.Add( readPart) ; } // L'ordinamento delle Part in un oggetto BTL avviene col confronto del parametro x, estratto dalla tabella vw_Cut btlObject.parts.Sort( (p, q) => p.x.CompareTo( q.x)) ; } //------------------------------------------------------------------------------------------------------------- private static int? GetVal( string sText, string sKey) { string[] sParts = sText.Split( new Char[] { '=' }) ; if ( string.Compare( sParts[0], sKey) != 0) return null ; if ( ! int.TryParse( sParts[1], out int nVal)) return null ; else return nVal ; } //------------------------------------------------------------------------------------------------------------- // Il seguente metodo prende i record visualizzati in ds (Caso: Ordine) e li carica in un oggetto BTL public static void GetListaProcesses( BTL btlObject) { DataTable dTab = _ds.Tables[0] ; int listaProcessesCount = dTab.Rows.Count ; if ( listaProcessesCount == 0) { btlObject.parts = null ; return ; } DataRow dRow0 = dTab.Rows[0] ; btlObject.projectNumber = dRow0["projectId"].ToString() ; btlObject.barLength = GetBarLengthO( (int)dRow0["elementId"], (int)dRow0["projectId"]).ToString( "F3", CultureInfo.InvariantCulture) ; btlObject.barLoad90 = "0" ; btlObject.panelLength = GetPanelLengthO( (int)dRow0["elementId"], (int)dRow0["projectId"]).ToString( "F3", CultureInfo.InvariantCulture) ; btlObject.panelWidth = GetPanelWidthO( (int)dRow0["elementId"], (int)dRow0["projectId"]).ToString( "F3", CultureInfo.InvariantCulture) ; btlObject.projectId = (int)dRow0["projectId"] ; btlObject.elementId = (int)dRow0["elementId"] ; btlObject.parts = new List() ; List ListaCutParts = new List( 1) ; ListaCutParts.Add( (int)dRow0["elementId"]) ; for ( int c = 0 ; c < ListaCutParts.Count ; c++) { BTL.Part readPart = new BTL.Part() ; bool bFirst = true ; for ( int f = 0 ; f < listaProcessesCount ; f++) { DataRow dRowF = dTab.Rows[f] ; if ( (int)dRowF["elementId"] != ListaCutParts[c]) continue ; if ( bFirst) { readPart.singleMemberNumber = GetElementSN( (int)dRow0["elementId"], (int)dRow0["projectId"]) ; readPart.count = "1" ; readPart.length = dRowF["length"].ToString() ; readPart.height = dRowF["height"].ToString() ; readPart.width = dRowF["width"].ToString() ; readPart.x = Constants.HeadOverMat ; readPart.z = Constants.HeadOverMat ; readPart.inverted = (double)dRowF["inverted"] ; readPart.rotated = (double)dRowF["rotated"] ; readPart.elementId = (int)dRowF["elementId"] ; bFirst = false ; readPart.features = new List() ; } if ( string.IsNullOrEmpty( dRowF["processId"].ToString())) continue ; BTL.Feature readFeature = new BTL.Feature() { processId = dRowF["processId"].ToString(), processKey = dRowF["group"].ToString() + "-" + dRowF["key"].ToString().Substring( 1, 3) + "-" + dRowF["face"].ToString(), designation = dRowF["des"].ToString(), processIdent = dRowF["processIdent"].ToString(), sag1 = dRowF["sag1"].ToString(), text = dRowF["text"].ToString(), process = ( Convert.ToInt16( dRowF["enabled"]) == 1) ? "YES" : "NO", processParameters = new List( 46) { dRowF["p01"].ToString(), dRowF["p02"].ToString(), dRowF["p03"].ToString(), dRowF["p04"].ToString(), dRowF["p05"].ToString(), dRowF["p06"].ToString(), dRowF["p07"].ToString(), dRowF["p08"].ToString(), dRowF["p09"].ToString(), dRowF["p10"].ToString(), dRowF["p11"].ToString(), dRowF["p12"].ToString(), dRowF["p13"].ToString(), dRowF["p14"].ToString(), dRowF["p15"].ToString(), dRowF["p16"].ToString(), dRowF["p17"].ToString(), dRowF["p18"].ToString(), dRowF["p19"].ToString(), dRowF["p20"].ToString(), dRowF["p21"].ToString(), dRowF["p22"].ToString(), dRowF["p23"].ToString(), dRowF["p24"].ToString(), dRowF["p25"].ToString(), dRowF["p26"].ToString(), dRowF["q01"].ToString(), dRowF["q02"].ToString(), dRowF["q03"].ToString(), dRowF["q04"].ToString(), dRowF["q05"].ToString(), dRowF["q06"].ToString(), dRowF["q07"].ToString(), dRowF["q08"].ToString(), dRowF["q09"].ToString(), dRowF["q10"].ToString(), dRowF["q11"].ToString(), dRowF["q12"].ToString(), dRowF["q13"].ToString(), dRowF["q14"].ToString(), dRowF["q15"].ToString(), dRowF["q16"].ToString(), dRowF["q17"].ToString(), dRowF["q18"].ToString(), dRowF["q19"].ToString(), dRowF["q20"].ToString() }, processReference = new List( 9) { dRowF["ox"].ToString(), dRowF["oy"].ToString(), dRowF["oz"].ToString(), dRowF["xx"].ToString(), dRowF["xy"].ToString(), dRowF["xz"].ToString(), dRowF["yx"].ToString(), dRowF["yy"].ToString(), dRowF["yz"].ToString() }, } ; readPart.features.Add( readFeature) ; } btlObject.parts.Add( readPart) ; } // L'ordinamento delle Part in un oggetto BTL avviene col confronto del parametro x, estratto dalla tabella vw_Cut btlObject.parts.Sort( (p, q) => p.x.CompareTo( q.x)) ; } //------------------------------------------------------------------------------------------------------------- // Il seguente metodo si connette al DB per estrarre tramite una query i cutId della tabella vw_Cut // aventi patternId e ProductionId che corrispondono a quelli passati come argomento private static List GetListaCutIdP() { List ListaCutId = new List() ; DataTable dTab = _ds.Tables[0] ; int listaTasksCount = dTab.Rows.Count ; for ( int f = 0 ; f < listaTasksCount ; f++) { int nCut = (int) dTab.Rows[f]["cutId"] ; if ( ! ListaCutId.Contains( nCut)) ListaCutId.Add( nCut) ; } return ListaCutId ; } //------------------------------------------------------------------------------------------------------------- // Recupera il singlemembernumber dell'Elemento (colonna "sn") private static string GetElementSN( int ElementId, int ProjectId) { string SN = "000" ; string sqlElementSN = "SELECT sn " + "FROM dbo.vw_Element " + "WHERE elementId = @firstId " + "AND projectId = @secondId" ; // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection( _SqlConnectionStr)) { cn.Open() ; using ( SqlCommand sqlCommand = new SqlCommand( sqlElementSN, cn)) { sqlCommand.Parameters.Add( "@firstId", SqlDbType.Int) ; sqlCommand.Parameters.Add( "@secondId", SqlDbType.Int) ; sqlCommand.Parameters["@firstId"].Value = ElementId ; sqlCommand.Parameters["@secondId"].Value = ProjectId ; SqlDataReader reader = sqlCommand.ExecuteReader() ; while ( reader.Read()) { SN = Convert.ToString( reader["sn"]) ; } } } return SN ; } //------------------------------------------------------------------------------------------------------------- // Recupera la lunghezza della barra nel caso Produzione (colonna "l") private static double GetBarLengthP( int patternId, int productionId) { double barLength = 0 ; string sqlBarLength = "SELECT l " + "FROM dbo.vw_Pattern " + "WHERE patternId = @firstId " + "AND productionId = @secondId" ; // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection( _SqlConnectionStr)) { cn.Open() ; using ( SqlCommand sqlCommand = new SqlCommand( sqlBarLength, cn)) { sqlCommand.Parameters.Add( "@firstId", SqlDbType.Int) ; sqlCommand.Parameters.Add( "@secondId", SqlDbType.Int) ; sqlCommand.Parameters["@firstId"].Value = patternId ; sqlCommand.Parameters["@secondId"].Value = productionId ; SqlDataReader reader = sqlCommand.ExecuteReader() ; while ( reader.Read()) { barLength = Convert.ToDouble( reader["l"]) ; } } } return barLength ; } //------------------------------------------------------------------------------------------------------------- // Recupera la larghezza della barra nel caso Produzione (colonna "w") private static double GetBarWidthP( int patternId, int productionId) { double barWidth = 0 ; string sqlBarWidth = "SELECT w " + "FROM dbo.vw_Pattern " + "WHERE patternId = @firstId " + "AND productionId = @secondId" ; // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection( _SqlConnectionStr)) { cn.Open() ; using ( SqlCommand sqlCommand = new SqlCommand( sqlBarWidth, cn)) { sqlCommand.Parameters.Add( "@firstId", SqlDbType.Int) ; sqlCommand.Parameters.Add( "@secondId", SqlDbType.Int) ; sqlCommand.Parameters["@firstId"].Value = patternId ; sqlCommand.Parameters["@secondId"].Value = productionId ; SqlDataReader reader = sqlCommand.ExecuteReader() ; while ( reader.Read()) { barWidth = Convert.ToDouble( reader["w"]) ; } } } return barWidth ; } //------------------------------------------------------------------------------------------------------------- // Recupera il flag di carico con rotazione di 90° nel caso Produzione (colonna "load90") private static int GetBarLoad90P( int patternId, int productionId) { int nLoad90 = 0 ; string sqlBarLength = "SELECT load90 " + "FROM dbo.vw_Pattern " + "WHERE patternId = @firstId " + "AND productionId = @secondId" ; // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection( _SqlConnectionStr)) { cn.Open() ; using ( SqlCommand sqlCommand = new SqlCommand( sqlBarLength, cn)) { sqlCommand.Parameters.Add( "@firstId", SqlDbType.Int) ; sqlCommand.Parameters.Add( "@secondId", SqlDbType.Int) ; sqlCommand.Parameters["@firstId"].Value = patternId ; sqlCommand.Parameters["@secondId"].Value = productionId ; SqlDataReader reader = sqlCommand.ExecuteReader() ; while ( reader.Read()) { nLoad90 = Convert.ToInt32( reader["load90"]) ; } } } return nLoad90 ; } //------------------------------------------------------------------------------------------------------------- // Recupera lo stato della barra nel caso Produzione (colonna "state") private static int GetBarStateP( int patternId, int productionId) { int barState = 16 ; string sqlBarLength = "SELECT state " + "FROM dbo.vw_Pattern " + "WHERE patternId = @firstId " + "AND productionId = @secondId" ; // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection( _SqlConnectionStr)) { cn.Open() ; using ( SqlCommand sqlCommand = new SqlCommand( sqlBarLength, cn)) { sqlCommand.Parameters.Add( "@firstId", SqlDbType.Int) ; sqlCommand.Parameters.Add( "@secondId", SqlDbType.Int) ; sqlCommand.Parameters["@firstId"].Value = patternId ; sqlCommand.Parameters["@secondId"].Value = productionId ; SqlDataReader reader = sqlCommand.ExecuteReader() ; while ( reader.Read()) { barState = Convert.ToInt32( reader["state"]) ; } } } return barState ; } //------------------------------------------------------------------------------------------------------------- // Recupera la lunghezza della barra nel caso Ordine (colonna "length", ovvero la lunghezza della singola trave) // a cui aggiungiamo un valore fisso (es. 2000) private static double GetBarLengthO( int elementId, int projectId) { double barLength = 0 ; DataTable dTab = _ds.Tables[0] ; int listaProcessesCount = dTab.Rows.Count ; if ( listaProcessesCount > 0) { double beamLength = Convert.ToDouble( dTab.Rows[0]["length"]) ; if ( beamLength < Constants.BarMaxLenForAdd) barLength = beamLength + Constants.BarAddLen ; else barLength = beamLength + 2 * Constants.HeadOverMat ; } return barLength ; } //------------------------------------------------------------------------------------------------------------- // Recupera la lunghezza del pannello nel caso Ordine (colonna "length", ovvero la lunghezza della singola parete) // a cui aggiungiamo un valore fisso (es. 200) private static double GetPanelLengthO( int elementId, int projectId) { double panelLength = 0 ; DataTable dTab = _ds.Tables[0] ; int listaProcessesCount = dTab.Rows.Count ; if ( listaProcessesCount > 0) { double wallLength = Convert.ToDouble( dTab.Rows[0]["length"]) ; panelLength = wallLength + 2 * Constants.PanelOverMat ; } return panelLength ; } //------------------------------------------------------------------------------------------------------------- // Recupera la lunghezza del pannello nel caso Ordine (colonna "width", ovvero la larghezza della singola parete) // a cui aggiungiamo un valore fisso (es. 200) private static double GetPanelWidthO( int elementId, int projectId) { double panelWidth = 0 ; DataTable dTab = _ds.Tables[0] ; int listaProcessesCount = dTab.Rows.Count ; if ( listaProcessesCount > 0) { double wallWidth = Convert.ToDouble( dTab.Rows[0]["width"]) ; panelWidth = wallWidth + 2 * Constants.PanelOverMat ; } return panelWidth ; } //------------------------------------------------------------------------------------------------------------- // Restituisce la path di esecuzione di EgtCam5 private static String GetExePath( InOutParameters parameters) { return parameters.Read( "EGALTECH", "PATH_EXE", "") ; } //------------------------------------------------------------------------------------------------------------- // Restituisce il direttorio per i file con i dati macchina private static String GetDataDir( InOutParameters parameters) { String DataDir = parameters.Read( "EGALTECH", "DIR_DATA", "") ; // Se la directory non esiste viene creata DirectoryInfo di = new DirectoryInfo( DataDir) ; if ( ! di.Exists) di.Create() ; return DataDir ; } //------------------------------------------------------------------------------------------------------------- // Restituisce la path completa per il file BTL private static String GetBtlPath( String DataDir, PatternInfo pattInfo) { String BtlDir, BtlName ; // Se progetto if ( pattInfo.IsFromProject) { BtlDir = Path.Combine( DataDir, "Projs", pattInfo.ProjectId.ToString( "D4")) ; BtlName = "Part_" + pattInfo.ProjectId.ToString() + "_" + pattInfo.ElementId.ToString() + ".btl" ; } // altrimenti produzione else { BtlDir = Path.Combine( DataDir, "Prods", pattInfo.ProductionId.ToString( "D4")) ; BtlName = "Bar_" + pattInfo.ProductionId.ToString() + "_" + pattInfo.PatternId.ToString() + ".btl" ; } // Se la directory non esiste viene creata DirectoryInfo di = new DirectoryInfo( BtlDir) ; if ( ! di.Exists) di.Create() ; // restituisco la path completa return Path.Combine( BtlDir, BtlName) ; } //------------------------------------------------------------------------------------------------------------- // Restituisce il massimo numero di istanze di EgtCAM5 eseguibili contemporaneamente private static int GetMaxInstances( InOutParameters parameters) { String sMaxInst = parameters.Read( "EGALTECH", "MaxInstances", "1") ; if ( ! int.TryParse( sMaxInst, out int nVal)) return 1 ; else return Math.Max( nVal, 1) ; } //------------------------------------------------------------------------------------------------------------- // Visualizzazione finestra gestione DB utensili public bool ShowTools( InOutParameters parameters) { // Recupero dati string ExePath = GetExePath( parameters) ; string DataDir = GetDataDir( parameters) ; string BtlPath = Path.Combine( DataDir, "QQQ.btl") ; // Esecuzione di EgtCAM5 con parametri path BTL, nome macchina e modo Process process = new Process() ; process.StartInfo.FileName = ExePath ; process.StartInfo.Arguments = "\"" + BtlPath + "\" " + parameters.MachineName + " 11" ; process.StartInfo.UseShellExecute = false ; process.Start() ; // Attendo il termine del processo while ( ! process.HasExited) { process.Refresh() ; Thread.Sleep( 50) ; } return true ; } //------------------------------------------------------------------------------------------------------------- // Visualizzazione finestra gestione DB lavorazioni public bool ShowJobs( InOutParameters parameters) { // Recupero dati string ExePath = GetExePath( parameters) ; string DataDir = GetDataDir( parameters) ; string BtlPath = Path.Combine( DataDir, "QQQ.btl") ; // Esecuzione di EgtCAM5 con parametri path BTL, nome macchina e modo Process process = new Process() ; process.StartInfo.FileName = ExePath ; process.StartInfo.Arguments = "\"" + BtlPath + "\" " + parameters.MachineName + " 12" ; process.StartInfo.UseShellExecute = false ; process.Start() ; // Attendo il termine del processo while ( ! process.HasExited) { process.Refresh() ; Thread.Sleep( 50) ; } return true ; } //------------------------------------------------------------------------------------------------------------- // Aggiornamento dati macchina public bool UpdateMachine( InOutParameters parameters) { GetMachineParams( parameters) ; return true ; } //------------------------------------------------------------------------------------------------------------- // Dati utensili e macchina //------------------------------------------------------------------------------------------------------------- // Import della funzione di sistema per la scrittura su file INI [DllImport("kernel32", CharSet = CharSet.Unicode)] static extern long WritePrivateProfileString( string Section, string Key, string Value, string FilePath) ; //------------------------------------------------------------------------------------------------------------- // Scrive il file Essetre-[MachineName].data che riporta i parametri macchina del DB private static void GetMachineParams( InOutParameters parameters) { // Direttorio di scrittura del file String DataDir = GetDataDir( parameters) ; // Path del file di dati e sua cancellazione se già esiste string DataName = "Essetre-" + parameters.MachineName + ".data" ; string DataPath = Path.Combine( DataDir, DataName) ; if ( File.Exists( DataPath)) File.Delete( DataPath) ; // Preparazione interrogazione per Offsets del DB _SqlConnectionStr = parameters.ConnectionString ; DataSet dsOffsets = new DataSet() ; string sqlOffsets = "SELECT [group], [key], [value] " + "FROM [ESSETRE].[dbo].[vw_MachineParam] " + "WHERE [group] = 'OFFSETS' AND configurationId = @ConfigId" ; // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection(_SqlConnectionStr)) { cn.Open() ; using ( SqlCommand cmd = new SqlCommand(sqlOffsets, cn)) { cmd.Parameters.Add( "@ConfigId", SqlDbType.Int) ; cmd.Parameters["@ConfigId"].Value = parameters.ConfigurationId ; var dataAdapter = new SqlDataAdapter( cmd) ; // Lettura DB e riempimento DataSet dsOffsets.Clear() ; dataAdapter.Fill(dsOffsets) ; } } // Preparazione interrogazione per Trave del DB _SqlConnectionStr = parameters.ConnectionString ; DataSet dsTrave = new DataSet() ; string sqlTrave = "SELECT [group], [key], [value] " + "FROM [ESSETRE].[dbo].[vw_MachineParam] " + "WHERE [group] = 'TRAVE' AND configurationId = @ConfigId" ; // Connessione al DB ed esecuzione query using ( SqlConnection cn = new SqlConnection(_SqlConnectionStr)) { cn.Open() ; using ( SqlCommand cmd = new SqlCommand( sqlTrave, cn)) { cmd.Parameters.Add( "@ConfigId", SqlDbType.Int) ; cmd.Parameters["@ConfigId"].Value = parameters.ConfigurationId ; var dataAdapter = new SqlDataAdapter( cmd) ; // Lettura DB e riempimento DataSet dsTrave.Clear() ; dataAdapter.Fill( dsTrave) ; } } // Preparazione interrogazione per Dati Utente del DB _SqlConnectionStr = parameters.ConnectionString; DataSet dsUser = new DataSet(); string sqlUser = "SELECT [group], [key], [value] " + "FROM [ESSETRE].[dbo].[vw_ConfigurationParam] " + "WHERE [group] <> 'TEXTS' AND [group] <> 'PARAMS' AND configurationId = @ConfigId"; // Connessione al DB ed esecuzione query using (SqlConnection cn = new SqlConnection(_SqlConnectionStr)) { cn.Open(); using (SqlCommand cmd = new SqlCommand(sqlUser, cn)) { cmd.Parameters.Add("@ConfigId", SqlDbType.Int); cmd.Parameters["@ConfigId"].Value = parameters.ConfigurationId; var dataAdapter = new SqlDataAdapter(cmd); // Lettura DB e riempimento DataSet dsUser.Clear(); dataAdapter.Fill(dsUser); } } // Apro file using ( var tw = new StreamWriter( DataPath, false)) { // Scrittura intestazione tw.WriteLine( "-- " + DataPath) ; tw.WriteLine( "") ; // Scrittura dei dati di Offsets tw.WriteLine( "local Offsets = {") ; foreach ( DataTable table in dsOffsets.Tables) { foreach ( DataRow row in table.Rows) { String Key = row["key"].ToString() ; String Value = row["value"].ToString() ; tw.WriteLine( " " + Key + "=" + Value + ",") ; } } tw.WriteLine( " Zzz=1") ; tw.WriteLine( "}") ; tw.WriteLine( "") ; // Scrittura dei dati di Trave tw.WriteLine( "local Trave = {") ; foreach ( DataTable table in dsTrave.Tables) { foreach ( DataRow row in table.Rows) { String Key = row["key"].ToString() ; String Value = row["value"].ToString() ; tw.WriteLine( " " + Key + "=" + Value + ",") ; } } tw.WriteLine( " Zzz=1") ; tw.WriteLine( "}") ; tw.WriteLine( "") ; // Scrittura dei dati di Utente tw.WriteLine("local User = {"); foreach (DataTable table in dsUser.Tables) { foreach (DataRow row in table.Rows) { String Group = row["group"].ToString(); String Key = row["key"].ToString(); String Value = row["value"].ToString(); tw.WriteLine(" " + Group + "_" + Key + "=" + Value + ","); } } tw.WriteLine(" Zzz=1"); tw.WriteLine("}"); tw.WriteLine(""); // Scrittura tabella da restituire tw.WriteLine( "local Machine = { Offsets=Offsets, Trave=Trave, User=User}") ; tw.WriteLine( "return Machine") ; } } //------------------------------------------------------------------------------------------------------------- // Indica direttori e file per backup public void CollectFile( InOutParameters parameters, FileCollector collector) { // Direttori notevoli String sRoot = parameters.Read( "EGALTECH", "DIR_EGT", "C:\\TechnoEssetre7\\EgalTech") ; String sBeamDir = "EgtCAM5\\Beam" ; String sMachDir = "EgtCAM5\\Machines\\Essetre-" + parameters.MachineName ; // Impostazione collector.SetRoot(sRoot) ; collector.AddDirectory(Path.Combine(sRoot, sBeamDir)) ; collector.AddDirectory(Path.Combine(sRoot, sMachDir)) ; } }