Inheritance: CyPhyGUIs.SmartLogger
 /// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a tansaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     if (Logger == null)
         Logger = new CyPhyGUIs.GMELogger(project, ComponentName);
     MgaGateway = new MgaGateway(project);
     project.CreateTerritoryWithoutSink(out MgaGateway.territory);       
 }
 /// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a tansaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     if (Logger == null)
     {
         Logger = new GMELogger(project, this.ComponentName);
     }
 }
 public CodeGenerator(CyPhyGUIs.IInterpreterMainParameters parameters, Mode mode, GMELogger Logger)
 {
     this.Logger = Logger;
     this.mainParameters = parameters;
     CodeGenerator.verbose = ((CyPhy2RF.CyPhy2RF_Settings)parameters.config).Verbose;
     this.mode = mode;
 }
Example #4
0
 /// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a tansaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     if (Logger == null)
     {
         Logger = new CyPhyGUIs.GMELogger(project, ComponentName);
     }
     MgaGateway = new MgaGateway(project);
 }
        public Unroller(MgaProject proj, IMgaTraceability Traceability = null, GMELogger Logger = null)
        {
            this.ConnectorsProcessed = new List<MgaModel>();
            this.ConnectorToStandalonePortMap = new Dictionary<MgaModel, List<PortWrapper>>();

            SupportedPortTypesMeta = new HashSet<int>();
            foreach (var kind in SupportedPortTypes)
            {
                SupportedPortTypesMeta.Add(proj.RootMeta.RootFolder.DefinedFCOByName[kind, true].MetaRef);
            }

            MetaRef = new Dictionary<String, int>();
            MetaRef.Add("Component", proj.RootMeta.RootFolder.DefinedFCOByName["Component", true].MetaRef);
            MetaRef.Add("ComponentAssembly", proj.RootMeta.RootFolder.DefinedFCOByName["ComponentAssembly", true].MetaRef);
            MetaRef.Add("Connector", proj.RootMeta.RootFolder.DefinedFCOByName["Connector", true].MetaRef);
            MetaRef.Add("TestBench", proj.RootMeta.RootFolder.DefinedFCOByName["TestBench", true].MetaRef);
            MetaRef.Add("TestComponent", proj.RootMeta.RootFolder.DefinedFCOByName["TestComponent", true].MetaRef);

            if (Logger == null)
            {
                this.Logger = new GMELogger(proj, "ConnectorUnroller");
                myLogger = true;
            }
            else
            {
                this.Logger = Logger;
                myLogger = false;
            }

            if (Traceability == null)
            {
                this.Traceability = new META.MgaTraceability();
            }
            else
            {
                this.Traceability = Traceability;
            }
        }
Example #6
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            Boolean disposeLogger = false;

            if (Logger == null)
            {
                Logger        = new CyPhyGUIs.GMELogger(project, "CyPhyDesignExporter");
                disposeLogger = true;
            }

            // TODO: Add your interpreter code
            Logger.WriteInfo("Running Design Exporter...");

            #region Prompt for Output Path
            // Get an output path from the user.
            if (this.OutputDir == null)
            {
                using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
                {
                    Description = "Choose a path for the generated files.",
                    //ShowNewFolderButton = true,
                    SelectedPath = Environment.CurrentDirectory,
                })
                {
                    DialogResult dr = fbd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        OutputDir = fbd.SelectedPath;
                    }
                    else
                    {
                        Logger.WriteWarning("Design Exporter cancelled");
                        return;
                    }
                }
            }
            #endregion

            Logger.WriteInfo("Beginning Export...");
            List <CyPhy.DesignEntity>  lde_allCAandDC = new List <CyPhy.DesignEntity>();
            List <CyPhy.TestBenchType> ltbt_allTB     = new List <CyPhy.TestBenchType>();

            if (currentobj != null &&
                currentobj.Meta.Name == "ComponentAssembly")
            {
                lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(currentobj));
            }
            else if (currentobj != null &&
                     currentobj.Meta.Name == "DesignContainer")
            {
                lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(currentobj));
            }
            else if (currentobj != null &&
                     IsTestBenchType(currentobj.MetaBase.Name))
            {
                ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(currentobj));
            }
            else if (selectedobjs != null && selectedobjs.Count > 0)
            {
                foreach (MgaFCO mf in selectedobjs)
                {
                    if (mf.Meta.Name == "ComponentAssembly")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(mf));
                    }
                    else if (mf.Meta.Name == "DesignContainer")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(mf));
                    }
                    else if (IsTestBenchType(mf.MetaBase.Name))
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(mf));
                    }
                }
            }
            else
            {
                CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);

                MgaFilter filter = project.CreateFilter();
                filter.Kind = "ComponentAssembly";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(item));
                    }
                }

                filter      = project.CreateFilter();
                filter.Kind = "DesignContainer";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(item));
                    }
                }

                filter      = project.CreateFilter();
                filter.Kind = "TestBenchType";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(item));
                    }
                }
            }

            foreach (CyPhy.DesignEntity de in lde_allCAandDC)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    if (de is CyPhy.ComponentAssembly)
                    {
                        ExportToPackage(de as CyPhy.ComponentAssembly, OutputDir);
                    }
                    else
                    {
                        ExportToFile(de, OutputDir);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", de.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", de.Name, OutputDir);
            }

            foreach (CyPhy.TestBenchType tbt in ltbt_allTB)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    ExportToFile(tbt, OutputDir);
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", tbt.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", tbt.Name, OutputDir);
            }

            Logger.WriteInfo(String.Format("{0} model(s) exported", lde_allCAandDC.Count + ltbt_allTB.Count));
            Logger.WriteInfo("Design Exporter finished");

            if (disposeLogger)
            {
                DisposeLogger();
            }
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                if (Logger == null)
                {
                    Logger = new GMELogger(project, ComponentName);
                }
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                this.mainParameters = new InterpreterMainParameters()
                {
                    Project = project,
                    CurrentFCO = currentobj as MgaFCO,
                    SelectedFCOs = selectedobjs,
                    StartModeParam = param
                };

                Main(this.mainParameters);

                //this.PrintRuntimeStatistics();
            }
            catch (Exception ex)
            {
                Logger.WriteError("Exception: {0}<br> {1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                if (MgaGateway != null &&
                    MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null; 
                DisposeLogger();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #8
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                // Create a new instance of the logger
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);

                if (currentobj == null)
                {
                    this.Logger.WriteFailed("CyPhyPET must be called from a Parametric Exploration.");
                    return;
                }

                // Need to call this interpreter in the same way as the MasterInterpreter will call it.
                // initialize main parameters
                var parameters = new InterpreterMainParameters()
                {
                    Project = project,
                    CurrentFCO = currentobj,
                    SelectedFCOs = selectedobjs,
                    StartModeParam = param,
                    VerboseConsole = true
                };

                this.mainParameters = parameters;
                parameters.ProjectDirectory = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));


                // Check if the PCCPropertyInputEditor should be opend.
                // If so return after this transaction
                bool doReturn = false;

                int VK_CONTROL = 0x11;
                // If control was held, try to open GUI. 
                if ((bool)((GetKeyState(VK_CONTROL) & 0x8000) == 0x8000))
                {
                    MgaGateway.PerformInTransaction(delegate
                    {
                        doReturn = this.TryOpenPCCPropertyInputEditor();
                    }, abort: false);
                }

                if (doReturn)
                {
                    return;
                }

                string interpreterProgID = "";

                // Set up the output directory and check kind of currentObj.
                string kindName = string.Empty;
                MgaGateway.PerformInTransaction(delegate
                {
                    string outputDirName = project.Name;
                    if (currentobj != null)
                    {
                        outputDirName = currentobj.Name;
                        kindName = currentobj.MetaBase.Name;
                    }

                    parameters.OutputDirectory = Path.GetFullPath(Path.Combine(
                        parameters.ProjectDirectory,
                        "results",
                        outputDirName));
                    var testBenchRef = currentobj.ChildObjects.Cast<MgaFCO>().Where(c => c.MetaRole.Name == typeof(CyPhyClasses.TestBenchRef).Name).FirstOrDefault();
                    if (testBenchRef != null)
                    {
                        var tbRef = CyPhyClasses.TestBenchRef.Cast(testBenchRef);
                        if (tbRef.AllReferred is CyPhy.TestBench)
                        {
                            var testBench = CyPhyClasses.TestBenchRef.Cast(testBenchRef).Referred.TestBench;
                            interpreterProgID = Rules.Global.GetInterpreterProgIDFromTestBench(testBench);
                        }
                        else if (tbRef.AllReferred is CyPhy.TestBenchType)
                        {
                            // Assume CyPhy2CAD_CSharp for all other types of test-benches for now.
                            interpreterProgID = "MGA.Interpreter.CyPhy2CAD_CSharp";
                        }
                    }
                });

                if (string.IsNullOrEmpty(kindName) == false && kindName != typeof(CyPhyClasses.ParametricExploration).Name)
                {
                    this.Logger.WriteFailed("CyPhyPET must be called from a Parametric Exploration.");
                    return;
                }

                PreConfigArgs preConfigArgs = new PreConfigArgs();
                preConfigArgs.ProjectDirectory = parameters.ProjectDirectory;

                // call the preconfiguration with no parameters and get preconfig
                var preConfig = this.PreConfig(preConfigArgs);

                // get previous GUI config
                var previousConfig = META.ComComponent.DeserializeConfiguration(
                    parameters.ProjectDirectory,
                    typeof(CyPhyPET.CyPhyPETSettings),
                    this.ComponentProgID);

                // get interpreter config through GUI
                var config = this.DoGUIConfiguration(preConfig, previousConfig);
                if (config == null)
                {
                    this.Logger.WriteWarning("Operation cancelled by the user.");
                    return;
                }

                // External Interpreter configuration
                if (interpreterProgID == "MGA.Interpreter.CyPhy2Modelica_v2")
                {
                    var cyPhy2Modelica_v2 = new META.ComComponent("MGA.Interpreter.CyPhy2Modelica_v2");
                    if (cyPhy2Modelica_v2.DoGUIConfiguration(parameters.ProjectDirectory) == false)
                    {
                        this.Logger.WriteWarning("Operation cancelled by the user.");
                        return;
                    }
                }
                else if (interpreterProgID == "MGA.Interpreter.CyPhy2CAD_CSharp")
                {
                    var cyPhy2CAD_CSharp = new META.ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp");
                    if (cyPhy2CAD_CSharp.DoGUIConfiguration(parameters.ProjectDirectory) == false)
                    {
                        this.Logger.WriteWarning("Operation cancelled by the user.");
                        return;
                    }
                }

                // if config is valid save it and update it on the file system
                META.ComComponent.SerializeConfiguration(parameters.ProjectDirectory, config, this.ComponentProgID);

                // assign the new configuration to mainParameters
                parameters.config = config;

                // call the main (ICyPhyComponent) function
                this.Main(parameters);

            }
            finally
            {
                if (this.Logger != null)
                {
                    this.Logger.Dispose();
                    this.Logger = null;
                }
                if (MgaGateway != null &&
                    MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                //GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
 public UnzipToTemp(GMELogger logger = null)
 {
     Logger = logger;
 }
 public void DisposeLogger()
 {
     if (Logger != null)
     {
         Logger.Dispose();
     }
     Logger = null;
 }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                if (Logger == null)
                {
                    Logger = new GMELogger(project, this.ComponentName);
                }
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                });
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                if (Logger != null)
                {
                    Logger.Dispose();
                }
                Logger = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            Boolean disposeLogger = false;
            if (Logger == null)
            {
                Logger = new CyPhyGUIs.GMELogger(project, "CyPhyDesignExporter");
                disposeLogger = true;
            }

            // TODO: Add your interpreter code
            Logger.WriteInfo("Running Design Exporter...");

            #region Prompt for Output Path
            // Get an output path from the user.
            if (this.OutputDir == null)
            {
                using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
                {
                    Description = "Choose a path for the generated files.",
                    //ShowNewFolderButton = true,
                    SelectedPath = Environment.CurrentDirectory,
                })
                {

                    DialogResult dr = fbd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        OutputDir = fbd.SelectedPath;
                    }
                    else
                    {
                        Logger.WriteWarning("Design Exporter cancelled");
                        return;
                    }
                }
            }
            #endregion

            Logger.WriteInfo("Beginning Export...");
            List<CyPhy.DesignEntity> lde_allCAandDC = new List<CyPhy.DesignEntity>();
            List<CyPhy.TestBenchType> ltbt_allTB = new List<CyPhy.TestBenchType>();
            
            if (currentobj != null && 
                currentobj.Meta.Name == "ComponentAssembly")
            {
                lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(currentobj));
            }
            else if (currentobj != null &&
                     currentobj.Meta.Name == "DesignContainer")
            {
                lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(currentobj));
            }
            else if (currentobj != null &&
                IsTestBenchType(currentobj.MetaBase.Name))
            {
                ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(currentobj));
            }
            else if (selectedobjs != null && selectedobjs.Count > 0)
            {
                foreach (MgaFCO mf in selectedobjs)
                {
                    if (mf.Meta.Name == "ComponentAssembly")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(mf));
                    }
                    else if (mf.Meta.Name == "DesignContainer")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(mf));
                    }
                    else if (IsTestBenchType(mf.MetaBase.Name))
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(mf));
                    }
                }
            }
            else
            {
                CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);

                MgaFilter filter = project.CreateFilter();
                filter.Kind = "ComponentAssembly";
                foreach (var item in project.AllFCOs(filter).Cast<MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(item));
                    }
                }

                filter = project.CreateFilter();
                filter.Kind = "DesignContainer";
                foreach (var item in project.AllFCOs(filter).Cast<MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(item));
                    }
                }

                filter = project.CreateFilter();
                filter.Kind = "TestBenchType";
                foreach (var item in project.AllFCOs(filter).Cast<MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(item));
                    }
                }
            }

            foreach (CyPhy.DesignEntity de in lde_allCAandDC)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    if (de is CyPhy.ComponentAssembly)
                    {
                        ExportToPackage(de as CyPhy.ComponentAssembly, OutputDir);
                    }
                    else
                    {
                        ExportToFile(de, OutputDir);
                    }
                } 
                catch (Exception ex) 
                {
                    Logger.WriteError("{0}: Exception encountered ({1})",de.Name,ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", de.Name, OutputDir);
            }

            foreach (CyPhy.TestBenchType tbt in ltbt_allTB)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    ExportToFile(tbt, OutputDir);
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", tbt.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", tbt.Name, OutputDir);
            }

            Logger.WriteInfo(String.Format("{0} model(s) exported", lde_allCAandDC.Count + ltbt_allTB.Count));
            Logger.WriteInfo("Design Exporter finished");

            if (disposeLogger)
            {
                DisposeLogger();
            }
        }
        public void MainInTransaction(InterpreterMainParameters parameters)
        {
            this.mainParameters = (InterpreterMainParameters)parameters;

            Boolean disposeLogger = false;
            if (Logger == null)
            {
                Logger = new GMELogger(mainParameters.Project, "CyPhyDesignExporter");
                disposeLogger = true;
            }

            var currentObject = mainParameters.CurrentFCO;
            var currentOutputDirectory = mainParameters.OutputDirectory;
            string artifactName = string.Empty;
            string metaBaseName = currentObject.MetaBase.Name;

            try
            {
                if (metaBaseName == typeof(CyPhyClasses.DesignContainer).Name)
                {
                    artifactName = ExportToFile(CyPhyClasses.DesignContainer.Cast(currentObject), currentOutputDirectory);
                }
                else if (metaBaseName == typeof(CyPhyClasses.ComponentAssembly).Name)
                {
                    artifactName = ExportToFile(CyPhyClasses.ComponentAssembly.Cast(currentObject), currentOutputDirectory);
                }
                else if (IsTestBenchType(metaBaseName))
                {
                    artifactName = ExportToFile(CyPhyClasses.TestBenchType.Cast(currentObject), currentOutputDirectory);
                }

                if (!string.IsNullOrWhiteSpace(artifactName))
                {
                    var manifest = AVM.DDP.MetaTBManifest.OpenForUpdate(currentOutputDirectory);
                    manifest.AddArtifact(Path.GetFileName(artifactName), "Design Model");
                    manifest.Serialize(currentOutputDirectory);
                }
            }
            finally
            {
                if (disposeLogger)
                {
                    DisposeLogger();
                }
            }

        }
Example #14
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                // Need to call this interpreter in the same way as the MasterInterpreter will call it.
                // initialize main parameters
                var parameters = new InterpreterMainParameters()
                {
                    Project        = project,
                    CurrentFCO     = currentobj,
                    SelectedFCOs   = selectedobjs,
                    StartModeParam = param
                };

                this.mainParameters         = parameters;
                parameters.ProjectDirectory = Path.GetDirectoryName(currentobj.Project.ProjectConnStr.Substring("MGA=".Length));

                // set up the output directory
                MgaGateway.PerformInTransaction(delegate
                {
                    string outputDirName = project.Name;
                    if (currentobj != null)
                    {
                        outputDirName = currentobj.Name;
                    }

                    parameters.OutputDirectory = Path.GetFullPath(Path.Combine(
                                                                      parameters.ProjectDirectory,
                                                                      "results",
                                                                      outputDirName));

                    //this.Parameters.PackageName = SystemC.Factory.GetModifiedName(currentobj.Name);
                });

                PreConfigArgs preConfigArgs = new PreConfigArgs();
                preConfigArgs.ProjectDirectory = parameters.ProjectDirectory;

                // call the preconfiguration with no parameters and get preconfig
                var preConfig = this.PreConfig(preConfigArgs);

                // get previous GUI config
                var previousConfig = META.ComComponent.DeserializeConfiguration(
                    parameters.ProjectDirectory,
                    typeof(CyPhy2RF_Settings),
                    this.ComponentProgID);

                // get interpreter config through GUI
                var config = this.DoGUIConfiguration(preConfig, previousConfig);
                if (config == null)
                {
                    Logger.WriteWarning("Operation cancelled by the user.");
                    return;
                }

                // if config is valid save it and update it on the file system
                META.ComComponent.SerializeConfiguration(parameters.ProjectDirectory, config, this.ComponentProgID);

                // assign the new configuration to mainParameters
                parameters.config = config;

                // call the main (ICyPhyComponent) function
                this.Main(parameters);
            }
            catch (Exception ex)
            {
                Logger.WriteError("Interpretation failed {0}<br>{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                if (Logger != null)
                {
                    Logger.Dispose();
                    Logger = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
 public LayoutParser(string inFile, GMELogger inLogger) 
 {
     mode = CodeGenerator.Mode.EDA;      // default mode
     gmeLogger = inLogger;
     layoutFile = inFile;
     portTraceMap = new Dictionary<Port, Signal>();
     componentPackageMap = new Dictionary<Component, Package>();
 }
        public LayoutGenerator(Eagle.schematic sch_obj, TestBench tb_obj, GMELogger inLogger)
        {
            this.Logger = inLogger;
            this.pkgPartMap = new Dictionary<Package, Eagle.part>();
            this.partPkgMap = new Dictionary<Eagle.part, Package>();
            this.preroutedPkgMap = new Dictionary<ComponentAssembly, Package>();

            boardLayout = new LayoutJson.Layout();
            var bw = tb_obj.Parameters.Where(p => p.Name.Equals("boardWidth")).FirstOrDefault();
            var bh = tb_obj.Parameters.Where(p => p.Name.Equals("boardHeight")).FirstOrDefault();

            try
            {
                boardLayout.boardWidth = (bw != null) ? Convert.ToDouble(bw.Value) : 40.0;
                boardLayout.boardHeight = (bh != null) ? Convert.ToDouble(bh.Value) : 40.0;
            }
            catch (FormatException ex)
            {
                Logger.WriteWarning("Exception while reading board dimensions: {0}", ex.Message);
            }
            boardLayout.numLayers = 2;
            {
                // Look to see if there is a PCB component in the top level assembly 
                var compImpl = tb_obj.ComponentAssemblies.SelectMany(c => c.ComponentInstances).Select(i => i.Impl)
                    .Where(j => (j as Tonka.Component).Attributes.Classifications
                        .Contains("pcb_board")).FirstOrDefault();
                // Look to see if it has a resource labeled 'BoardTemplate'
                var comp = (compImpl != null) ? compImpl as Tonka.Component : null;
                var btRes = (comp != null) ? comp.Children.ResourceCollection.Where(r =>
                    r.Name.ToUpper().Contains("BOARDTEMPLATE")).FirstOrDefault() : null;
                if (btRes != null)
                {
                    var btPath = Path.Combine(comp.Attributes.Path, btRes.Attributes.Path);
                    boardLayout.boardTemplate = Path.GetFileName(btPath);
                }
            }

            // the prior code looks up for a boardTemplate file associated with a PCB component
            // the users can override it with a boardTemplate file specified as a testbench parameter
            {
                var bt = tb_obj.Parameters.Where(p => p.Name.Equals("boardTemplate")).FirstOrDefault();
                // if its a file path - we only want to pass the file name to board synthesis
                if (bt != null)
                    try
                    {
                        boardLayout.boardTemplate = Path.GetFileName(bt.Value);
                    }
                    catch (System.ArgumentException ex)
                    {
                        CodeGenerator.Logger.WriteError("Error extracting boardTemplate filename: {0}", ex.Message);
                    }
            }
            // the users also can specify a designRule file as a testbench parameter
            {
                var dr = tb_obj.Parameters.Where(p => p.Name.Equals("designRules")).FirstOrDefault();
                if (dr != null)
                    try
                    {
                        boardLayout.designRules = Path.GetFileName(dr.Value);
                    }
                    catch (System.ArgumentException ex)
                    {
                        CodeGenerator.Logger.WriteError("Error extracting designRules filename: {0}", ex.Message);
                    }
            }

            boardLayout.packages = new List<Package>();
            int pkg_idx = 0;

            // we want to handle prerouted assemblies as follows
            // 1) all parts that are part of the pre-routed assembly are tagged with a 'virtual' spaceClaim part
            // 2) we add their absolute location (in the subckt frame of refernece) in the output json
            // 3) we create virtual spaceClaim parts for pre-routed subcircuits

            // 4) all nets belonging to the pre-routed subcircuit are tagged with the spaceClaim part
            // 5) these nets are added to json with absolute location (same as parts above)

            foreach (var ca in tb_obj.ComponentAssemblies)
            {
                pkg_idx = HandlePreRoutedAsm(ca, pkg_idx);
            }

            // compute part dimensions from 
            foreach (var part in sch_obj.parts.part)
            {
                var dev = sch_obj.libraries.library.Where(l => l.name.Equals(part.library)).
                    SelectMany(l => l.devicesets.deviceset).Where(ds => ds.name.Equals(part.deviceset)).
                    SelectMany(ds => ds.devices.device).Where(d => d.name.Equals(part.device)).FirstOrDefault();
                var spkg = (dev != null)
                           ? sch_obj.libraries.library.Where(l => l.name.Equals(part.library))
                                    .SelectMany(l => l.packages.package).Where(p => p.name.Equals(dev.package))
                                    .FirstOrDefault()
                           : null;

                Package pkg = new Package();
                pkg.name = part.name;
                pkg.pkg_idx = pkg_idx++;

                if (dev == null || spkg == null)
                {
                    // emit warning
                    Logger.WriteWarning("Unable to get package size for part - layout/chipfit results may be inaccurate: {0}", part.name);
                }
                else
                {
                    pkg.package = spkg.name;        // note that the eagle package information may be incomplete - should really have curated version from CyPhy

                    #region ComputePackageSize

                    var minX = Double.MaxValue;
                    var minY = Double.MaxValue;
                    var maxX = Double.MinValue;
                    var maxY = Double.MinValue;

                    foreach (Eagle.wire wire in spkg.Items.Where(s => s is Eagle.wire))
                    {
                        if (wire == null) continue;

                        if (!LayersForBoundingBoxComputation.Any(wire.layer.Contains))
                            continue;

                        var x1 = Convert.ToDouble(wire.x1);
                        var x2 = Convert.ToDouble(wire.x2);
                        var y1 = Convert.ToDouble(wire.y1);
                        var y2 = Convert.ToDouble(wire.y2);
                        if (x1 < minX) minX = x1;
                        if (x2 < minX) minX = x2;
                        if (x1 > maxX) maxX = x1;
                        if (x2 > maxX) maxX = x2;
                        if (y1 < minY) minY = y1;
                        if (y2 < minY) minY = y2;
                        if (y1 > maxY) maxY = y1;
                        if (y2 > maxY) maxY = y2;
                    }
                    foreach (Eagle.pad pad in spkg.Items.Where(s => s is Eagle.pad))
                    {
                        if (pad == null) continue;
                        var pad_num = pad.name;
                        var x = Convert.ToDouble(pad.x);
                        var y = Convert.ToDouble(pad.y);
                        var drill = Convert.ToDouble(pad.drill);
                        var dia = Convert.ToDouble(pad.diameter);
                        var shape = pad.shape;  // enum padShape {round, octagon, @long, offset}
                        var rot = pad.rot;      // { R90, R180, R270, ...}  
                        var r = 0.0;
                        if (dia == 0.0)  // JS: Workaround for no diameter present, estimate dia to be 2x drill size 
                        {
                            dia = drill * 2.0;
                        }

                        if (shape == Eagle.padShape.@long)
                        {
                            // TODO: consider PAD rotation; for now, consider long pads are 2x diameter.

                            dia *= 2.0;  // diameter value from package desc is for the "short" side, for max calc, consider long side is 2x (by inspection)
                        }
                        r = dia / 2.0;

                        if ((x - r) < minX) minX = x - r;
                        if ((x + r) > maxX) maxX = x + r;
                        if ((y - r) < minY) minY = y - r;
                        if ((y + r) > maxY) maxY = y + r;
                    }
                    foreach (Eagle.circle circle in spkg.Items.Where(s => s is Eagle.circle))
                    {
                        if (circle == null) continue;
                        var x = Convert.ToDouble(circle.x);
                        var y = Convert.ToDouble(circle.y);
                        var r = Convert.ToDouble(circle.radius);
                        if ((x - r) < minX) minX = x - r;
                        if ((x + r) > maxX) maxX = x + r;
                        if ((y - r) < minY) minY = y - r;
                        if ((y + r) > maxY) maxY = y + r;
                    }
                    foreach (Eagle.smd smd in spkg.Items.Where(s => s is Eagle.smd))
                    {
                        if (smd == null) continue;
                        // SKN: after intense research on eagle, it seems that the way SMD pads are placed is as follows
                        // dx - dy tells the length of the pad, while the x is the center point of the SMD pad

                        var x = Convert.ToDouble(smd.x);
                        var y = Convert.ToDouble(smd.y);
                        var ddx = Convert.ToDouble(smd.dx);
                        var ddy = Convert.ToDouble(smd.dy);
                        var dx = ddx;  // should be /2??
                        var dy = ddy;
                        if (smd.rot.Equals("R90") || smd.rot.Equals("R270"))
                        {       // flip dx and dy if there is rotation
                            dx = ddy;
                            dy = ddx;
                        }
                        var x1 = x - dx / 2.0;
                        var x2 = x + dx / 2.0;
                        var y1 = y - dy / 2.0;
                        var y2 = y + dy / 2.0;
                        if (x1 < minX) minX = x1;
                        if (x2 > maxX) maxX = x2;
                        if (y1 < minY) minY = y1;
                        if (y2 > maxY) maxY = y2;
                    }
                    pkg.width = maxX - minX;
                    pkg.height = maxY - minY;
                    pkg.originX = Math.Floor(10.0 * (maxX + minX) / 2.0) / 10.0;
                    pkg.originY = Math.Floor(10.0 * (maxY + minY) / 2.0) / 10.0;

                    #endregion

                    // emit component ID for locating components in CAD assembly
                    if (CodeGenerator.partComponentMap.ContainsKey(part))
                    {
                        var comp_obj = CodeGenerator.partComponentMap[part];
                        var comp = comp_obj.Impl as Tonka.Component;

                        // emit component ID for locating components in CAD assembly
                        pkg.ComponentID = comp.Attributes.InstanceGUID;

                        Boolean isMultiLayer = comp.Children.EDAModelCollection.
                            Any(e => e.Attributes.HasMultiLayerFootprint);
                        if (isMultiLayer)
                            pkg.multiLayer = true;

                        #region ExactConstraints
                        // exact constraints related to this part
                        var exactCons =
                            from conn in comp.SrcConnections.ApplyExactLayoutConstraintCollection
                            select conn.SrcEnds.ExactLayoutConstraint;

                        foreach (var c in exactCons)
                        {
                            var pcons = new ExactConstraint();
                            pcons.type = "exact";
                            if (!c.Attributes.X.Equals(""))
                                pcons.x = Convert.ToDouble(c.Attributes.X);
                            if (!c.Attributes.Y.Equals(""))
                                pcons.y = Convert.ToDouble(c.Attributes.Y);
                            if (!c.Attributes.Layer.Equals(""))
                                pcons.layer = Convert.ToInt32(c.Attributes.Layer);
                            if (!c.Attributes.Rotation.Equals(""))
                                pcons.rotation = Convert.ToInt32(c.Attributes.Rotation);
                            if (pkg.constraints == null)
                                pkg.constraints = new List<Constraint>();
                            pkg.constraints.Add(pcons);
                        }
                        #endregion

                        #region RangeConstraints
                        // range constraints related to this part
                        var rangeCons =
                            from conn in comp.SrcConnections.ApplyRangeLayoutConstraintCollection
                            select conn.SrcEnds.RangeLayoutConstraint;
                        foreach (var c in rangeCons)
                        {
                            var pcons = new RangeConstraint();
                            pcons.type = "range";
                            if (!c.Attributes.XRange.Equals(""))
                                pcons.x = c.Attributes.XRange;
                            if (!c.Attributes.YRange.Equals(""))
                                pcons.y = c.Attributes.YRange;
                            if (!c.Attributes.LayerRange.Equals(""))
                                pcons.layer = c.Attributes.LayerRange;
                            if (pkg.constraints == null)
                                pkg.constraints = new List<Constraint>();
                            pkg.constraints.Add(pcons);
                        }
                        #endregion

                        #region PreRoutedAssemblyPart
                        // now handle if this component is part of a pre-routed sub-ckt
                        if (CodeGenerator.preRouted.ContainsKey(comp_obj.Parent))
                        {
                            var layoutParser = CodeGenerator.preRouted[comp_obj.Parent];
                            var prePkg = layoutParser.componentPackageMap[comp_obj];
                            pkg.x = prePkg.x;
                            pkg.y = prePkg.y;
                            pkg.rotation = prePkg.rotation;
                            pkg.RelComponentID = (comp_obj.Parent.Impl.Impl as GME.MGA.MgaFCO)
                                .RegistryValue["Elaborator/InstanceGUID_Chain"];
                            pkg.doNotPlace = true;
                        }
                        #endregion
                    }
                }
                pkgPartMap.Add(pkg, part);  // add to map
                partPkgMap.Add(part, pkg);
                boardLayout.packages.Add(pkg);
            }



            #region AddSignalsToBoardLayout
            boardLayout.signals = new List<Signal>();
            foreach (var net in sch_obj.sheets.sheet.FirstOrDefault().nets.net)
            {
                // dump pre-routed signals to board file
                var sig = new Signal();
                sig.name = net.name;
                sig.pins = new List<Pin>();

                Signal preRouted = null;
                string preRoutedAsmID = null; // ID of the parent pre-routed assembly
                string preRoutedAsm = null; // name the parent pre-routed assembly
                bool onlyOnePreroute = true;

                foreach (var seg in net.segment.SelectMany(s => s.Items).Where(s => s is Eagle.pinref))
                {
                    bool isPrerouted = false;

                    var pr = seg as Eagle.pinref;
                    var pin = new Pin();
                    pin.name = pr.pin;
                    pin.gate = pr.gate;
                    pin.package = pr.part.ToUpper();

                    // find package and pad
                    var part = sch_obj.parts.part.Where(p => p.name.Equals(pr.part)).FirstOrDefault();

                    var dev = (part != null) ?
                        sch_obj.libraries.library.Where(l => l.name.Equals(part.library)).
                        SelectMany(l => l.devicesets.deviceset).Where(ds => ds.name.Equals(part.deviceset)).
                        SelectMany(ds => ds.devices.device).Where(d => d.name.Equals(part.device)).FirstOrDefault()
                        : null;
                    var pad = (dev != null) ?
                        dev.connects.connect.Where(c => c.gate.Equals(pr.gate) && c.pin.Equals(pr.pin)).Select(c => c.pad).FirstOrDefault()
                        : null;
                    if (pad != null)
                        pin.pad = pad;

                    // check for preroutes - all pins in this signal should be in the prerouted net, otherwise reject it
                    if (part != null && CodeGenerator.partComponentMap.ContainsKey(part))
                    {
                        var comp_obj = CodeGenerator.partComponentMap[part];
                        if (CodeGenerator.preRouted.ContainsKey(comp_obj.Parent)) // is the parent assembly prerouted
                        {
                            Logger.WriteDebug("Net {0} in Prerouted Asm {1}", net.name, comp_obj.Parent.Name);

                            var layoutParser = CodeGenerator.preRouted[comp_obj.Parent];
                            // find the name/gate matching port in schematic domain model
                            var sch = comp_obj.Impl.Children.SchematicModelCollection.FirstOrDefault();

                            var port = (sch != null) ?
                                sch.Children.SchematicModelPortCollection.
                                Where(p => p.Attributes.EDAGate == pin.gate && p.Name == pin.name).
                                FirstOrDefault()
                                : null;

                            // find the buildPort
                            var buildPort = port != null && CyPhyBuildVisitor.Ports.ContainsKey(port.ID) ?
                                CyPhyBuildVisitor.Ports[port.ID] : null;


                            if (buildPort != null && layoutParser.portTraceMap.ContainsKey(buildPort))
                            {
                                isPrerouted = true;
                                Logger.WriteDebug("Found build Port and Associated Trace");

                                if (preRouted == null)
                                {
                                    preRouted = layoutParser.portTraceMap[buildPort];
                                    preRoutedAsmID = (comp_obj.Parent.Impl.Impl as GME.MGA.MgaFCO)
                                        .RegistryValue["Elaborator/InstanceGUID_Chain"];
                                    preRoutedAsm = comp_obj.Parent.Name;
                                }
                                else if (preRouted != layoutParser.portTraceMap[buildPort])
                                    isPrerouted = false;
                            }
                        }
                    }

                    onlyOnePreroute = onlyOnePreroute && isPrerouted;

                    // add pin to list of pins for this signal
                    sig.pins.Add(pin);
                }

                // if pre-routed then copy wires 
                if (onlyOnePreroute && preRouted != null)
                {
                    Logger.WriteInfo("Prerouted net {0}, from assembly {1}, originally as {2}", net.name, preRoutedAsm, preRouted.name);
                    sig.wires = new List<Wire>();
                    sig.vias = new List<Via>();
                    sig.RelComponentID = preRoutedAsmID;
                    foreach (var w in preRouted.wires)
                        sig.wires.Add(w);
                    foreach (var v in preRouted.vias)
                        sig.vias.Add(v);
                }

                boardLayout.signals.Add(sig);
            }
            #endregion

            #region AddRelativeConstraintsToBoardLayout
            // now process relative constraints - they require that all parts be mapped to packages already
            for (int i = 0; i < boardLayout.packages.Count; i++)
            {
                var pkg = boardLayout.packages[i];
                if (!pkgPartMap.ContainsKey(pkg))
                    continue;

                var part = pkgPartMap[pkg];
                var comp = CodeGenerator.partComponentMap.ContainsKey(part) ?
                    CodeGenerator.partComponentMap[part] : null;
                var impl = comp != null ? comp.Impl as Tonka.Component : null;
                var relCons =
                    from conn in impl.SrcConnections.ApplyRelativeLayoutConstraintCollection
                    select conn.SrcEnds.RelativeLayoutConstraint;

                foreach (var c in relCons)
                {
                    var pcons = new RelativeConstraint();
                    pcons.type = "relative-pkg";
                    if (!c.Attributes.XOffset.Equals(""))
                        pcons.x = Convert.ToDouble(c.Attributes.XOffset);
                    if (!c.Attributes.YOffset.Equals(""))
                        pcons.y = Convert.ToDouble(c.Attributes.YOffset);
                    // find origin comp
                    var origCompImpl = (from conn in c.SrcConnections.RelativeLayoutConstraintOriginCollection
                                        select conn.SrcEnds.Component).FirstOrDefault();
                    var origComp =
                        ((origCompImpl != null) && CyPhyBuildVisitor.Components.ContainsKey(origCompImpl.ID)) ?
                        CyPhyBuildVisitor.Components[origCompImpl.ID] :
                        null;
                    var origPart =
                        ((origComp != null) && CodeGenerator.componentPartMap.ContainsKey(origComp)) ?
                        CodeGenerator.componentPartMap[origComp] :
                        null;
                    var origPkg = ((origPart != null) && partPkgMap.ContainsKey(origPart)) ?
                        partPkgMap[origPart] :
                        null;
                    pcons.pkg_idx = origPkg.pkg_idx.Value;
                    if (pkg.constraints == null)
                        pkg.constraints = new List<Constraint>();
                    pkg.constraints.Add(pcons);
                    boardLayout.packages[i] = pkg;
                }

            }
            #endregion

        }
Example #17
0
        public bool RunInTransaction(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, string outputDirectory = null, bool commitTransaction = false)
        {
            bool success             = false;
            bool shouldDisposeLogger = false;

            try
            {
                MgaGateway = new MgaGateway(project);

                // populate a test model

                /*MgaGateway.PerformInTransaction(delegate
                 * {
                 *  currentobj = GenerateTestModel(project, currentobj);
                 * }, transactiontype_enum.TRANSACTION_NON_NESTED);*/

                if (this.Logger == null)
                {
                    GMELogger gmeLogger;
                    this.Logger = gmeLogger = new CyPhyGUIs.GMELogger(project, this.ComponentName);
                    gmeLogger.GMEConsoleLoggingLevel = this.Convert(param) == ComponentStartMode.GME_SILENT_MODE ?
                                                       CyPhyGUIs.SmartLogger.MessageType_enum.Warning :
                                                       CyPhyGUIs.SmartLogger.MessageType_enum.Info;
                    this.Logger.LoggingLevel = SmartLogger.MessageType_enum.Info;
                    shouldDisposeLogger      = true;
                }

                HashSet <string> m_addonNames = new HashSet <string>()
                {
                    "ConstraintManager".ToLowerInvariant(),
                    "CyPhyAddOn".ToLowerInvariant(),
                    "CyPhyDecoratorAddon".ToLowerInvariant(),
                    "CyPhyMdaoAddOn".ToLowerInvariant(),
                    "CyPhySignalBlocksAddOnAddon".ToLowerInvariant(),
                    "ComponentLibraryManagerAddOn".ToLowerInvariant()
                };

                // turn off all addons specified above
                var addons = project.AddOnComponents.Cast <IMgaComponentEx>();
                foreach (var addon in addons)
                {
                    if (addon.ComponentName.ToLowerInvariant() == "CyPhyAddOn".ToLowerInvariant())
                    {
                        addon.ComponentParameter["DontAssignGuidsOnNextTransaction".ToLowerInvariant()] = true;
                    }

                    if (m_addonNames.Contains(addon.ComponentName.ToLowerInvariant()))
                    {
                        try
                        {
                            addon.Enable(false);
                        }
                        catch (Exception ex)
                        {
                            // if one fails keep trying the other ones.
                            this.Logger.WriteError("Turing off addon failed: {0} --> {1}", addon.ComponentName, ex.ToString());
                        }
                    }
                }

                try
                {
                    MgaGateway.PerformInTransaction(delegate
                    {
                        success = this.Main(project, currentobj, selectedobjs, this.Convert(param));

                        if (String.IsNullOrEmpty(outputDirectory) == false)
                        {
                            UpdateMetricsInTestbenchManifest(currentobj, outputDirectory);
                        }
                    },
                                                    transactiontype_enum.TRANSACTION_NON_NESTED, abort: !commitTransaction);

                    // call old elaborator
                    ////this.CallOldElaborator(project, currentobj);
                }
                catch (Exception ex)
                {
                    this.Logger.WriteInfo(ex.ToString());
                    success = false;
                }
                finally
                {
                    foreach (var addon in addons)
                    {
                        if (m_addonNames.Contains(addon.ComponentName.ToLowerInvariant()))
                        {
                            try
                            {
                                addon.Enable(true);
                            }
                            catch (Exception ex)
                            {
                                // if one fails keep trying the other ones.
                                this.Logger.WriteError("Turing off addon failed: {0} --> {1}", addon.ComponentName, ex.ToString());
                            }
                        }
                    }
                }
            }
            finally
            {
                if (shouldDisposeLogger &&
                    this.Logger != null)
                {
                    this.Logger.Dispose();
                }

                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return(success);
        }
 private void InitializeLogger(MgaProject project)
 {
     Logger = new GMELogger(project, this.ComponentName);
 }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                // Need to call this interpreter in the same way as the MasterInterpreter will call it.
                // initialize main parameters
                var parameters = new InterpreterMainParameters()
                {
                    Project = project,
                    CurrentFCO = currentobj,
                    SelectedFCOs = selectedobjs,
                    StartModeParam = param
                };

                this.mainParameters = parameters;
                parameters.ProjectDirectory = Path.GetDirectoryName(currentobj.Project.ProjectConnStr.Substring("MGA=".Length));

                // set up the output directory
                MgaGateway.PerformInTransaction(delegate
                {
                    string outputDirName = project.Name;
                    if (currentobj != null)
                    {
                        outputDirName = currentobj.Name;
                    }

                    parameters.OutputDirectory = Path.GetFullPath(Path.Combine(
                        parameters.ProjectDirectory,
                        "results",
                        outputDirName));

                    //this.Parameters.PackageName = SystemC.Factory.GetModifiedName(currentobj.Name);
                });

                PreConfigArgs preConfigArgs = new PreConfigArgs();
                preConfigArgs.ProjectDirectory = parameters.ProjectDirectory;

                // call the preconfiguration with no parameters and get preconfig
                var preConfig = this.PreConfig(preConfigArgs);

                // get previous GUI config
                var previousConfig = META.ComComponent.DeserializeConfiguration(
                    parameters.ProjectDirectory,
                    typeof(CyPhy2RF_Settings),
                    this.ComponentProgID);

                // get interpreter config through GUI
                var config = this.DoGUIConfiguration(preConfig, previousConfig);
                if (config == null)
                {
                    Logger.WriteWarning("Operation cancelled by the user.");
                    return;
                }

                // if config is valid save it and update it on the file system
                META.ComComponent.SerializeConfiguration(parameters.ProjectDirectory, config, this.ComponentProgID);

                // assign the new configuration to mainParameters
                parameters.config = config;

                // call the main (ICyPhyComponent) function
                this.Main(parameters);
            }
            catch (Exception ex)
            {
                Logger.WriteError("Interpretation failed {0}<br>{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                if (MgaGateway != null && MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                if (Logger != null)
                {
                    Logger.Dispose();
                    Logger = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #20
0
        public void ImportCADModel(string CADpath = null)
        {
            string cadFilename = "";

            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);
            using (this.Logger)
            {
                //The CAT module will perform these steps, in this order:
                //  - Check that the user has Creo (so that the extraction will be successful)
                //      - Implementation Suggestion: The extraction utility may have special flag to have it indicates if all the dependencies are met

                //  - Display a dialog box to let the user choose their Creo model file
                bool cad_file_chosen         = false;
                bool test_copy_and_path_only = false;
                if (string.IsNullOrWhiteSpace(CADpath))
                {
                    cad_file_chosen = get_cad_file(out cadFilename);
                }
                else
                {
                    test_copy_and_path_only = true;
                    cadFilename             = CADpath;
                    if (File.Exists(cadFilename))
                    {
                        cad_file_chosen = true;
                    }
                    else
                    {
                        this.Logger.WriteError("Invalid CAD file path passed in: " + CADpath);
                    }
                }

                //  - Run the extractor on the Creo model file
                #region Run the Extractor

                bool   extractor_ran_success = test_copy_and_path_only;
                string tempXMLfile           = Path.GetTempFileName();
                this.Logger.WriteDebug("Temporary XML file created: " + tempXMLfile);

                if (cad_file_chosen && !test_copy_and_path_only)
                {
                    try
                    {
                        // assemble the arg string
                        // first the input CAD file
                        // include quotation marks to handle paths with white spaces
                        string argstring = "ExtractACM-XMLfromCreoModels -c \"";
                        argstring += cadFilename;
                        argstring += "\"";

                        // add the XML output file name
                        argstring += " -x \"";
                        argstring += tempXMLfile;
                        argstring += "\"";

                        // Debug only: pause before exit, graphics mode.
                        //argstring += " -p -g";

                        Process firstProc = new Process();

                        string path = Path.Combine(META.VersionInfo.MetaPath, "bin\\CAD\\Creo\\bin\\CADCreoParametricCreateAssembly.exe");
                        if (!File.Exists(path))
                        {
                            this.Logger.WriteError(String.Format("Cannot find '{0}'", path));
                            throw new Exception("CADCreoParametricCreateAssembly.exe not found.");
                        }

                        firstProc.StartInfo.FileName               = path;
                        firstProc.StartInfo.Arguments              = argstring;
                        firstProc.StartInfo.CreateNoWindow         = true;
                        firstProc.StartInfo.UseShellExecute        = false;
                        firstProc.StartInfo.RedirectStandardOutput = true;
                        firstProc.StartInfo.RedirectStandardError  = true;
                        firstProc.StartInfo.RedirectStandardInput  = true;

                        int           streamsClosed    = 0;
                        StringBuilder exeConsoleOutput = new StringBuilder();

                        DataReceivedEventHandler handler = (sender, e) =>
                        {
                            lock (Logger)
                            {
                                if (e.Data == null)
                                {
                                    streamsClosed += 1;
                                    if (streamsClosed == 2)
                                    {
                                    }
                                    return;
                                }
                                Logger.WriteDebug(e.Data);
                                exeConsoleOutput.AppendLine(e.Data);
                            }
                        };
                        firstProc.OutputDataReceived += handler;
                        firstProc.ErrorDataReceived  += handler;
                        firstProc.EnableRaisingEvents = true;
                        bool             showProgressBar        = sender != null && sender is IWin32Window;
                        bool             done                   = false;
                        Object           doneSyncObject         = new object();
                        GUIs.CADProgress progress               = null;
                        EventHandler     closeDialogWithSuccess = (e, o) =>
                        {
                            lock (doneSyncObject)
                            {
                                if (done == false)
                                {
                                    progress.BeginInvoke((Action)(() =>
                                    {
                                        done = true;
                                        progress.DialogResult = DialogResult.OK;
                                        progress.Close();
                                    }));
                                }
                            }
                        };
                        if (showProgressBar)
                        {
                            progress          = new GUIs.CADProgress();
                            firstProc.Exited += closeDialogWithSuccess;
                        }
                        IntPtr job = JobObjectPinvoke.CreateKillOnCloseJob();
                        firstProc.Exited += (s, o) =>
                        {
                            if (job != JobObjectPinvoke.INVALID_HANDLE_VALUE)
                            {
                                JobObjectPinvoke.CloseHandle(job);
                            }
                            if (progress != null && progress.DialogResult == DialogResult.Cancel)
                            {
                                File.Delete(tempXMLfile);
                            }
                        };

                        this.Logger.WriteDebug("Calling CADCreoParametricCreateAssembly.exe with argument string: " + argstring);

                        firstProc.Start();
                        JobObjectPinvoke.AssignProcessToJobObject(firstProc, job);
                        firstProc.StandardInput.Close();
                        firstProc.BeginOutputReadLine();
                        firstProc.BeginErrorReadLine();

                        if (showProgressBar)
                        {
                            progress.FormClosing += (e, o) =>
                            {
                                lock (doneSyncObject)
                                {
                                    firstProc.Exited -= closeDialogWithSuccess;
                                    done              = true;
                                }
                            };
                            var result = progress.ShowDialog((IWin32Window)sender);
                            if (result == DialogResult.Cancel)
                            {
                                cleanup(null, true);
                                return;
                            }
                        }
                        else
                        {
                            firstProc.WaitForExit();
                        }

                        this.Logger.WriteDebug("CADCreoParametricCreateAssembly.exe ExtractACM-XMLfromCreoModels has completed.");

                        if (firstProc.ExitCode == 0)
                        {
                            extractor_ran_success = true;
                        }
                        else
                        {
                            this.Logger.WriteDebug("CADCreoParametricCreateAssembly.exe ExtractACM-XMLfromCreoModels returned error code " + firstProc.ExitCode.ToString());
                            // Warn with last non-empty line, it should contain a useful error message
                            Regex lastLine = new Regex("[\\n^]([^\\n]+)(\\n|\\s)*$", RegexOptions.Singleline);
                            var   match    = lastLine.Match(exeConsoleOutput.ToString());
                            if (match != null && match.Success)
                            {
                                this.Logger.WriteWarning(match.Groups[1].Value);
                            }
                            throw new Exception("Extract executable returned error code " + firstProc.ExitCode.ToString() + ". Detailed log at " + this.Logger.LogFilenames.FirstOrDefault());
                        }
                    }
                    catch (Exception ex)
                    {
                        this.Logger.WriteError("An error occurred running Creo parametric: " + ex.Message + " - Extraction Failed. Insure you can access the Creo license server");
                        cleanup(tempXMLfile, true);
                        return;
                    }
                }
                #endregion

                //  - Use a function from CyPhy2ComponentModel to convert the extractor's XML format into a CyPhy model fragment
                #region Convert_to_XML
                // used in creating the resource object below
                CyPhy.CADModel ProcessedCADModel = null;

                if (extractor_ran_success && !test_copy_and_path_only)
                {
                    this.Logger.WriteDebug("About to call DeserializeAvmComponentXml...");
                    StreamReader  streamReader = new StreamReader(tempXMLfile);
                    avm.Component ac_import    = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(streamReader);
                    streamReader.Close();
                    this.Logger.WriteDebug("... finished DeserializeAvmComponentXml call.");

                    foreach (var cadmodel in ac_import.DomainModel.Where(dm => dm is avm.cad.CADModel)
                             .Cast <avm.cad.CADModel>())
                    {
                        var rf = CyPhyClasses.RootFolder.GetRootFolder(CurrentProj);

                        AVM2CyPhyML.CyPhyMLComponentBuilder newComponent = new AVM2CyPhyML.CyPhyMLComponentBuilder(rf);
                        ProcessedCADModel      = newComponent.process(cadmodel, (CyPhy.Component)GetCurrentDesignElement());
                        ProcessedCADModel.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFilename));
                    }

                    // find the largest current Y value so our new elements are added below the existing design elements
                    foreach (var child in GetCurrentDesignElement().AllChildren)
                    {
                        foreach (MgaPart item in (child.Impl as MgaFCO).Parts)
                        {
                            int    read_x, read_y;
                            string read_str;
                            item.GetGmeAttrs(out read_str, out read_x, out read_y);
                            greatest_current_y = (read_y > greatest_current_y) ? read_y : greatest_current_y;
                        }
                    }

                    // layout CAD model to the "south" of existing elements
                    foreach (MgaPart item in (ProcessedCADModel.Impl as MgaFCO).Parts)
                    {
                        item.SetGmeAttrs(null, CAD_MODEL_START_X, greatest_current_y + CAD_MODEL_START_Y);
                    }

                    // Extend it's properties out to the component level.
                    this.CADModuleImportExtension(ProcessedCADModel);
                }
                else if (test_copy_and_path_only)
                {
                    ProcessedCADModel      = CyPhyClasses.CADModel.Create((CyPhy.Component)GetCurrentDesignElement());
                    ProcessedCADModel.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(CADpath));
                }

                #endregion

                //  - Copy the Creo Model files into the component's backend folder
                //      - Note: The solution includes a function that can find this folder using the project.manifest.json file.
                //      - For nice organization, create them in a subfolder called "CAD"
                // create avmproj
                #region Copy files to backend folder

                // used in creating the resource object below
                string PathforComp = null;

                var importedCADFiles = new List <String>();
                if (extractor_ran_success)
                {
                    try
                    {
                        // create the destination path
                        PathforComp = META.ComponentLibraryManager.EnsureComponentFolder((CyPhy.Component)GetCurrentDesignElement());
                        PathforComp = ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

                        string finalPathName = Path.Combine(PathforComp, "CAD");

                        Directory.CreateDirectory(finalPathName);

                        // determine if one part file or all part and assembly files need to be copied
                        string cpsrcfile = System.IO.Path.GetFileName(cadFilename);

                        // copy the selected file
                        string cadFileCopyPath = System.IO.Path.Combine(finalPathName, cpsrcfile);
                        if (Path.GetFullPath(cadFilename) != Path.GetFullPath(cadFileCopyPath))
                        {
                            System.IO.File.Copy(cadFilename, cadFileCopyPath, true);
                        }

                        // Set "primary" file as the first in the list.
                        importedCADFiles.Add(Path.Combine("CAD", Path.GetFileName(cadFileCopyPath)));

                        if (fileISasm(cpsrcfile) && !test_copy_and_path_only)
                        {
                            // get a string of the XML contents
                            this.Logger.WriteDebug("About to read contents of XML file using class XmlDocument: " + tempXMLfile);

                            XmlDocument doc = new XmlDocument();
                            doc.Load(tempXMLfile);
                            string xmlcontents = doc.InnerXml;

                            // mine down to the Resource dependencies
                            using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents)))
                            {
                                // iterate through each file listed in the resourcedependency section
                                while (reader.ReadToFollowing("ResourceDependency") == true)
                                {
                                    string res_path = reader.GetAttribute("Path");
                                    this.Logger.WriteDebug("Copying this file: " + res_path);

                                    // CAD files end in .1 .2 etc. Pick the latest ones
                                    var allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*prt." /*n.b. literal dot*/ + "*")
                                                   .Concat(Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*asm.*"))
                                                   .Select(Path.GetFileName)
                                                   .Select(filename => new { basename = filename.Substring(0, filename.LastIndexOf('.')), version = filename.Substring(filename.LastIndexOf('.') + 1) })
                                                   .Where(p => { int val; return(Int32.TryParse(p.version, out val)); })
                                                   .OrderByDescending(p => Int32.Parse(p.version))
                                                   .ToArray();
                                    foreach (var basename in allFiles.Select(p => p.basename).Distinct())
                                    {
                                        var latest = allFiles.Where(p => p.basename == basename).FirstOrDefault();
                                        if (latest != null)
                                        {
                                            string latestFilename = latest.basename + "." + latest.version;
                                            // Need to limit this down to just the filename in question
                                            // The XML file changes the name to all caps, so compare apples to apples
                                            if (latestFilename.ToUpperInvariant().StartsWith(Path.GetFileName(res_path).ToUpperInvariant()))
                                            {
                                                string destpathandname = Path.Combine(finalPathName, latestFilename);
                                                if (!importedCADFiles.Contains(Path.Combine("CAD", Path.GetFileName(destpathandname))))
                                                {
                                                    importedCADFiles.Add(Path.Combine("CAD", Path.GetFileName(destpathandname)));
                                                }
                                                var sourcepathandname = Path.Combine(Path.GetDirectoryName(res_path), latestFilename);
                                                if (Path.GetFullPath(sourcepathandname) != Path.GetFullPath(destpathandname))
                                                {
                                                    File.Copy(sourcepathandname, destpathandname, true);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception err_create_proj)
                    {
                        this.Logger.WriteError("Error creating AVM project: " + err_create_proj.Message, " - Extraction Failed. Possible ComponentManagement issue.");
                        cleanup(tempXMLfile, true);
                        return;
                    }
                }
                #endregion

                //  - Create Resource objects in the CyPhy Component model that point to these Creo Model files
                //      - Note: The "paths" of these should be the relative path from that component's root folder
                if (extractor_ran_success)
                {
                    foreach (var cadFile in importedCADFiles)
                    {
                        CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create((CyPhy.Component)GetCurrentDesignElement());
                        ResourceObj.Attributes.ID    = Guid.NewGuid().ToString("B");
                        ResourceObj.Attributes.Path  = AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFile);
                        ResourceObj.Attributes.Notes = "CAD Model Import tool added this resource object for the imported CAD file";
                        ResourceObj.Name             = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFile));

                        // layout Resource just to the side of the CAD model
                        foreach (MgaPart item in (ResourceObj.Impl as MgaFCO).Parts)
                        {
                            item.SetGmeAttrs(null, RESOURCE_START_X, greatest_current_y + RESOURCE_START_Y);
                        }

                        // The "primary" CAD model is the first one -- associate it with the CyPhy CADModel object
                        if (importedCADFiles.IndexOf(cadFile) == 0)
                        {
                            //  - Create a UsesResource association between the CyPhy CADModel object and the Resource object that represents the top-level Creo Model file.
                            CyPhyClasses.UsesResource.Connect(ResourceObj, ProcessedCADModel, null, null, (CyPhy.Component)GetCurrentDesignElement());
                        }
                    }
                }

                // throw in an ACM file for the current state of the component.
                if (extractor_ran_success && !test_copy_and_path_only)
                {
                    var    exporter = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter();
                    String acmPath  = Path.Combine(PathforComp, GetCurrentDesignElement().Name + ".component.acm");
                    CyPhyComponentExporterInterpreter.ExportToDirectory((CyPhy.Component)GetCurrentDesignElement(), Path.GetDirectoryName(acmPath));
                }

                // Clean up
                cleanup(tempXMLfile, (extractor_ran_success && !test_copy_and_path_only));
            }
        }
        /// <summary>
        /// No GUI and interactive elements are allowed within this function.
        /// </summary>
        /// <param name="parameters">Main parameters for this run and GUI configuration.</param>
        /// <returns>Result of the run, which contains a success flag.</returns>
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            if (Logger == null)
                Logger = new GMELogger(parameters.Project, ComponentName);

            this.runtime.Clear();
            this.mainParameters = parameters;
            var configSuccess = this.mainParameters != null;
            this.UpdateSuccess("Configuration", configSuccess);
            this.result.Labels = "RF";

            try
            {
                MgaGateway.PerformInTransaction(delegate
                    {
                        this.WorkInMainTransaction();
                    },
                    transactiontype_enum.TRANSACTION_NON_NESTED,
                    abort: true
                );

                this.PrintRuntimeStatistics();
                if (this.result.Success)
                {
                    Logger.WriteInfo("Generated files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>", this.mainParameters.OutputDirectory);
                    Logger.WriteInfo("RF simulation has been created. [SUCCESS: {0}, Labels: {1}]", this.result.Success, this.result.Labels);
                }
                else
                {
                    Logger.WriteError("RF simulation cannot be created! See error messages above.");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError("Exception: {0}<br> {1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                if (MgaGateway != null &&
                    MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                if (Logger != null)
                {
                    Logger.Dispose();
                    Logger = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            META.Logger.RemoveFileListener(this.ComponentName);

            return this.result;
        }