Inheritance: IInterpreterResult
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            this.mainParameters = (InterpreterMainParameters)parameters;

            try
            {
                MgaGateway = new MgaGateway(mainParameters.Project);

                var result = new InterpreterResult() { Success = true, RunCommand = "" };

                MgaGateway.PerformInTransaction(delegate
                {
                    MainInTransaction((InterpreterMainParameters)parameters);


                    // TODO: this part needs to be refactored!
                    var workflowRef = this.mainParameters
                        .CurrentFCO
                        .ChildObjects
                        .OfType<MgaReference>()
                        .FirstOrDefault(x => x.Meta.Name == "WorkflowRef");
                    
                    if (workflowRef != null)
                    {
                        string Parameters = workflowRef
                            .Referred
                            .ChildObjects
                            .OfType<MgaAtom>()
                            .FirstOrDefault(fco => fco.Meta.Name == typeof(CyPhy.Task).Name
                                && String.Equals(CyPhyClasses.Task.Cast(fco).Attributes.COMName, this.ComponentProgID, StringComparison.InvariantCultureIgnoreCase))
                            .StrAttrByName["Parameters"];

                        Dictionary<string, string> workflowParameters = new Dictionary<string, string>();

                        try
                        {
                            workflowParameters = (Dictionary<string, string>)Newtonsoft.Json.JsonConvert.DeserializeObject(Parameters, typeof(Dictionary<string, string>));
                            if (workflowParameters == null)
                            {
                                workflowParameters = new Dictionary<string, string>();
                            }
                        }
                        catch (Newtonsoft.Json.JsonReaderException)
                        {
                        }

                        META.AnalysisTool.ApplyToolSelection(this.ComponentProgID, workflowParameters, result, this.mainParameters);
                    }
                });

                return result;
            }
            finally
            {
                MgaGateway = null;                
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Beispiel #2
0
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            var result = new InterpreterResult();
            result.RunCommand = "runCarSim.bat";
            try
            {

                MgaGateway.PerformInTransaction(delegate
                {
                    if (parameters.CurrentFCO.MetaBase.Name == "CarTestBench")
                    {
                        try
                        {
                            var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter();
                            elaborator.Logger = new GMELogger(parameters.Project);
                            //elaborator.Logger.AddWriter(Logger.Instance);
                            var elaboratorresult = elaborator.RunInTransaction(parameters.Project, parameters.CurrentFCO, parameters.SelectedFCOs, parameters.StartModeParam);
                            if (elaboratorresult == false)
                            {
                                throw new ApplicationException("see elaborator log");
                            }

                        }
                        catch (Exception e)
                        {
                            //Logger.Instance.AddLogMessage("Elaborator exception occurred: " + e.Message, Severity.Error);
                            throw new Exception(e.Message);
                        }
                        var testBench = CyPhyClasses.CarTestBench.Cast(parameters.CurrentFCO);

                        TestBenchProcessor processor = new TestBenchProcessor() { GMEConsole = GMEConsole, OutputDir = parameters.OutputDirectory, ProjectDir = parameters.ProjectDirectory };
                        processor.Process(testBench);
                    }
                    else
                    {
                        GMEConsole.Error.WriteLine("Not a Car Test Bench.");
                        return;
                    }
                },
                transactiontype_enum.TRANSACTION_NON_NESTED, abort: true);
                result.Success = true;
            }
            catch (Exception ex)
            {
                GMEConsole.Error.WriteLine("Exception was raised: {0}", ex.ToString());
                result.Success = false;
            }
            finally
            {
//                parameters.Project.AbortTransaction();
                MgaGateway = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return result;
        }
Beispiel #3
0
        public void Main()
        {
            if (CurrentObjectRequired == true &&
                MainParameters.CurrentFCO == null)
            {
                throw new InterpreterException("Current object is not set for COM object.");
            }
            if (MgaComponent == null)
            {
                throw new ArgumentNullException("MgaComponent");
            }
            if (MgaComponent is ICyPhyInterpreter)
            {
                MainParameters.config = InterpreterConfig;
                result = ((ICyPhyInterpreter)MgaComponent).Main(MainParameters);
            }
            else
            {
                // set up the interpreter specific parameters
                if (ProgId == "MGA.Decorator.CyPhy2CAD")
                {
                    MgaComponent.ComponentParameter["generateCAD"] = "true";
                }
                MgaComponent.ComponentParameter["automation"] = "true";
                MgaComponent.ComponentParameter["output_dir"] = MainParameters.OutputDirectory;
                MgaComponent.ComponentParameter["console_messages"] = MainParameters.ConsoleMessages ? "on" : "off";
                MgaComponent.ComponentParameter["original_project_file"] = Path.Combine(MainParameters.ProjectDirectory, "fake.mga");
                MgaComponent.ComponentParameter["do_config"] = "false";

                MgaComponent.InvokeEx(
                    MainParameters.Project,
                    MainParameters.CurrentFCO,
                    MainParameters.SelectedFCOs,
                    MainParameters.StartModeParam);

                InterpreterResult result = new InterpreterResult();
                result.Labels = MgaComponent.ComponentParameter["labels"] as string;
                result.RunCommand = MgaComponent.ComponentParameter["runCommand"] as string;
                result.Success = true;
                result.ZippyServerSideHook = MgaComponent.ComponentParameter["results_zip_py"] as string;
                // FIXME
                result.LogFileDirectory = Path.Combine(MainParameters.ProjectDirectory, "log");
                result.BuildQuery = MgaComponent.ComponentParameter["build_query"] as string;
                this.result = result;
            }
            if (this.result.Success == false)
            {
                throw new InterpreterException(this.Name + " execution failed");
            }
        }
        private bool CallElaborator(
            MgaProject project,
            MgaFCO currentobj,
            MgaFCOs selectedobjs,
            int param,
            bool expand = true)
        {
            bool result = false;
            try
            {
                var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter();
                elaborator.Initialize(project);

                Logger.WriteInfo("Elaborating model...");
                System.Windows.Forms.Application.DoEvents();

                int verbosity = 128;
                result = elaborator.RunInTransaction(project, currentobj, selectedobjs, verbosity);

                if (this.result.Traceability == null)
                {
                    this.result.Traceability = new META.MgaTraceability();
                }

                if (elaborator.Traceability != null)
                {
                    elaborator.Traceability.CopyTo(this.result.Traceability);
                }
                //this.Logger.WriteDebug("Elaboration is done.");
            }
            catch (Exception ex)
            {
                Logger.WriteError(ex.Message);
                return false;
            }

            return true;
        }
        private bool CheckGeneratedModelWithOpenModelica(Modelica.ComponentMap modelicaURIMaps, ModelConfig modelConfig)
        {
            var modelicaSettings = this.mainParameters.config as CyPhy2Modelica_v2Settings;
            var omcExe = MainForm.OMCExe;
            var result = false;
            if (File.Exists(omcExe) == false)
            {
                this.Logger.WriteWarning("OpenModelica installation was not found.");
                this.Logger.WriteWarning("The generate code cannot be checked with OpenModelica.");
                return true;
            }
            else
            {
                this.Logger.WriteDebug("OpenModelica compiler was found: " + omcExe);
            }

            try
            {
                var tb = CyPhyClasses.TestBench.Cast(this.mainParameters.CurrentFCO);
                var externalLibraries = new List<String>();
                externalLibraries = modelConfig.lib_package_names;
                var mslVersion = modelConfig.MSL_version;
                // generate script file for model check
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("// Checking model in OpenModelica");
                sb.AppendLine(string.Format("loadModel(Modelica, {{\"{0}\"}});", mslVersion));
                foreach (var item in externalLibraries)
                {
                    sb.AppendLine(string.Format("loadModel({0});", item));
                }
                sb.AppendLine("loadFile(\"CyPhy/package.mo\");");
                sb.AppendLine(string.Format("checkStr := checkModel({0}.TestBenches.{1});", Modelica.CodeGenerator.MainPackage, tb.Name));
                sb.AppendLine("writeFile(\"CyPhy/checkModelOpenModelica.txt\", checkStr);");
                string checkModelMos = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage, "checkModelOpenModelica.mos");

                File.WriteAllText(checkModelMos, sb.ToString());

                // call mos file to check model
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo()
                {
                    Arguments = string.Format("+q +s \"{0}\"", checkModelMos),
                    FileName = omcExe,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    WorkingDirectory = this.mainParameters.OutputDirectory
                };

                if (p.StartInfo.EnvironmentVariables["OPENMODELICALIBRARY"] != null)
                {
                    p.StartInfo.EnvironmentVariables.Remove("OPENMODELICALIBRARY");
                }

                var modelicaPath = Path.Combine(Environment.GetEnvironmentVariable("OPENMODELICAHOME"), "lib", "omlibrary") + ";" 
                    + Path.GetFullPath(Path.Combine(this.mainParameters.OutputDirectory, "Libraries"));

                p.StartInfo.EnvironmentVariables.Add("OPENMODELICALIBRARY", modelicaPath);

                this.Logger.WriteInfo("Checking model with OpenModelica...");
                this.Logger.WriteDebug("OmcExe : {0}", omcExe);
                this.Logger.WriteDebug("OPENMODELICALIBRARY : {0}", modelicaPath);
                System.Windows.Forms.Application.DoEvents();

                p.Start();
                p.WaitForExit();
                // read generated results back

                string s = File.ReadAllText(Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage, "checkModelOpenModelica.txt"));

                // display it on the GME console
                if (s.Contains("Check of " + Modelica.CodeGenerator.MainPackage + ".TestBenches." + tb.Name + " completed successfully."))
                {
                    // TODO: maybe check for next line  = true?
                    this.Logger.WriteInfo("Successful OpenModelica check.");
                    result = true;
                }
                else
                {
                    result = false;
                    this.Logger.WriteError("Failed OpenModelica check.");
                    s.Split(Environment.NewLine.ToArray())
                        .Where(l => string.IsNullOrWhiteSpace(l) == false).ToList()
                        .ForEach(x => this.Logger.WriteError(TryConvertErrorStringToHyperLink(x, modelicaURIMaps)));
                }

            }
            catch (Exception ex)
            {
                //Trace.TraceError(ex.ToString());
                this.Logger.WriteError(ex.ToString());
                result = false;
            }

            return result;
        }
        private bool CheckGeneratedModelWithDymola(Modelica.ComponentMap modelicaURIMaps)
        {
            var modelicaSettings = this.mainParameters.config as CyPhy2Modelica_v2Settings;
            int secondsToWait = 120;
            var dymolaExe = MainForm.DymolaExe;
            var result = false;
            if (File.Exists(dymolaExe) == false)
            {
                //GMEConsole.Warning.WriteLine("Dymola install was not found.");
                this.Logger.WriteWarning("Dymola install was not found.");
                this.Logger.WriteWarning("The generate code cannot be checked with Dymola.");
                return true;
            }
            else
            {
                this.Logger.WriteDebug("Dymola install was found: " + dymolaExe);
            }

            try
            {
                var tb = CyPhyClasses.TestBench.Cast(this.mainParameters.CurrentFCO);

                // generate script file for model check
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Advanced.TranslationInCommandLog = true");
                sb.AppendLine("openModel(\"CyPhy\\package.mo\")");
                sb.AppendLine("checkModel(\"" + Modelica.CodeGenerator.MainPackage + ".TestBenches." + tb.Name + "\")");
                sb.AppendLine("savelog(\"checkModelDymola.txt\")");
                sb.AppendLine("exit()");
                string checkModelMos = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage, "checkModelDymola.mos");

                File.WriteAllText(checkModelMos, sb.ToString());

                Process p = new Process();
                p.StartInfo = new ProcessStartInfo()
                {
                    Arguments = " /nowindow " + checkModelMos,
                    FileName = dymolaExe,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    WorkingDirectory = this.mainParameters.OutputDirectory
                };

                if (p.StartInfo.EnvironmentVariables["MODELICAPATH"] != null)
                {
                    p.StartInfo.EnvironmentVariables.Remove("MODELICAPATH");
                }

                var modelicaPath = Path.GetFullPath(Path.Combine(this.mainParameters.OutputDirectory, "Libraries"));

                p.StartInfo.EnvironmentVariables.Add("MODELICAPATH", modelicaPath);

                this.Logger.WriteInfo("Checking model with Dymola...");
                this.Logger.WriteDebug("DymolaExe : {0}", dymolaExe);
                this.Logger.WriteDebug("MODELICAPATH : {0}", modelicaPath);
                System.Windows.Forms.Application.DoEvents();

                p.Start();
                if (p.WaitForExit(1000 * secondsToWait) == false)
                {
                    p.Kill();
                    this.Logger.WriteError("Dymola checking process did not exit within {0} seconds - the process was killed.", secondsToWait);
                    this.Logger.WriteError("Do you have a Dymola license? If so please leave a Dymola instance open (it will keep the license checked out).");
                    return result;
                }
                // read generated results back

                string s = File.ReadAllText(Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage, "checkModelDymola.txt"));

                // display it on the GME console
                if (s.Contains("Check of " + Modelica.CodeGenerator.MainPackage + ".TestBenches." + tb.Name + " successful."))
                {
                    // TODO: maybe check for next line  = true?
                    this.Logger.WriteInfo("Successful Dymola check.");
                    result = true;
                }
                else
                {
                    result = false;
                    this.Logger.WriteError("Failed Dymola check.");
                    var startRecording = false;
                    foreach (var line in s.Split(Environment.NewLine.ToArray()).Where(l => string.IsNullOrWhiteSpace(l) == false))
                    {
                        if (startRecording == false)
                        {
                            if (line.Contains("Advanced.TranslationInCommandLog = true"))
                            {
                                startRecording = true;
                            }
                        }
                        else
                        {
                            if (line.Contains("savelog(\"checkModelDymola.txt\")"))
                            {
                                break;
                            }
                            this.Logger.WriteError(TryConvertErrorStringToHyperLink(line, modelicaURIMaps));
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                //Trace.TraceError(ex.ToString());
                this.Logger.WriteError(ex.ToString());
                result = false;
            }

            return result;
        }
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            var result = new InterpreterResult();
            this.parameters = parameters;
            result.Success = this.RunInTransaction(parameters.CurrentFCO.Project, parameters.CurrentFCO, parameters.SelectedFCOs, 128, parameters.OutputDirectory);
            result.RunCommand = "cmd.exe /c \"\"";

            return result;
        }