【问题标题】:Reading OPC UA Node attribute values with C# client使用 C# 客户端读取 OPC UA 节点属性值
【发布时间】:2022-01-12 14:10:35
【问题描述】:

我有一个简单的 C# OPC UA 客户端与 OPC UA 服务器通信。服务器使用 Modbus 数据模型。我实际上是使用 NuGet 的 Opc.UA.Fx 包。

我可以连接,并从我尝试读取的节点获取属性。但是,我无法弄清楚如何读取数组的元素。我只是想阅读布尔数组的元素。当我访问节点值时,它返回“System.Boolean[]”

  1. 我搜索了 OPC 10000-8 Pat 8: Data Access Manual,但我不太清楚如何访问节点的元素。
  2. 我研究了许多源示例,但它们都非常臃肿和神秘。
  3. 我尝试了 OPC.Ua.Fx 文献中的示例,但无法通过类型转换。
  4. 我可以通过使用UAExpert 进行监控来验证我的服务器是否正常工作。

这是读取线圈节点(离散IO)的简单客户端:

static void Main(string[] args)
{
  StringBuilder localEndpoint = new StringBuilder();
  var rawIpAddress = "127.0.0.1";
  localEndpoint.Append(epPrefix + rawIpAddress + epSuffix);

  // HmiClient is a class that constructs the OpcClient and Connects.
  var robot = new HmiClient(localEndpoint.ToString()); 

  // Create a list and store Attribute info
  List<string> coilNodeAttributes = new List<string>();    
  coilNodeAttributes = GetAttributeInfo(robot.hmiClient, NodeDef.Coils);

  foreach (var el in coilNodeAttributes)
  {
    Console.WriteLine(el);
  }
  Console.WriteLine("==================================\n");

  // Trying to determing the data type for reading the array elements.
  OpcValue discreteInputs = robot.hmiClient.ReadNode(1,302,OpcAttribute.Value);

  Type inputType = discreteInputs.GetType();      

  Console.WriteLine("ReadNode Value Relflection: {0}", inputType.ToString());  

  Console.Read();
}

下面是UAExpert 连接到服务器和我的C# 客户端连接的屏幕截图。

再次,我不明白为什么我根本无法访问布尔 [ ] 的元素。我显然在努力将值转换为正确的 C# 类型。

【问题讨论】:

  • HmiClient 是自定义类?通常您使用Session.ReadValues(IList&lt;NodeId&gt; nodes, types, out values, out results) 来读取值。 NodeId 有几个构造函数重载(包括一个 int(用于您的 302))
  • 是的,它只是一个简单的类来连接服务器。让我用您建议的方法进行调查和试验。
  • 你可能可以读到像new NodeId("Coils[1]")这样的值

标签: c# opc-ua opc


【解决方案1】:

为了回答我自己的问题,我的 OpcValue 作为 Object 返回,需要转换为您正在处理的类型。我的转换语法不正确。

正确:

  OpcValue discreteInputs = robot.Client.ReadNode(1, 302, OpcAttribute.Value);

  bool[] discreteInputValues = (bool[])discreteInputs.Value;

显然,现在我可以遍历数组来显示元素。

【讨论】:

    猜你喜欢
    • 2020-07-24
    • 2017-05-04
    • 2015-08-03
    • 2020-08-28
    • 2022-12-19
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多