如何通过TIA Portal Openness API获取功能块(FB)的接口变量?
获取TIA Portal Openness API中FB的接口变量
核心处理逻辑
- 先将已找到的
PlcBlock实例转换为PlcFunctionBlock类型(仅FB/FC这类带接口的块具备接口变量集合) - 通过
PlcFunctionBlock.Interface属性访问块接口,再分别读取Inputs、Outputs、InOuts变量集合
修改后的代码示例
if (_apiWrapper.PlcSoftwares[0].BlockGroup.Blocks.Find(_apiWrapper.ProjectTreeLeaf.Name) != null) { _apiWrapper.ProjectSelectedPlcBlock = _apiWrapper.PlcSoftwares[0].BlockGroup.Blocks.Find(_apiWrapper.ProjectTreeLeaf.Name); Console.WriteLine($"TREE VIEW: SELECTED BLOCK = {_apiWrapper.ProjectSelectedPlcBlock.Name}"); // 将通用PlcBlock转换为带接口的PlcFunctionBlock if (_apiWrapper.ProjectSelectedPlcBlock is PlcFunctionBlock targetFunctionBlock) { PlcInterface blockInterface = targetFunctionBlock.Interface; // 遍历输出输入变量 Console.WriteLine("\n=== Input Variables ==="); foreach (PlcVariable inputVar in blockInterface.Inputs) { Console.WriteLine($"Name: {inputVar.Name}, Type: {inputVar.DataType.Name}, Comment: {inputVar.Comment}"); } // 遍历输出变量 Console.WriteLine("\n=== Output Variables ==="); foreach (PlcVariable outputVar in blockInterface.Outputs) { Console.WriteLine($"Name: {outputVar.Name}, Type: {outputVar.DataType.Name}, Comment: {outputVar.Comment}"); } // 遍历输入输出变量 Console.WriteLine("\n=== InOut Variables ==="); foreach (PlcVariable inOutVar in blockInterface.InOuts) { Console.WriteLine($"Name: {inOutVar.Name}, Type: {inOutVar.DataType.Name}, Comment: {inOutVar.Comment}"); } } else { Console.WriteLine("选中的块不是功能块(FB)或函数(FC),无接口变量"); } }
关键说明
- 类型转换必要性:只有
PlcFunctionBlock类型的块包含Interface属性,DB、OB等其他块无法转换,因此需添加类型判断避免报错。 - 变量属性获取:
PlcVariable类包含接口变量的核心属性,除示例中的名称、数据类型、注释外,还可按需访问Address(地址)、Retain(保持性)等属性。 - 健壮性优化:若需处理复杂场景,可添加try-catch块捕获权限不足、属性不存在等异常。
内容的提问来源于stack exchange,提问作者starkar
相关产品推荐
相关产品推荐

