«

使用 OPC UA 检测和转换自定义方法输入参数

磁力搜索 • 1 天前 • 3 次点击 • 资讯分享


使用 opc ua 检测和转换自定义方法输入参数

本文将深入探讨如何在使用 OPC UA 客户端(例如 asyncua)调用自定义方法时,解决动态检测和转换输入参数数据类型的问题。核心在于理解如何利用 OPC UA 协议提供的元数据信息,动态地获取方法参数的类型,并将其转换为客户端可用的 Python 类,从而实现灵活且类型安全的方法调用。

在 OPC UA 中,方法节点的 "0:InputArguments" 属性包含了方法参数的详细信息,包括参数名称、数据类型等。通过读取这个属性的值,我们可以获得一个 Argument 对象的列表,每个对象描述一个输入参数。

以下代码展示了如何从 Argument 对象中提取数据类型,并将其转换为相应的 Python 类:

from asyncua.ua import ObjectIds
from asyncua import ua

base_type_list = {
    ua.NodeId(ObjectIds.Null): None,
    ua.NodeId(ObjectIds.Boolean): bool,
    ua.NodeId(ObjectIds.SByte): ua.SByte,
    ua.NodeId(ObjectIds.Byte): ua.Byte,
    ua.NodeId(ObjectIds.Int16): ua.Int16,
    ua.NodeId(ObjectIds.UInt16): ua.UInt16,
    ua.NodeId(ObjectIds.Int32): ua.Int32,
    ua.NodeId(ObjectIds.UInt32): ua.UInt32,
    ua.NodeId(ObjectIds.Int64): ua.Int64,
    ua.NodeId(ObjectIds.UInt64): ua.UInt64,
    ua.NodeId(ObjectIds.Float): ua.Float,
    ua.NodeId(ObjectIds.Double): ua.Double,
    ua.NodeId(ObjectIds.String): ua.String,
    ua.NodeId(ObjectIds.DateTime): ua.DateTime,
    ua.NodeId(ObjectIds.Guid): ua.Guid,
    ua.NodeId(ObjectIds.ByteString): ua.ByteString,
    ua.NodeId(ObjectIds.XmlElement): ua.XmlElement,
    ua.NodeId(ObjectIds.NodeId): ua.NodeId,
    ua.NodeId(ObjectIds.ExpandedNodeId): ua.ExpandedNodeId,
    ua.NodeId(ObjectIds.StatusCode): ua.StatusCode,
    ua.NodeId(ObjectIds.QualifiedName): ua.QualifiedName,
    ua.NodeId(ObjectIds.LocalizedText): ua.LocalizedText,
    ua.NodeId(ObjectIds.Structure): ua.ExtensionObject,
    ua.NodeId(ObjectIds.DataValue): ua.DataValue,
    ua.NodeId(ObjectIds.BaseVariableType): ua.Variant,
    ua.NodeId(ObjectIds.DiagnosticInfo): ua.DiagnosticInfo,
}

def get_class_from_nodeid(datatype_nodeid):
   """
   从 NodeId 获取对应的 Python 类。

   Args:
       datatype_nodeid (ua.NodeId): 数据类型的 NodeId。

   Returns:
       type: 对应的 Python 类,如果找不到则返回 None。
   """
   # 检查所有类型字典
   sources = [base_type_list, ua.basetype_by_datatype, ua.extension_objects_by_datatype, ua.enums_by_datatype]
   cls = None
   for src in sources:
       cls = src.get(datatype_nodeid, None)
       if cls is not None:
          return cls
   return cls
登录后复制


    还没收到回复