private void AddToExistingComponent(CyPhy.ComponentType cyPhyComponentType, Modelica.ExportedComponent flatExportedComponentInfo)
        {
            string cName = flatExportedComponentInfo.ExportedComponentClass.Split('.').LastOrDefault();
            this.numModelicaModels = cyPhyComponentType.Children.ModelicaModelCollection.Count();
            CyPhy.ModelicaModel newModelicaModel = null;

            if (cyPhyComponentType is CyPhy.TestComponent)
            {
                newModelicaModel = CyPhyClasses.ModelicaModel.Create(cyPhyComponentType as CyPhy.TestComponent);
            }
            else if (cyPhyComponentType is CyPhy.Component)
            {
                newModelicaModel = CyPhyClasses.ModelicaModel.Create(cyPhyComponentType as CyPhy.Component);
            }
            else
            {
                return;
            }

            this.numModelicaModels++;

            newModelicaModel.Name = cName.ToLower();
            newModelicaModel.Attributes.Class = flatExportedComponentInfo.ExportedComponentClass;
            newModelicaModel.Preferences.PortLabelLength = 0;

            foreach (MgaPart item in (newModelicaModel.Impl as MgaFCO).Parts)
            {
                item.SetGmeAttrs(
                    null, 
                    MODELICA_MODEL_START_X, 
                    this.numModelicaModels * MODELICA_MODEL_ADJUST_Y);
            } 

            Modelica.Component modelicaComponentInfo = flatExportedComponentInfo.Components.FirstOrDefault(c =>
                c.FullName == flatExportedComponentInfo.ExportedComponentClass);

            this.m_Logger.WriteDebug("Adding {0} to {1}", newModelicaModel.Name, cyPhyComponentType.Name);
            AddComponentParts_Flat(cyPhyComponentType, newModelicaModel, modelicaComponentInfo);
        }
        private void AddComponentParts_Flat(
            CyPhy.ComponentType cyphyComponent,
            CyPhy.ModelicaModel modelicaModel,
            Modelica.Component modelicaComponentInfo)
        {
            this.m_Logger.WriteDebug("Adding properties/parameters for {0}", modelicaModel.Name);
            AddParameters_Flat(cyphyComponent, modelicaModel, modelicaComponentInfo.Parameters);

            this.m_Logger.WriteDebug("Adding connectors for {0}", modelicaModel.Name);
            AddConnectors_Flat(cyphyComponent, modelicaModel, modelicaComponentInfo);
        }
        private Modelica.Component ExtractExtendsInfo(
            Modelica.Component flatComponent, 
            List<Modelica.Component> componentList, 
            string componentClass)
        {
            Modelica.Component thisComponent = componentList.FirstOrDefault(x=>x.FullName == componentClass);

            var parameterDict = thisComponent.Parameters.ToDictionary(p => p.Name);
            foreach (Modelica.Parameter parameter in flatComponent.Parameters)
            {
                #region Try to get base class parameter info, and save a 'default' value
                Modelica.Parameter extendedClassParameterInfo = null;

                if (parameterDict.TryGetValue(parameter.Name, out extendedClassParameterInfo))
                {
                    parameter.DefaultValue = extendedClassParameterInfo.Value;
                }
                #endregion

                parameterDict[parameter.Name] = parameter;
            }
            flatComponent.Parameters = parameterDict.Values.ToList();

            var connectorDict = thisComponent.Connectors.ToDictionary(p => p.Name);
            foreach (Modelica.Connector connector in flatComponent.Connectors)
            {
                connectorDict[connector.Name] = connector;
            }
            flatComponent.Connectors = connectorDict.Values.ToList();

            var packageDict = thisComponent.Packages.ToDictionary(p => p.Name);
            foreach (Modelica.Package package in flatComponent.Packages)
            {
                #region Try to get base class package info, and save a 'default' value
                Modelica.Package extendedClassPackageInfo = null;

                if (packageDict.TryGetValue(package.Name, out extendedClassPackageInfo))
                {
                    package.DefaultValue = extendedClassPackageInfo.Value;
                }
                #endregion

                packageDict[package.Name] = package;
            }
            flatComponent.Packages = packageDict.Values.ToList();

            foreach (Modelica.Extend extend in thisComponent.Extends)
            {
                parameterDict = extend.Parameters.ToDictionary(p => p.Name);
                foreach (Modelica.Parameter parameter in flatComponent.Parameters)
                {
                    #region Try to get base class parameter info, and save a 'default' value
                    Modelica.Parameter extendedClassParameterInfo = null;

                    if (parameterDict.TryGetValue(parameter.Name, out extendedClassParameterInfo))
                    {
                        parameter.DefaultValue = extendedClassParameterInfo.Value;
                    }
                    #endregion

                    parameterDict[parameter.Name] = parameter;
                }
                flatComponent.Parameters = parameterDict.Values.ToList();

                ExtractExtendsInfo(flatComponent, componentList, extend.FullName);
            }

            return flatComponent;
        }
        private void MakeNewTestComponent(CyPhy.TestComponents tcFolder, Modelica.ExportedComponent flatExportedComponentInfo)
        {
            var newCyPhyTestComponent = CyPhyClasses.TestComponent.Create(tcFolder);
            string cName = flatExportedComponentInfo.ExportedComponentClass.Split('.').LastOrDefault();
            newCyPhyTestComponent.Name = cName;

            var newModelicaModel = CyPhyClasses.ModelicaModel.Create(newCyPhyTestComponent);
            newModelicaModel.Name = cName.ToLower();
            newModelicaModel.Attributes.Class = flatExportedComponentInfo.ExportedComponentClass;
            newModelicaModel.Preferences.PortLabelLength = 0;

            foreach (MgaPart item in (newModelicaModel.Impl as MgaFCO).Parts)
            {
                item.SetGmeAttrs(
                    null,
                    MODELICA_MODEL_START_X,
                    MODELICA_MODEL_ADJUST_Y);
            }

            Modelica.Component modelicaComponentInfo = flatExportedComponentInfo.Components.FirstOrDefault(c =>
                c.FullName == flatExportedComponentInfo.ExportedComponentClass);

            this.m_Logger.WriteDebug("Creating {0} and {1}.", newCyPhyTestComponent.Name, newModelicaModel.Name);
            AddComponentParts_Flat(newCyPhyTestComponent, newModelicaModel, modelicaComponentInfo);
        }
        private Modelica.ExportedComponent FlattenExportedComponent(Modelica.ExportedComponent componentInfo)
        {
            Modelica.Component flatComponent = new Modelica.Component();
            Modelica.ExportedComponent flatComponentInfo = new Modelica.ExportedComponent();

            string componentClass = componentInfo.ExportedComponentClass;
            flatComponent.FullName = componentClass;
            flatComponentInfo.ExportedComponentClass = componentClass;

            flatComponent = ExtractExtendsInfo(flatComponent, componentInfo.Components, componentClass);

            flatComponentInfo.Components.Add(flatComponent);

            return flatComponentInfo;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Recursively goes through the component assembly "tree" and appends component assemblies and packages to one string.
        /// </summary>
        /// <param name="ca_mo">Root component-assembly.</param>
        /// <param name="sb">Text will be appended to sb.</param>
        /// <param name="extendModelicaIconPackage">Bool indicating if the MSL is >= 3.2.</param>
        /// <param name="environments">These will be generated in all component-assemblies.</param>
        private void GetComponentAssemblyPackageFile(Modelica.ComponentAssembly ca_mo, StringBuilder sb, bool extendModelicaIconPackage, SortedSet<Modelica.Environment> environments)
        {
            ca_mo.Environments = environments;
            if (ca_mo.HasInnerCAs)
            {
                sb.AppendLine(string.Format("package {0}", ca_mo.Name));
                if (extendModelicaIconPackage)
                {
                    sb.AppendLine("extends Modelica.Icons.Package;");
                }
            }

            sb.Append(ca_mo.ToString());

            foreach (var inner_ca_mo in ca_mo.ComponentAssemblyInstances.Select(c => c.InstanceOf))
            {
                this.GetComponentAssemblyPackageFile(inner_ca_mo, sb, extendModelicaIconPackage, environments);
            }

            if (ca_mo.HasInnerCAs)
            {
                sb.AppendLine(string.Format("end {0};", ca_mo.Name));
            }
        }
        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;
        }
        private string TryConvertErrorStringToHyperLink(string errorMsg, Modelica.ComponentMap modelicaURIMaps)
        {
            // Assumption, only checks each line for one mapping!

            var result = errorMsg.Replace("__CyPhy__", "");
            var match = "";
            foreach (var kvp in modelicaURIMaps.ModelMapping)
            {
                if (errorMsg.Contains(kvp.Key) && kvp.Key.Length > match.Length)
                {
                    // Make sure the longest ModelicaURI is used.
                    match = kvp.Key;
                }
            }

            if (string.IsNullOrWhiteSpace(match) == false)
            {
                var cInfo = modelicaURIMaps.ModelMapping[match];
                var mgaComponent = this.mainParameters.Project.GetFCOByID(cInfo.ID);
                if (mgaComponent != null)
                {
                    return errorMsg.Replace(match, GmeConsoleHelper.ToMgaHyperLink(mgaComponent, this.result.Traceability));
                }
                else
                {
                    this.Logger.WriteWarning("Could not obtain {0} from IDMap using {1}", match, cInfo.Path);
                }
            }
            else
            {
                foreach (var kvp in modelicaURIMaps.InstanceMapping)
                {
                    if (errorMsg.Contains(kvp.Key) && kvp.Key.Length > match.Length)
                    {
                        // Make sure the longest ModelicaURI is used.
                        match = kvp.Key;
                    }
                }

                if (string.IsNullOrWhiteSpace(match) == false)
                {
                    var cInfo = modelicaURIMaps.InstanceMapping[match];
                    var mgaComponent = this.mainParameters.Project.GetFCOByID(cInfo.ID);
                    if (mgaComponent != null)
                    {
                        return errorMsg.Replace(match, GmeConsoleHelper.ToMgaHyperLink(mgaComponent, this.result.Traceability));
                    }
                    else
                    {
                        this.Logger.WriteWarning("Could not obtain {0} from IDMap using {1}", match, cInfo.Path);
                    }
                }
            }

            return result;
        }