private static void SetupTask(ITcSysManager sysManager, IReadOnlyCollection <ITcSmTreeItem> autds) { var tasks = sysManager.LookupTreeItem("TIRT"); var task1 = tasks.CreateChild("Task 1", 0, null); var doc = new XmlDocument(); var xml = task1.ProduceXml(false); doc.LoadXml(xml); doc.SelectSingleNode("TreeItem/TaskDef/CycleTime").InnerText = _cycleTicks == "manual" ? _taskCycleTime : (TaskCycleTimeBase * int.Parse(_cycleTicks)).ToString(); task1.ConsumeXml(doc.OuterXml); var task1Out = sysManager.LookupTreeItem("TIRT^Task 1^Outputs"); // make global header for (var i = 0; i < HeadSize; i++) { var name = $"header[{i}]"; task1Out.CreateChild(name, -1, null, "WORD"); } // make gain body for (var id = 0; id < autds.Count; id++) { for (var i = 0; i < BodySize; i++) { var name = $"gbody[{id}][{i}]"; task1Out.CreateChild(name, -1, null, "WORD"); } } var task1In = sysManager.LookupTreeItem("TIRT^Task 1^Inputs"); for (var id = 0; id < autds.Count; id++) { var name = $"input[{id}]"; task1In.CreateChild(name, -1, null, "WORD"); } // connect links for (var id = 0; id < autds.Count; id++) { for (var i = 0; i < HeadSize; i++) { var source = $"TIRT^Task 1^Outputs^header[{i}]"; var destination = $"TIID^EtherCAT Master^Box {id + 1} (AUTD)^RxPdo1^data[{i}]"; sysManager.LinkVariables(source, destination); } for (var i = 0; i < BodySize; i++) { var source = $"TIRT^Task 1^Outputs^gbody[{id}][{i}]"; var destination = $"TIID^EtherCAT Master^Box {id + 1} (AUTD)^RxPdo0^data[{i}]"; sysManager.LinkVariables(source, destination); } { var source = $"TIRT^Task 1^Inputs^input[{id}]"; var destination = $"TIID^EtherCAT Master^Box {id + 1} (AUTD)^TxPdo^dummy"; sysManager.LinkVariables(source, destination); } } }
public static bool SearchForItem(string itemPath, ref ITcSysManager sysManager, ref ITcSmTreeItem item) { try { item = sysManager.LookupTreeItem(itemPath); Console.WriteLine(itemPath + " item found."); } catch (Exception e) { Console.WriteLine(itemPath + " item not found. Exiting on Enter."); Console.Read(); Environment.Exit(-1); } return(true); }
private static void AddRoute(ITcSysManager sysManager, IPAddress ipAddr) { var routeConfiguration = sysManager.LookupTreeItem("TIRR"); var addProjectRouteIp = @"<TreeItem> <RoutePrj> <AddProjectRoute> <Name>" + ipAddr + @"</Name> <NetId>" + ipAddr + @".1.1" + @"</NetId> <IpAddr>" + ipAddr + @"</IpAddr> </AddProjectRoute> </RoutePrj> </TreeItem>"; routeConfiguration.ConsumeXml(addProjectRouteIp); }
static void Main(string[] args) { Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0"); EnvDTE.DTE dte = (EnvDTE.DTE)System.Activator.CreateInstance(t); dte.SuppressUI = false; dte.MainWindow.Visible = true; EnvDTE.Solution sol = dte.Solution; sol.Open(@"C:\Temp\SolutionFolder\MySolution1\MySolution1.sln"); EnvDTE.Project pro = sol.Projects.Item(1); ITcSysManager sysMan = pro.Object; sysMan.ActivateConfiguration(); sysMan.StartRestartTwinCAT(); }
public static void AssignCpuCores(ITcSysManager sysManager) { var realtimeSettings = sysManager.LookupTreeItem("TIRS"); var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter)) { writer.WriteStartElement("TreeItem"); writer.WriteStartElement("RTimeSetDef"); writer.WriteElementString("MaxCPUs", "1"); writer.WriteStartElement("CPUs"); WriteCpuProperties(writer, 0); writer.WriteEndElement(); // CPUs writer.WriteEndElement(); // RTimeSetDef writer.WriteEndElement(); // TreeItem } var xml = stringWriter.ToString(); realtimeSettings.ConsumeXml(xml); }
private void OnSolutionOpened(object sender = null, OpenSolutionEventArgs e = null) { _isTwinCATProject = false; _systemManager = null; ThreadHelper.ThrowIfNotOnUIThread(); var dte = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; if (dte != null) { _DTE = dte; // Get all projects in active solution _projects = _DTE.Solution.Projects .Cast <EnvDTE.Project>() .ToList(); // Find TwinCAT Project and save the systemmanager foreach (var project in _projects) { try { ITcSysManager sysMan = (ITcSysManager)project.Object; if (sysMan != null) { _systemManager = (ITcSysManager10)sysMan; _isTwinCATProject = true; break; } } catch { } } } }
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(); }
//Activate Actual Configuration public static void ActivateActualConfiguration(IConfigurationRoot configuration, ITcSysManager systemManager, bool debugMode) { systemManager.ActivateConfiguration(); systemManager.StartRestartTwinCAT(); }
private static void Main() { LoadSettings(); var solutionPath = Path.Combine( Environment.GetEnvironmentVariable("temp") ?? string.Empty, SolutionName); MessageFilter.Register(); try { // Parse Commandline Options var alwaysYes = false; var commandLineArgs = Environment.GetCommandLineArgs(); foreach (var cmd in commandLineArgs) { if (cmd == "-y") { alwaysYes = true; } } // Close all TwinCAT Autd Server solutions currently opened var processes = System.Diagnostics.Process.GetProcesses().Where(x => x.MainWindowTitle.StartsWith(SolutionName) && x.ProcessName.Contains("devenv")); foreach (var process in processes) { GetDte(process.Id)?.Quit(); } // Wait for input Console.WriteLine("Please Enter the IP Address of your Client to allow connection: [127.0.0.1]"); var ipaddrStr = "127.0.0.1"; if (!alwaysYes) { ipaddrStr = Console.ReadLine(); } IPAddress.TryParse(ipaddrStr ?? string.Empty, out var ipAddr); Console.WriteLine("Connecting to TcXaeShell DTE..."); var t = Type.GetTypeFromProgID("TcXaeShell.DTE.15.0"); var dte = (DTE2)Activator.CreateInstance(t); dte.SuppressUI = false; dte.MainWindow.Visible = true; dte.UserControl = true; Console.WriteLine("Switching TwinCAT3 to Config Mode..."); SetConfigMode(); System.Threading.Thread.Sleep(1000); Console.WriteLine("Creating a Project..."); var project = CreateProject(dte, solutionPath); ITcSysManager sysManager = project.Object; if (ipAddr != null) { Console.WriteLine("Setting up the Routing Table to " + ipAddr); AddRoute(sysManager, ipAddr); } Console.WriteLine("Scanning Devices..."); var autds = ScanAutDs(sysManager); AssignCpuCores(sysManager); SetupTask(sysManager, autds); Console.WriteLine("Activating and Restarting TwinCAT3..."); sysManager.ActivateConfiguration(); sysManager.StartRestartTwinCAT(); Console.WriteLine("Saving the Project..."); SaveProject(dte, project, solutionPath); Console.WriteLine("Done. Do you want to close the TwinCAT config window? [Yes]/No"); var closeWindow = "Yes"; if (!alwaysYes) { closeWindow = Console.ReadLine(); } if (closeWindow != "No") { dte.Quit(); } } catch (Exception e) { Console.WriteLine("Error. Press any key to exit. Check your license of TwinCAT3."); Console.WriteLine(e.Message); Console.ReadLine(); } MessageFilter.Revoke(); }
private static List <ITcSmTreeItem> ScanAutDs(ITcSysManager sysManager) { var devices = (ITcSmTreeItem3)sysManager.LookupTreeItem("TIID"); var doc = new XmlDocument(); var xml = devices.ProduceXml(false); doc.LoadXml(xml); var nodes = doc.SelectNodes("TreeItem/DeviceGrpDef/FoundDevices/Device"); var ethernetNodes = (from XmlNode node in nodes let typeNode = node.SelectSingleNode("ItemSubType") let subType = int.Parse(typeNode.InnerText) where subType == (int)DeviceType.EtherCAT_AutomationProtocol || subType == (int)DeviceType.EtherCAT_DirectMode || subType == (int)DeviceType.EtherCAT_DirectModeV210 select node).ToList(); if (ethernetNodes.Count == 0) { throw new Exception("No devices were found. Check if TwinCAT3 is in Config Mode"); } Console.WriteLine("Scan found a RT-compatible Ethernet device."); var device = (ITcSmTreeItem3)devices.CreateChild("EtherCAT Master", (int)DeviceType.EtherCAT_DirectMode, null); // Taking only the first found Ethernet Adapter var ethernetNode = ethernetNodes[0]; var addressInfoNode = ethernetNode.SelectSingleNode("AddressInfo"); addressInfoNode.SelectSingleNode("Pnp/DeviceDesc").InnerText = "TwincatEthernetDevice"; // Set the Address Info var xml2 = $"<TreeItem><DeviceDef>{addressInfoNode.OuterXml}</DeviceDef></TreeItem>"; device.ConsumeXml(xml2); const string scanXml = "<TreeItem><DeviceDef><ScanBoxes>1</ScanBoxes></DeviceDef></TreeItem>"; device.ConsumeXml(scanXml); var autds = new List <ITcSmTreeItem>(); foreach (ITcSmTreeItem box in device) { if (box.ItemSubTypeName != "AUTD") { continue; } var bdoc = new XmlDocument(); var bxml = box.ProduceXml(false); bdoc.LoadXml(bxml); // set DC var dcOpmodes = bdoc.SelectNodes("TreeItem/EtherCAT/Slave/DC/OpMode"); foreach (XmlNode item in dcOpmodes) { if (item.SelectSingleNode("Name")?.InnerText == "DC") { var attr = bdoc.CreateAttribute("Selected"); attr.Value = "true"; item.Attributes?.SetNamedItem(attr); item.SelectSingleNode("CycleTimeSync0").InnerText = _cycleTicks == "manual" ? _sync0CycleTime : (Sync0CycleTimeBase * int.Parse(_cycleTicks)).ToString(); attr = bdoc.CreateAttribute("Factor"); attr.Value = "0"; item.Attributes?.SetNamedItem(attr); item.SelectSingleNode("CycleTimeSync0").Attributes?.SetNamedItem(attr); } else { item.Attributes?.RemoveAll(); } } box.ConsumeXml(bdoc.OuterXml); autds.Add(box); } Console.WriteLine($"{autds.Count} AUTDs are found and added."); return(autds); }