private ITcSmTreeItem createItf(ItfInfo itfInfo, ITcSmTreeItem parent, IWorker worker, XmlDocument doc)
        {
            XmlNode itfNode = doc.SelectSingleNode("TcPlcObject/Itf");
            string  itfName = itfNode.Attributes["Name"].Value;

            worker.ProgressStatus = string.Format("Creating Interface '{0}' ...", itfName);

            ITcSmTreeItem item = null;
            XmlElement    node = (XmlElement)doc.SelectSingleNode("TcPlcObject/Itf/Declaration");

            string declString = node.InnerText;

            if (!TryLookupChild(parent, itfName, out item))
            {
                item = parent.CreateChild(itfName, TreeItemType.PlcInterface.AsInt32(), "", declString);
            }

            //Debug.Fail("");
            ITcXmlDocument xmlDoc = (ITcXmlDocument)item;

            xmlDoc.DocumentXml = doc.OuterXml;
            ITcPlcDeclaration decl = (ITcPlcDeclaration)item;

            //decl.DeclarationText = node.InnerText;
            return(item);
        }
        private ITcSmTreeItem createPlcFolder(ITcSmTreeItem parent, string folderName, string before, IWorker worker)
        {
            worker.ProgressStatus = string.Format("Creating Folder '{0}' ...", folderName);
            ITcSmTreeItem item = parent.CreateChild(folderName, TreeItemType.PlcFolder.AsInt32(), before, null);

            return(item);
        }
        private void createFBCalls(string[] boxName)
        {
            //acuire project instance of MAIN Pou
            //then tell TwinCAT to create 3 new Actions for MAIN
            ITcSmTreeItem mainPOU    = sysMan.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^POUs^MAIN");
            ITcSmTreeItem fbBlockAct = mainPOU.CreateChild("A_Block", 608, "");
            ITcSmTreeItem fbInitAct  = mainPOU.CreateChild("A_Init", 608, "");

            ITcPlcPou pouMain = (ITcPlcPou)mainPOU;


            ITcPlcImplementation actBlock = (ITcPlcImplementation)fbBlockAct;
            ITcPlcImplementation actInit  = (ITcPlcImplementation)fbInitAct;

            ITcPlcImplementation pouMainImpl = (ITcPlcImplementation)pouMain;

            ITcPlcDeclaration pouMainDecl = (ITcPlcDeclaration)pouMain;

            generateMainDecl(ref pouMainDecl, ref boxName);
            generateMainImpl(ref pouMainImpl);
            generateBlockAct(ref actBlock, ref boxName);
            generateInitAct(ref actInit, ref boxName);
        }
        //<Not used>
        public void addBaseSln(String slnBasePath)                                            //For adding collab code automatically - requires better gitbash
        {
            string        template = slnBasePath + @"\tc_project_app\tc_project_app.plcproj"; //path toproject template
            ITcSmTreeItem plc      = SystemManager.LookupTreeItem("TIPC");

            try
            {
                ITcSmTreeItem newProject = plc.CreateChild("basePLC", 0, "", template);
            }
            catch
            {
                MessageBox.Show("Nope"); //Change the template so it detects version installed and knows where to look
            }
        }
        public SolutionHandler(string filePath, string FileName)
        {
            this.BASEFOLDER    = filePath;
            this._solutionName = _tcProjectName = FileName;
            this.adsClient     = new TcAdsClient();
            MessageFilter.Register();

            /* -----------------------------------------------------------------
             * Creates new solution based off of TwinCAT's XAE and PLC templates.
             * -----------------------------------------------------------------*/
            if (dte == null)
            {
                CreateNewProject();
            }

            pro    = sol.Projects.Item(1);
            sysMan = (ITcSysManager11)pro.Object;

            //System.Threading.Thread.Sleep(5000);
            ITcSmTreeItem plc = sysMan.LookupTreeItem("TIPC");

            plc.CreateChild("Untitled1", 0, "", "Standard PLC Template");
            //---Navigate to References node and cast to Library Manager interface
            ITcSmTreeItem        references     = sysMan.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^References");
            ITcPlcLibraryManager libraryManager = (ITcPlcLibraryManager)this.RetrieveLibMan();

            /* ------------------------------------------------------
             * Check to see if library already exists, if it does it will delete before adding to avoid any exceptions.
             * ------------------------------------------------------ */

            foreach (ITcPlcLibRef libraryReference in libraryManager.References)
            {
                if (libraryReference is ITcPlcLibrary)
                {
                    ITcPlcLibrary library = (ITcPlcLibrary)libraryReference;
                    if (library.Name == "MDR_Control")
                    {
                        DeleteLibrary(ref libraryManager);
                    }
                }
            }

            /* ------------------------------------------------------
             * Add our MDR library to the project References.
             * ------------------------------------------------------ */
            AddLibrary(ref libraryManager);

            MessageFilter.Revoke();
        }//Constructor()
        private ITcSmTreeItem CreateBox(ITcSmTreeItem parent, BoxInfo boxInfo, IWorker worker)
        {
            worker.ProgressStatus = string.Format("Creating Box '{0}' ({1})...", boxInfo.Name, boxInfo.Type);
            ITcSmTreeItem ret = parent.CreateChild(boxInfo.Name, (int)BoxType.EtherCAT_EXXXXX, "", boxInfo.Type);

            if (boxInfo.ChildBoxes != null)
            {
                foreach (BoxInfo child in boxInfo.ChildBoxes)
                {
                    ITcSmTreeItem tcChild = CreateBox(ret, child, worker);
                }
            }

            return(ret);
        }
        protected void CreateMotion(IWorker worker)
        {
            if (worker.CancellationPending)
            {
                throw new Exception("Execution cancelled!");
            }

            OrderScriptContext context           = (OrderScriptContext)_context;
            ConfigurationInfo  configurationInfo = context.Order.ConfigurationInfo;

            ITcSmTreeItem ncConfig = systemManager.LookupTreeItem("TINC");

            foreach (TaskInfo taskInfo in configurationInfo.MotionTasks)
            {
                ITcSmTreeItem task = null;

                worker.ProgressStatus = string.Format("Creating Motion Task '{0}'", taskInfo.Name);

                if (!TryLookupChild(ncConfig, taskInfo.Name, out task))
                {
                    task = ncConfig.CreateChild(taskInfo.Name, 1);
                }
                ITcSmTreeItem axes = null;
                TryLookupChild(task, "Axes", out axes);

                if (axes == null)
                {
                    TryLookupChild(task, "Achsen", out axes);
                }

                foreach (AxisInfo axisInfo in taskInfo.Axes)
                {
                    if (worker.CancellationPending)
                    {
                        throw new Exception("Execution cancelled!");
                    }

                    ITcSmTreeItem axis = null;
                    worker.ProgressStatus = string.Format("Creating Axis '{0}'", axisInfo.Name);

                    if (!TryLookupChild(axes, axisInfo.Name, out axis))
                    {
                        axis = axes.CreateChild(axisInfo.Name, 1);
                        ConsumeTemplate(axis, axisInfo.TemplatePath);
                    }
                }
            }
        }
        private ITcSmTreeItem createPou(POUInfo pouInfo, ITcSmTreeItem parent, IWorker worker, XmlDocument doc)
        {
            XmlNode pouNode = doc.SelectSingleNode("TcPlcObject/POU");
            string  pouName = pouNode.Attributes["Name"].Value;

            worker.ProgressStatus = string.Format("Creating POU '{0}' ...", pouName);

            ITcSmTreeItem item = null;

            if (!TryLookupChild(parent, pouName, out item))
            {
                item = parent.CreateChild(pouName, TreeItemType.PlcPouFunctionBlock.AsInt32(), "", null);
            }
            // some items need to be casted to a more special interface to gain access to all of their methods and properties, for example POUs which need
            // to be casted to the interface ITcPlcPou to get access to their unique methods and properties.
            ITcPlcPou pou = (ITcPlcPou)item;

            pou.DocumentXml = doc.OuterXml;   // get/set PLC code of a POU in XML Format
            return(item);
        }
        }//LinkIoToPlc()

        private void createDriveStruct()
        {
            //create strings for the beginning and end of the struct declaration
            string structStart = "TYPE ST_EP7402:" + Environment.NewLine + "STRUCT" + Environment.NewLine;
            string structEnd   = "END_STRUCT" + Environment.NewLine + "END_TYPE" + Environment.NewLine;

            //create the DUT and assign it to a container
            ITcSmTreeItem     DUT         = sysMan.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^DUTs");
            ITcSmTreeItem     driveStruct = DUT.CreateChild("ST_EP7402", 606, "");
            ITcPlcDeclaration structDecl  = (ITcPlcDeclaration)driveStruct;

            string sdeclarationText;

            //create a string for generating the member declaration of the struct.
            string structMembers = @"stInputs   AT %I*  :   EP7402_Inputs;" + Environment.NewLine +
                                   "stOutputs   AT %Q*  :   EP7402_Outputs;" + Environment.NewLine;

            //combine the string into a single string to create the declaration text
            sdeclarationText           = structStart + structMembers + structEnd;
            structDecl.DeclarationText = sdeclarationText;
        }
        private ITcSmTreeItem createDut(DataTypeInfo info, ITcSmTreeItem parent, IWorker worker, XmlDocument doc)
        {
            XmlNode dutNode  = doc.SelectSingleNode("TcPlcObject/DUT");
            string  typeName = dutNode.Attributes["Name"].Value;

            worker.ProgressStatus = string.Format("Creating Type '{0}' ...", typeName);

            XmlNode declNode    = dutNode.SelectSingleNode("Declaration");
            string  declaration = string.Empty;

            declaration = declNode.InnerText;

            ITcSmTreeItem dataTypeItem = parent.CreateChild(typeName, TreeItemType.PlcDutStruct.AsInt32(), "", declaration);

            ITcPlcDeclaration decl  = (ITcPlcDeclaration)dataTypeItem;
            ITcXmlDocument    tcDoc = (ITcXmlDocument)dataTypeItem;

            string xml = tcDoc.DocumentXml;

            return(dataTypeItem);
        }
        private ITcSmTreeItem createGvl(GvlInfo gvlInfo, ITcSmTreeItem parent, IWorker worker, XmlDocument doc)
        {
            XmlNode gvlNode = doc.SelectSingleNode("TcPlcObject/GVL");
            string  gvlName = gvlNode.Attributes["Name"].Value;

            worker.ProgressStatus = string.Format("Creating GlobalVariable Sheet '{0}' ...", gvlName);

            ITcSmTreeItem item = null;

            if (!TryLookupChild(parent, gvlName, out item))
            {
                item = parent.CreateChild(gvlName, TreeItemType.PlcGvl.AsInt32());
            }

            ITcXmlDocument    xmlDoc = (ITcXmlDocument)item;
            ITcPlcDeclaration decl   = (ITcPlcDeclaration)item;

            XmlElement node = (XmlElement)doc.SelectSingleNode("TcPlcObject/GVL/Declaration");

            decl.DeclarationText = node.InnerText;
            return(item);
        }
Esempio n. 12
0
        private void CreateModuleCode()
        {
            String eventManagerName;

            //-----------------------------------------------------------------------------------------------------------------------
            //---------------------------------Create module In-Out Structs  --------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------

            moduleConditionsToFire = dut.CreateChild(
                module.getName + "conditionsToFire",
                606,
                "",
                Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintModuleOutStruct,
                    new string[] { "@moduleName@" },
                    new string[] { module.getName }
                    )
                );

            //Structure that defines the Event-Triggers that will be used as inputs in the Eventmanager
            moduleEventTriggers = dut.CreateChild(
                module.getName + "EventTriggers",
                606,
                "",
                Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintModuleInStruct,
                    new string[] { "@moduleName@" },
                    new string[] { module.getName }
                    )
                );


            //-----------------------------------------------------------------------------------------------------------------------
            //--------------------------------- Fill the  ModulesGVL ----------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------

            modulesGvlImplementation = "\t" + module.getName + ": " + module.getName + ";" + "\n";
            decl  = (ITcPlcDeclaration)modules;
            index = decl.DeclarationText.IndexOf(keyVarGlobal);
            decl.DeclarationText =
                decl.DeclarationText.Insert(
                    index + (keyVarGlobal.Length + 1),
                    modulesGvlImplementation
                    );

            //-----------------------------------------------------------------------------------------------------------------------
            //------------------------------------------------Create the FB_TargetModule---------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------

            //604   TREEITEMTYPE_PLCPOUFB   POU Function Block
            ITcSmTreeItem targetModule = pou.CreateChild(module.getName, 604, "1");

            //-----------------------------------------------------------------------------------------------------------------------
            //--------------------------- Create the FB_TargetModule Methods --------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------
            moduleEventManagerDeclaration = null;
            eventNamesLists.Clear();

            foreach (EventManager eventManager in module.content)
            {
                eventNamesLists.Add(eventManager.content.eventNames);
                eventManagerNames.Add(eventManager.getName);
                moduleEventManagerDeclaration += Assigner.ReplaceBlueprintValues(
                    "\t" + AssignedConfigFileData.blueprintModuleEventManagerDeclaration + "\n",
                    new string[] { "@eventManagerName@" },
                    new string[] { eventManager.getName }
                    );

                moduleEventManagerImplementation += Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintModuleEventManagerImplementation + "\n",
                    new string[] { "@eventManagerName@" },
                    new string[] { eventManager.getName }
                    );
            }

            foreach (String[] eventNamesGroup in eventNamesLists)
            {
                eventManagerName = eventManagerNames.First();
                eventManagerNames.RemoveAt(0);

                foreach (String eventName in eventNamesGroup)
                {
                    //Create EventMethods
                    currentMethod = targetModule.CreateChild(eventName + "Event", 609, "", methodDescription);

                    decl = (ITcPlcDeclaration)currentMethod;
                    decl.DeclarationText = Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintEventMethodDeclaration,
                        new string[] { "@eventName@" },
                        new string[] { eventName }
                        );

                    //Create SenderMethods
                    currentMethod = targetModule.CreateChild("fire" + Functions.UppercaseFirst(eventName) + "Event", 609, "", methodDescription);

                    decl = (ITcPlcDeclaration)currentMethod;

                    decl.DeclarationText = Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintSenderMethodDeclaration,
                        new string[] { "@eventName@" },
                        new string[] { eventName }
                        );

                    impl = (ITcPlcImplementation)currentMethod;
                    impl.ImplementationText = Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintSenderMethodImplementation,
                        new string[] { "@eventName@", "@eventManagerName@" },
                        new string[] { eventName, eventManagerName }
                        );

                    outConditionsToFire += "\t" + eventName + "Event : BOOL;\n";

                    eventRaiserImplementation += Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintEventRaiserImplementation + "\n",
                        new string[] { "@eventName@" },
                        new string[] { eventName }
                        );

                    moduleTriggerEventDeclaration += Assigner.ReplaceBlueprintValues(
                        "\t" + AssignedConfigFileData.blueprintModuleTriggerEventsDeclaration + "\n",
                        new string[] { "@eventName@" },
                        new string[] { Functions.UppercaseFirst(eventName) }
                        );
                }
            }

            //Fill the module structures with the relevant data
            //--------------------------------------------------------------------------------
            decl = (ITcPlcDeclaration)moduleEventTriggers;

            index = decl.DeclarationText.IndexOf(keyVarStruct);
            decl.DeclarationText = decl.DeclarationText.Insert(
                index + (keyVarStruct.Length + 1),
                moduleTriggerEventDeclaration
                );

            decl = (ITcPlcDeclaration)moduleConditionsToFire;

            index = decl.DeclarationText.IndexOf(keyVarStruct);
            decl.DeclarationText = decl.DeclarationText.Insert(
                index + (keyVarStruct.Length + 1),
                outConditionsToFire
                );
            //--------------------------------------------------------------------------------

            //eventRaiser method
            currentMethod = targetModule.CreateChild("eventRaiser", 609, "", methodDescription);


            decl = (ITcPlcDeclaration)currentMethod;
            decl.DeclarationText = AssignedConfigFileData.blueprintEventRaiserDeclaration;

            impl = (ITcPlcImplementation)currentMethod;
            impl.ImplementationText = eventRaiserImplementation;

            //callComponents method
            currentMethod = targetModule.CreateChild("callComponents", 609, "", methodDescription);


            decl = (ITcPlcDeclaration)currentMethod;
            decl.DeclarationText = AssignedConfigFileData.blueprintCallComponentsDeclaration;

            //registerSequence method
            currentMethod = targetModule.CreateChild("registerSequence", 609, "", methodDescription);


            decl = (ITcPlcDeclaration)currentMethod;
            decl.DeclarationText = AssignedConfigFileData.blueprintRegisterSequenceDeclarationText;

            impl = (ITcPlcImplementation)currentMethod;
            impl.ImplementationText = AssignedConfigFileData.blueprintRegisterSequenceImplementationText;

            //runSequence method
            currentMethod = targetModule.CreateChild("runSequence", 609, "", methodDescription);


            decl = (ITcPlcDeclaration)currentMethod;
            decl.DeclarationText = AssignedConfigFileData.blueprintRunSequenceDeclarationText;

            impl = (ITcPlcImplementation)currentMethod;
            impl.ImplementationText = AssignedConfigFileData.blueprintRunSequenceImplementationText;

            /*
             * currentMethod = targetModule.CreateChild("eventRaiser", 609, "", methodDescription);
             *
             * //M_EventRaiser
             * decl = (ITcPlcDeclaration)currentMethod;
             * decl.DeclarationText = AssignedConfigFileData.blueprintEventRaiserDeclaration;
             *
             * impl = (ITcPlcImplementation)currentMethod;
             * impl.ImplementationText = eventRaiserImplementation;
             *
             * currentMethod = targetModule.CreateChild("callComponents", 609, "", methodDescription);
             *
             * //M_CallComponents
             * decl = (ITcPlcDeclaration)currentMethod;
             * decl.DeclarationText = AssignedConfigFileData.blueprintCallComponentsDeclaration;
             */
            //-----------------------------------------------------------------------------------------------------------------------
            //-------------------------- Fill the declaration and implementation part of FB_TargetModule with code-------------------
            //-----------------------------------------------------------------------------------------------------------------------

            decl = (ITcPlcDeclaration)targetModule;
            impl = (ITcPlcImplementation)targetModule;

            decl.DeclarationText = Assigner.ReplaceBlueprintValues(
                AssignedConfigFileData.modulesDeclarations[targetIndex],
                new string[] { "@eventManagers", "@moduleName@" },
                new string[] { moduleEventManagerDeclaration, module.getName }
                );

            impl.ImplementationText = Assigner.ReplaceBlueprintValues(
                AssignedConfigFileData.modulesImplementations[targetIndex],
                new string[] { "@eventManagers" },
                new string[] { moduleEventManagerImplementation }
                );
        }
Esempio n. 13
0
        private void CreateEventManagerCode()
        {
            //-----------------------------------------------------------------------------------------------------------------------
            //------------------------------------------------Create the FB_EventManager---------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------
            foreach (EventManager eventManager in module.content)
            {
                ITcSmTreeItem fbEventManager = eventManagers.CreateChild(eventManager.getName + "EventManager", 604, "1");

                String[] eventNameGroup = eventManager.content.eventNames;

                outEventManagerEvents         = null;
                eventManagerEventsStrings     = null;
                eventDispatcherImplementation = null;
                handlerOperations             = null;
                enumEventDeclaration          = null;
                triggersImplementation        = null;
                foreach (String eventName in eventNameGroup)
                {
                    outEventManagerEvents += "\t" + eventName + "Event : BOOL;\n";

                    if (eventNameGroup.Last() == eventName)
                    {
                        eventManagerEventsStrings += "\t\t'" + eventName + "Event'\n";
                    }
                    else
                    {
                        eventManagerEventsStrings += "\t\t'" + eventName + "Event',\n";
                    }


                    eventDispatcherImplementation += Assigner.ReplaceBlueprintValues(
                        "\n" + AssignedConfigFileData.blueprintEventDispatcherImplementation,
                        new string[] { "@eventManagerName@", "@eventName@" },
                        new string[] { eventManager.getName, eventName }
                        );

                    handlerOperations += Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintHandlerOperation + "\n",
                        new string[] { "@eventManagerName@", "@eventName@", "@moduleName@" },
                        new string[] { eventManager.getName, eventName, module.getName }
                        );

                    enumEventDeclaration += "\t" + eventName + "Event,\n";

                    triggersImplementation += "\t" + eventName + "RTrigger : R_TRIG;" + "\n";
                    //-----------------------------------------------------------------------------------------------------------------------
                    //--------------------------- Create the FB_EventManager eventReceivers -------------------------------------------------
                    //-----------------------------------------------------------------------------------------------------------------------

                    //Implement receivers
                    currentReceiver = fbEventManager.CreateChild(eventName + "Receiver", 611, "", propertyDescription);

                    decl = (ITcPlcDeclaration)currentReceiver;
                    decl.DeclarationText = Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintReceiversDeclaration,
                        new string[] { "@eventName@" },
                        new string[] { eventName }
                        );

                    //Implement getters
                    currentReceiver = currentReceiver.CreateChild("", 613, "", "1");

                    impl = (ITcPlcImplementation)currentReceiver;
                    impl.ImplementationText = Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintReceiversGetterImplementation,
                        new string[] { "@eventManagerName@", "@eventName@" },
                        new string[] { eventManager.getName, eventName }
                        );
                }

                //-----------------------------------------------------------------------------------------------------------------------
                //-------------------------- Create the  E_<X>Event Enumaration ---------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------

                //605   TREEITEMTYPE_PLCDUTENUM     DUT enum data type
                dut.CreateChild(
                    eventManager.getName + "Event",
                    605, "",
                    Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintEnumEventDeclaration,
                        new string[] { "@eventManagerName@", "@eventNames" },
                        new string[] { eventManager.getName, enumEventDeclaration }
                        )
                    );

                //-----------------------------------------------------------------------------------------------------------------------
                //-------------------------- Create the  EventManager-Structures ----------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------

                dut.CreateChild(
                    eventManager.getName + "EventRecord",
                    606,
                    "",
                    Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintEventRecordDeclaration,
                        new string[] { "@eventManagerName@" },
                        new string[] { eventManager.getName }
                        )
                    );

                //Structure that defines the Event-Triggers that will be used as inputs in the Eventmanager
                eventManagerEventTriggers = dut.CreateChild(
                    eventManager.getName + "EventTriggers",
                    606,
                    "",
                    Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintEventManagerInStruct,
                        new string[] { "@eventManagerName@" },
                        new string[] { eventManager.getName }
                        )
                    );

                decl = (ITcPlcDeclaration)eventManagerEventTriggers;

                index = decl.DeclarationText.IndexOf(keyVarStruct);
                decl.DeclarationText = decl.DeclarationText.Insert(
                    index + (keyVarStruct.Length + 1),
                    triggersImplementation
                    );

                eventManagerEventReceivers = dut.CreateChild(
                    eventManager.getName + "EventReceiver",
                    606,
                    "",
                    Assigner.ReplaceBlueprintValues(
                        AssignedConfigFileData.blueprintEventManagerOutStruct,
                        new string[] { "@eventManagerName@" },
                        new string[] { eventManager.getName }
                        )
                    );

                decl  = (ITcPlcDeclaration)eventManagerEventReceivers;
                index = decl.DeclarationText.IndexOf(keyVarStruct);
                decl.DeclarationText = decl.DeclarationText.Insert(
                    index + (keyVarStruct.Length + 1),
                    outEventManagerEvents
                    );
                //-----------------------------------------------------------------------------------------------------------------------
                //-------------------------- Fill the declaration and implementation part of FB_EventManager with code-------------------
                //-----------------------------------------------------------------------------------------------------------------------
                decl = (ITcPlcDeclaration)fbEventManager;
                impl = (ITcPlcImplementation)fbEventManager;

                decl.DeclarationText = Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintEventManagerDeclaration,
                    new string[] { "@eventManagerName@", "@eventStrings", "@moduleName@" },
                    new string[] { eventManager.getName, eventManagerEventsStrings, module.getName }
                    );


                impl.ImplementationText = AssignedConfigFileData.blueprintEventManagerImplementation;

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------- Create the FB_EventManager Methods --------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------

                //M_CheckForRaceCondition
                currentMethod = fbEventManager.CreateChild("checkForRaceCondition", 609, "", methodDescription);

                decl = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = AssignedConfigFileData.blueprintRaceConditionDeclaration;

                impl = (ITcPlcImplementation)currentMethod;
                impl.ImplementationText = Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintRaceConditionImplementation,
                    new string[] { "@eventManagerName@" },
                    new string[] { eventManager.getName }
                    );

                //M_EventDispatcher
                currentMethod = fbEventManager.CreateChild("eventDispatcher", 609, "", methodDescription);

                decl = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = AssignedConfigFileData.blueprintEventDispatcherDeclaration;

                impl = (ITcPlcImplementation)currentMethod;
                impl.ImplementationText = eventDispatcherImplementation;

                //M_ExecuteHandler
                currentMethod = fbEventManager.CreateChild("executeHandler", 609, "", methodDescription);

                decl = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = AssignedConfigFileData.blueprintExecuteHandlerDeclaration;

                impl = (ITcPlcImplementation)currentMethod;
                impl.ImplementationText = Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintExecuteHandlerImplementation,
                    new string[] { "@handlerOperations" },
                    new string[] { handlerOperations }
                    );

                //M_UpdateEventHistory
                currentMethod = fbEventManager.CreateChild("updateEventHistory", 609, "", methodDescription);

                decl = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = AssignedConfigFileData.blueprintUpdateEventHistoryDeclaration;


                impl = (ITcPlcImplementation)currentMethod;

                impl.ImplementationText = AssignedConfigFileData.blueprintUpdateEventHistoryImplementation;

                //M_UpdateEventRecord
                currentMethod = fbEventManager.CreateChild("updateEventRecord", 609, "", methodDescription);

                decl = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = AssignedConfigFileData.blueprintUpdateEventRecordDeclaration;

                impl = (ITcPlcImplementation)currentMethod;
                impl.ImplementationText = Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintUpdateEventRecordImplementation,
                    new string[] { "@unequal" },
                    new string[] { "<>" }
                    );
                //FB_Init
                currentMethod        = fbEventManager.CreateChild("FB_init", 609, "", methodDescription);
                decl                 = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintEventManagerFBInitDeclarationText,
                    new string[] { "@moduleName@" },
                    new string[] { module.getName }
                    );
                impl = (ITcPlcImplementation)currentMethod;
                impl.ImplementationText = Assigner.ReplaceBlueprintValues(
                    AssignedConfigFileData.blueprintEventManagerFBInitImplementationText,
                    new string[] { "@moduleName@" },
                    new string[] { module.getName }
                    );
                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------- Create the FB_EventManager disable signal -------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                disableSignal =
                    fbEventManager.
                    CreateChild("disableEventManagerSignal", 611, "", propertyDescription);

                decl = (ITcPlcDeclaration)disableSignal;
                decl.DeclarationText = AssignedConfigFileData.blueprintDisableEventManagerSignalDeclaration;

                //Implement getter
                currentSignal           = disableSignal.CreateChild("", 613, "", "1");
                impl                    = (ITcPlcImplementation)currentSignal;
                impl.ImplementationText = AssignedConfigFileData.blueprintDisableEventManagerSignalGetterImplementation;

                //Implement setter
                currentSignal           = disableSignal.CreateChild("", 614, "", "1");
                impl                    = (ITcPlcImplementation)currentSignal;
                impl.ImplementationText = AssignedConfigFileData.blueprintDisableEventManagerSignalSetterImplementation;

                Console.WriteLine("Code for " + eventManager.getName + "EventManager" + " created.");
            }
        }
Esempio n. 14
0
        public void ScanDevicesAndBoxes(DataTable dt)
        {
            int config;

            if ((config = checkForRunMode()) == 1)
            {
                ITcSmTreeItem ioDevicesItem = sysMan.LookupTreeItem("TIID"); // Get The IO Devices Node

                // Scan Devices (Be sure that the target system is in Config mode!)
                string scannedXml = ioDevicesItem.ProduceXml(false); // Produce Xml implicitly starts the ScanDevices on this node.

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(scannedXml); // Loads the Xml data into an XML Document
                XmlNodeList          xmlDeviceList = xmlDoc.SelectNodes("TreeItem/DeviceGrpDef/FoundDevices/Device");
                List <ITcSmTreeItem> devices       = new List <ITcSmTreeItem>();

                //local variables for our spreadsheet writing statements
                int deviceCount = 0;

                int i = 2;

                // Add all found devices to configuration
                foreach (XmlNode node in xmlDeviceList)
                {
                    // Add a selection or subrange of devices
                    int     itemSubType = int.Parse(node.SelectSingleNode("ItemSubType").InnerText);
                    string  typeName    = node.SelectSingleNode("ItemSubTypeName").InnerText;
                    XmlNode xmlAddress  = node.SelectSingleNode("AddressInfo");

                    ITcSmTreeItem device = ioDevicesItem.CreateChild(string.Format("Device_{0}", ++deviceCount), itemSubType, string.Empty, null);

                    string xml = string.Format("<TreeItem><DeviceDef>{0}</DeviceDef></TreeItem>", xmlAddress.OuterXml);
                    device.ConsumeXml(xml); // Consume Xml Parameters (here the Address of the Device)
                    devices.Add(device);
                }


                // Scan all added devices for attached boxes
                foreach (ITcSmTreeItem device in devices)
                {
                    string xml = "<TreeItem><DeviceDef><ScanBoxes>1</ScanBoxes></DeviceDef></TreeItem>"; // Using the "ScanBoxes XML-Method"
                    try
                    {
                        device.ConsumeXml(xml); // Consume starts the ScanBoxes and inserts every found box/terminal into the configuration
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Warning: {0}", ex.Message);
                    }
                    int j = 0;
                    foreach (ITcSmTreeItem Box in device)
                    {
                        if (Box.ItemSubTypeName.Contains("EP7402-0057"))
                        {
                            Box.Name = dt.Rows[j].ItemArray[0].ToString() + j.ToString();
                            this.EditParams(Box, dt.Rows[j].ItemArray[2].ToString());
                            j++;
                            LinkIoToPlc(Box);
                        }
                    } //for each Box
                }     //end of foreach loops
            }
        }             //ScanDevicesandBoxes()
Esempio n. 15
0
        public void PLCdeclarations(DataTable dt)
        {
            string mainVar        = @"VAR_GLOBAL" + Environment.NewLine;
            string endMain        = Environment.NewLine + @"          
END_VAR";
            string constDeclStart = @"VAR_GLOBAL CONSTANT" + Environment.NewLine;
            string constDeclEnd   = Environment.NewLine + @"          
END_VAR";

            createDriveStruct();
            System.Threading.Thread.Sleep(3000);
            //Add function blocks to MAIN declaration
            ITcSmTreeItem main      = sysMan.LookupTreeItem("TIPC^Untitled1^Untitled1 Project^GVLs");
            ITcSmTreeItem GVL       = main.CreateChild("MDR_Control_FBs", 615, "", 0);
            ITcSmTreeItem StructGVL = main.CreateChild("EP7402_List", 615, "", 0);
            //Cast to specific interface for declaration and implementation area
            ITcPlcDeclaration mainDecl   = (ITcPlcDeclaration)GVL;
            ITcPlcDeclaration structDecl = (ITcPlcDeclaration)StructGVL;



            //Get current declaration and implementation area content
            string strMainDecl   = mainDecl.DeclarationText;
            string strStructDecl = structDecl.DeclarationText;

            //string strMainImpl = mainImpl.ImplementationText;
            _nDriveCount = dt.Rows.Count;
            string[] boxName = new string[_nDriveCount];
            int      j       = 0;
            int      i       = 0;

            string structCount = string.Format(" nDriveCount : UINT := {0};", _nDriveCount);

            for (i = 0; i < _nDriveCount - 1; i++)
            {
                boxName[i] = dt.Rows[j].ItemArray[0].ToString() + j.ToString();
                //Console.WriteLine(boxName[i]);
                j++;
            }


            declarations             = string.Join(": FB_MDR_Control;" + Environment.NewLine, boxName);
            mainDecl.DeclarationText = mainVar + declarations + endMain;

            for (i = 0; i < _nDriveCount - 1; i++)
            {
                boxName[i] = boxName[i].Insert(0, "st");
            }


            declarations = string.Join(": ST_EP7402;" + Environment.NewLine, boxName);
            structDecl.DeclarationText = mainVar + declarations + endMain + Environment.NewLine + constDeclStart + structCount + constDeclEnd;
            createFBCalls(boxName);

            System.Threading.Thread.Sleep(2000);
            var settings = dte.GetObject("TcAutomationSettings");

            settings.SilentMode = true;
            dte.Solution.SolutionBuild.Build(true); // compile the plc project
            settings.SilentMode = false;
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            //-----------------------------------------------------------------------------------------------------------------------
            //                                          Retrieve all relevant data from config file
            //-----------------------------------------------------------------------------------------------------------------------

            ConfigFileReader configFileReader = new ConfigFileReader();
            Assigner         assigner         = new Assigner();

            MessageFilter.Register();

            //-----------------------------------------------------------------------------------------------------------------------
            //                                          Attach to existing Dte
            //-----------------------------------------------------------------------------------------------------------------------



            AssignedConfigFileData.pathToSolution = Assigner.ReplaceBlueprintValues(
                AssignedConfigFileData.pathToSolution,
                new string[] { "@NameOfProject@" },
                new string[] { AssignedConfigFileData.nameOfProject }
                );

            Console.WriteLine("pathToSolution: {0}", AssignedConfigFileData.pathToSolution);

            AssignedConfigFileData.pathToPOUsFolder = Assigner.ReplaceBlueprintValues(
                AssignedConfigFileData.pathToPOUsFolder,
                new string[] { "@NameOfPLCProject@" },
                new string[] { AssignedConfigFileData.nameOfPlcProject }
                );

            Console.WriteLine("pathToPOUsFolder: {0}", AssignedConfigFileData.pathToPOUsFolder);

            AssignedConfigFileData.pathToDUTsFolder = Assigner.ReplaceBlueprintValues(
                AssignedConfigFileData.pathToDUTsFolder,
                new string[] { "@NameOfPLCProject@" },
                new string[] { AssignedConfigFileData.nameOfPlcProject }
                );

            Console.WriteLine("pathToDUTsFolder: {0}", AssignedConfigFileData.pathToDUTsFolder);

            AssignedConfigFileData.pathToGVLsFolder = Assigner.ReplaceBlueprintValues(
                AssignedConfigFileData.pathToGVLsFolder,
                new string[] { "@NameOfPLCProject@" },
                new string[] { AssignedConfigFileData.nameOfPlcProject }
                );

            Console.WriteLine("pathToGVLsFolder: {0}", AssignedConfigFileData.pathToGVLsFolder);

            AssignedConfigFileData.pathToMAIN = Assigner.ReplaceBlueprintValues(
                AssignedConfigFileData.pathToMAIN,
                new string[] { "@NameOfPLCProject@" },
                new string[] { AssignedConfigFileData.nameOfPlcProject }
                );

            Console.WriteLine("pathToMAIN: {0}", AssignedConfigFileData.pathToMAIN);

            List <Project> projectList  = new List <Project>();
            Project        plcProj      = null;
            bool           projectFound = false;

            ITcPlcDeclaration    decl = (ITcPlcDeclaration)null;
            ITcPlcImplementation impl = (ITcPlcImplementation)null;

            ITcSmTreeItem currentMethod = null;
            ITcSmTreeItem pou           = null;
            ITcSmTreeItem dut           = null;
            ITcSmTreeItem gvl           = null;
            ITcSmTreeItem main          = null;
            ITcSmTreeItem modules       = null;
            ITcSmTreeItem constants     = null;
            ITcSmTreeItem system        = null;
            ITcSmTreeItem targetModule  = null;
            ITcSmTreeItem triggers      = null;
            ITcSmTreeItem eventManagers = null;
            ITcSmTreeItem interfaces    = null;
            ITcSmTreeItem i_sequence    = null;

            ITcSysManager sysManager = null;

            EnvDTE.DTE dte =
                DteAttacher.attachToExistingDte(
                    AssignedConfigFileData.pathToSolution,
                    AssignedConfigFileData.visualStudioVersion,
                    AssignedConfigFileData.nameOfProject

                    );

            dynamic solution = dte.Solution;

            Console.WriteLine("Full solution name:");
            Console.WriteLine(solution.FullName);

            Projects prjs = solution.projects;

            Console.WriteLine("Projects in solution: {0}", prjs.Count);
            for (int i = 1; i <= prjs.Count; i++)
            {
                projectList.Add(prjs.Item(i));
                Console.WriteLine("Project found: {0}", prjs.Item(i).Name);
                Console.WriteLine("Searching for project: {0}", AssignedConfigFileData.nameOfProject);
                if (prjs.Item(i).Name.Equals(AssignedConfigFileData.nameOfProject))
                {
                    plcProj      = prjs.Item(i);
                    projectFound = true;
                }
            }

            //-----------------------------------------------------------------------------------------------------------------------
            //                                          Perform checks
            //-----------------------------------------------------------------------------------------------------------------------

            Console.WriteLine("Performing checks:");

            if (projectFound)
            {
                Console.WriteLine("Project found.");
                sysManager = plcProj.Object;
            }
            else
            {
                Console.WriteLine("Project not found. Exiting on Enter.");
                Console.Read();
                return;
            }

            //Is POUs item available?
            Functions.SearchForItem(AssignedConfigFileData.pathToPOUsFolder, ref sysManager, ref pou);

            //Is DUTs item available?
            Functions.SearchForItem(AssignedConfigFileData.pathToDUTsFolder, ref sysManager, ref dut);

            //Is GVLs item available?
            Functions.SearchForItem(AssignedConfigFileData.pathToGVLsFolder, ref sysManager, ref gvl);

            //Is Main item available?
            Functions.SearchForItem(AssignedConfigFileData.pathToMAIN, ref sysManager, ref main);

            if (AssignedConfigFileData.activity.Equals("SpecificEventsModuleCreator"))
            {
                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- MAIN implementation -----------------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                impl = (ITcPlcImplementation)main;
                impl.ImplementationText = AssignedConfigFileData.blueprintMainImplementation;

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create methods for MAIN -------------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                currentMethod        = main.CreateChild("systemTime", 609, "");
                decl                 = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = AssignedConfigFileData.blueprintMainSystemTimeDeclaration;

                impl = (ITcPlcImplementation)currentMethod;
                impl.ImplementationText = AssignedConfigFileData.blueprintMainSystemTimeImplementation;

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create the  ModulesGVL --------------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                modules = gvl.CreateChild("Modules", 615, "", AssignedConfigFileData.blueprintModulesGvlDeclaration);

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create the  ConstantsGVL ------------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                constants = gvl.CreateChild("Constants", 615, "", AssignedConfigFileData.blueprintConstantsGvlDeclaration);

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create the SystemGVL ----------------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                system = gvl.CreateChild("System", 615, "", AssignedConfigFileData.blueprintSystemGvlDeclaration);

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create the EventManagers folder -----------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                eventManagers = pou.CreateChild("EventManagers", 601, "", "1");

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create the Interfaces folder --------------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                interfaces = pou.CreateChild("Interfaces", 601, "", "1");

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create the I_Sequence interface -----------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                i_sequence = interfaces.CreateChild("I_Sequence", 618);

                //-----------------------------------------------------------------------------------------------------------------------
                //--------------------------------- Create the sequence interface method ------------------------------------------------
                //-----------------------------------------------------------------------------------------------------------------------
                currentMethod        = i_sequence.CreateChild("sequence", 610);
                decl                 = (ITcPlcDeclaration)currentMethod;
                decl.DeclarationText = AssignedConfigFileData.blueprintInterfaceSequenceMethodDeclaration;
            }
            else
            {
                //Is the Module GVL present?
                Functions.SearchForSubItem("Modules", ref gvl, ref modules);

                //Is the Triggers GVL present?
                //Functions.SearchForSubItem("Triggers", ref gvl, ref triggers);

                //Is the Eventmanagers folder present?
                Functions.SearchForSubItem("EventManagers", ref pou, ref eventManagers);
            }

            //Is TargetModule present?

            /*
             * if (AssignedConfigFileData.activity.Equals("InjectNewEventManagerInTarget"))
             * {
             *  Functions.SearchForItem(AssignedConfigFileData.pathToTargetModule, ref sysManager, ref targetModule);
             * }
             */
            //Is the Interfaces folder present?
            //Functions.SearchForSubItem("Interfaces", ref pou, ref interfaces);

            //-----------------------------------------------------------------------------------------------------------------------
            //                                          Start activity
            //-----------------------------------------------------------------------------------------------------------------------

            Console.WriteLine("Executing program.");

            for (int i = 0; i < AssignedConfigFileData.modulesContainer.content.Length; i++)
            {
                if (AssignedConfigFileData.activity.Equals("GeneralEventsModuleCreator"))
                {
                    new GeneralEventsModuleCreator(i, pou, dut, gvl, eventManagers, modules, triggers);
                }
                else if (AssignedConfigFileData.activity.Equals("SpecificEventsModuleCreator"))
                {
                    new SpecificEventsModuleCreator(i, pou, dut, gvl, eventManagers, modules, triggers);
                }
            }
            MessageFilter.Revoke();
            Console.WriteLine("Finished!");
            Console.Read();
        }
        /// <summary>
        ///  Durch die Hauptschnittstelle ITcSysManager können wir ein neue PLCProjekt generieren. Die Lookup-Methode ist implementiert.
        /// </summary>

        protected ITcSmTreeItem CreatePlcProject(IWorker worker)
        {
            if (worker.CancellationPending)
            {
                throw new Exception("Execution cancelled!");
            }

            OrderScriptContext context           = (OrderScriptContext)_context;
            ConfigurationInfo  configurationInfo = context.Order.ConfigurationInfo;

            string        plcProjectName = configurationInfo.PlcProjectName;
            ITcSmTreeItem plcConfig      = systemManager.LookupTreeItem("TIPC"); //Navigation im PLC struktur im TC.

            worker.ProgressStatus = string.Format("Creating empty PLC Project '{0}' ...", plcProjectName);
            ITcSmTreeItem plcProjectRoot = plcConfig.CreateChild(plcProjectName, 0, "", vsXaePlcEmptyTemplateName); //diese Method ausführen, um ein neues PLCProjekt erstellen.

            ITcPlcProject plcProjectRootIec = (ITcPlcProject)plcProjectRoot;                                        //setting the properties of the PLC Project like boot option.

            plcProjectRootIec.BootProjectAutostart = true;
            plcProjectRootIec.GenerateBootProject(true);

            ITcSmTreeItem plcProject = plcProjectRoot.LookupChild(plcProjectName + " Project"); // for example Schulung and Schulung Project. Now the ITcTreeItem pointer is pointing Schulung Project

            foreach (PlcObjectInfo plcObjectInfo in context.Order.ConfigurationInfo.PlcObjects) //Creating all the components of the PLC Project
            {
                if (worker.CancellationPending)
                {
                    throw new Exception("Execution cancelled!");
                }

                switch (plcObjectInfo.Type)  // we can have library, placeholder, POU, ITf, GVL and so on...
                {
                case PlcObjectType.DataType: // PlcObjectType defined in ScriptInfo.
                    createWorksheet((WorksheetInfo)plcObjectInfo, plcProject, worker);
                    break;

                case PlcObjectType.Library:
                    createLibrary((LibraryInfo)plcObjectInfo, plcProject, worker);
                    break;

                case PlcObjectType.Placeholder:
                    createPlaceholder((PlaceholderInfo)plcObjectInfo, plcProject, worker);
                    break;

                case PlcObjectType.POU:      // first create folder and then create POU
                    createWorksheet((WorksheetInfo)plcObjectInfo, plcProject, worker);
                    break;

                case PlcObjectType.Itf:
                    createWorksheet((WorksheetInfo)plcObjectInfo, plcProject, worker);
                    break;

                case PlcObjectType.Gvl:
                    createWorksheet((WorksheetInfo)plcObjectInfo, plcProject, worker);
                    break;

                default:
                    Debug.Fail("");
                    break;
                }
            }

            ITcSmTreeItem realtimeTasks = systemManager.LookupTreeItem("TIRT");     //creating tasks
            ITcSmTreeItem rtTask        = realtimeTasks.CreateChild("PlcTask", TreeItemType.Task.AsInt32());

            ITcSmTreeItem taskRef = null;

            worker.ProgressStatus = "Linking PLC instance with task 'PlcTask' ...";

            if (!TryLookupChild(plcProject, "PlcTask", out taskRef))
            {
                if (worker.CancellationPending)
                {
                    throw new Exception("Execution cancelled!");
                }

                taskRef = plcProject.CreateChild("PlcTask", TreeItemType.PlcTask.AsInt32(), "", "MAIN");
            }

            //foreach (ITcSmTreeItem prog in taskRef)
            //{
            //    string name = prog.Name;
            //}

            //ErrorItems errors;

            //if (worker.CancellationPending)
            //    throw new Exception("Execution cancelled!");

            //bool ok = CompileProject(worker, out errors);

            //if (!ok)
            //    throw new ApplicationException(string.Format("Plc Project compile produced '{0}' errors.  Please see Visual Studio Error Window for details.!", plcProject.Name));

            return(plcProject);
        }