如何以编程方式将 twincat 3 项目部署到 PLC

How to deploy twincat 3 project to PLC programmatically

我正在寻找一种通过 C# 激活配置和更新启动项目的方法。 我的 Twincat 3 项目已编译,所有必需的文件都在 /_Boot 文件夹中。 下一步是在我的 PLC 上加载和执行项目的 C# 程序(实际上是单元测试)。

到目前为止,我已经通读了 Beckhoff 信息系统,但找不到任何提示。

您需要 Twincat 自动化接口 API 才能激活您的配置并启动 PLC。

来自官方文档的例子:

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using EnvDTE100;
        using System.IO;
        using TCatSysManagerLib;

        namespace ActivatePreviousConfiguration{

            class Program
            {

                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();
                }
            }
        }

还有 许多 你可以用这个 api 做的其他事情,例如为你的 PLC 生成代码..

您可以在此处找到文档:

Automation Interface pdf

如果您只有 _Boot 文件夹可供使用,您只需将 _Boot\TwinCAT RT(x64)\Plc 的内容复制到您的目标引导文件夹 C:\TwinCAT.1\Boot\Plc 并通过 ADS-Command.

启动 PLC

PLC 将使用替换后的编译项目启动。

这里是官方ADS-Documentation启动plc的例子:

static void Main(string[] args)
{
    //Create a new instance of class TcAdsClient
    TcAdsClient tcClient = new TcAdsClient();

    try
    {
        // Connect to local PLC - Runtime 1 - TwinCAT2 Port=801, TwinCAT3 Port=851
        tcClient.Connect(851);

        Console.WriteLine(" PLC Run\t[R]");
        Console.WriteLine(" PLC Stop\t[S]");
        Console.WriteLine("\r\nPlease choose \"Run\" or \"Stop\" and confirm with enter..");
        string sInput = Console.ReadLine().ToLower();

        //Process user input and apply chosen state
        do{
            switch (sInput)
            {
                case "r": tcClient.WriteControl(new StateInfo(AdsState.Run, tcClient.ReadState().DeviceState)); break;
                case "s": tcClient.WriteControl(new StateInfo(AdsState.Stop, tcClient.ReadState().DeviceState)); break;
                default: Console.WriteLine("Please choose \"Run\" or \"Stop\" and confirm with enter.."); sInput = Console.ReadLine().ToLower(); break;
            }
        } while (sInput != "r" && sInput != "s");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        Console.ReadKey();
    }
    finally
    {
        tcClient.Dispose();
    }
}