How to use the opcua.ua.VariantType function in opcua

To help you get started, we’ve selected a few opcua examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github FreeOpcUa / python-opcua / tests / tests_common.py View on Github external
v.set_array_dimensions([0, 0, 0])
        dim = v.get_array_dimensions()
        self.assertEqual(dim, [0, 0, 0])

        v.set_value_rank(0)
        rank = v.get_value_rank()
        self.assertEqual(rank, 0)

        v2 = v.get_value()
        self.assertEqual(v2, l)
        dv = v.get_data_value()
        self.assertEqual(dv.Value.Dimensions, [2,3,4])

        l = [[[], [], []], [[], [], []]]
        variant = ua.Variant(l, ua.VariantType.UInt32)
        v = objects.add_variable(3, 'variableWithDimsEmpty', variant)
        v2 = v.get_value()
        self.assertEqual(v2, l)
        dv = v.get_data_value()
        self.assertEqual(dv.Value.Dimensions, [2,3,0])
github FreeOpcUa / opcua-asyncio / tests / tests.py View on Github external
def test_variant_array_dim(self):
        objects = self.opc.get_objects_node()
        l = [[[1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0], [3.0, 3.0, 3.0, 3.0]],[[5.0, 5.0, 5.0, 5.0], [7.0, 8.0, 9.0, 01.0], [1.0, 1.0, 1.0, 1.0]]]
        v = objects.add_variable(3, 'variableWithDims', l)
        v2 = v.get_value()
        self.assertEqual(v2, l)
        dv = v.get_data_value()
        self.assertEqual(dv.Value.Dimensions, [2,3,4])

        l = [[[], [], []], [[], [], []]]
        variant = ua.Variant(l, ua.VariantType.UInt32)
        v = objects.add_variable(3, 'variableWithDimsEmpty', variant)
        v2 = v.get_value()
        self.assertEqual(v2, l)
        dv = v.get_data_value()
        self.assertEqual(dv.Value.Dimensions, [2,3,0])
github FreeOpcUa / opcua-modeler / test_uamodeler.py View on Github external
def test_structs(modeler, mgr):
    mgr.new_model()

    urns = modeler.get_current_server().get_namespace_array()
    ns_node = mgr.server_mgr.get_node(ua.ObjectIds.Server_NamespaceArray)
    urns = ns_node.get_value()
    urns.append("urn://modeller/testing")
    ns_node.set_value(urns)

    path = "test_save_structs.xml"

    struct_node = mgr.server_mgr.get_node(ua.ObjectIds.Structure)
    modeler.tree_ui.expand_to_node(struct_node)
    mystruct = mgr.add_data_type(1, "MyStruct")
    var1 = mystruct.add_variable(1, "MyFloat", 0.1, varianttype=ua.VariantType.Float)
    var2 = mystruct.add_variable(1, "MyBytes", b'lkjlk', varianttype=ua.VariantType.ByteString)
    mgr.save_xml(path)
    assert len(mgr.new_nodes) == 4  # one struct + TypeDictionary node + namespace and struct node under typedict

    # FIXME: test for presence of nodes under typedict for every new struct
    opc_binary = mgr.server_mgr.get_node(ua.ObjectIds.OPCBinarySchema_TypeSystem)
    typedict = opc_binary.get_child("1:TypeDictionary")
    xml = typedict.get_value()
    assert b"MyFloat" in xml
    assert b"MyStruct" in xml

    mgr.save_xml(path)
    mgr.close_model()
    mgr.open_xml(path)

    opc_binary = mgr.server_mgr.get_node(ua.ObjectIds.OPCBinarySchema_TypeSystem)
    typedict = opc_binary.get_child("1:TypeDictionary")
github FreeOpcUa / opcua-asyncio / tests / tests_xml.py View on Github external
def test_xml_method(self):
        self.opc.register_namespace("tititi")
        self.opc.register_namespace("whatthefuck")
        o = self.opc.nodes.objects.add_object(2, "xmlexportmethod")
        m = o.add_method(2, "callme", func, [ua.VariantType.Double, ua.VariantType.String], [ua.VariantType.Float])
        # set an arg dimension to a list to test list export
        inputs = m.get_child("InputArguments")
        val = inputs.get_value()
        val[0].ArrayDimensions = [2, 2]
        desc = "My nce description"
        val[0].Description = ua.LocalizedText(desc)
        inputs.set_value(val)

        # get all nodes and export
        nodes = [o, m]
        nodes.extend(m.get_children())
        self.opc.export_xml(nodes, "tmp_test_export.xml")

        self.opc.delete_nodes(nodes)
        self.opc.import_xml("tmp_test_export.xml")
github FreeOpcUa / python-opcua / tests / tests_server.py View on Github external
def test_server_method(self):
        def func(parent, variant):
            variant.Value *= 2
            return [variant]
        o = self.opc.get_objects_node()
        v = o.add_method(3, 'Method1', func, [ua.VariantType.Int64], [ua.VariantType.Int64])
        result = o.call_method(v, ua.Variant(2.1))
        self.assertEqual(result, 4.2)
github FreeOpcUa / python-opcua / opcua / ua / ua_binary.py View on Github external
def to_binary(uatype, val):
    """
    Pack a python object to binary given a string defining its type
    """
    if uatype.startswith("ListOf"):
        #if isinstance(val, (list, tuple)):
        return list_to_binary(uatype[6:], val)
    elif isinstance(uatype, (str, unicode)) and hasattr(ua.VariantType, uatype):
        vtype = getattr(ua.VariantType, uatype)
        return pack_uatype(vtype, val)
    elif isinstance(uatype, (str, unicode)) and hasattr(Primitives, uatype):
        return getattr(Primitives, uatype).pack(val)
    elif isinstance(val, (IntEnum, Enum)):
        return Primitives.UInt32.pack(val.value)
    elif isinstance(val, ua.NodeId):
        return nodeid_to_binary(val)
    elif isinstance(val, ua.Variant):
        return variant_to_binary(val)
    elif hasattr(val, "ua_types"):
        return struct_to_binary(val)
    else:
        raise UaError("No known way to pack {} of type {} to ua binary".format(val, uatype))
github FreeOpcUa / python-opcua / opcua / common / type_dictionary_buider.py View on Github external
from opcua import ua
from enum import Enum

import xml.etree.ElementTree as Et
import re

# Indicates which type should be OPC build in types
_ua_build_in_types = [ua_type for ua_type in ua.VariantType.__members__ if ua_type != 'ExtensionObject']


def _repl_func(m):
    """
    taken from
     https://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python
     """
    return m.group(1) + m.group(2).upper()


def _to_camel_case(name):
    """
    Create python class name from an arbitrary string to CamelCase string
    e.g.                 actionlib/TestAction -> ActionlibTestAction
         turtle_actionlib/ShapeActionFeedback -> TurtleActionlibShapeActionFeedback
    """
github FreeOpcUa / python-opcua / opcua / ua / ua_binary.py View on Github external
def pack_uatype(vtype, value):
    if hasattr(Primitives, vtype.name):
        return getattr(Primitives, vtype.name).pack(value)
    elif vtype.value > 25:
        return Primitives.Bytes.pack(value)
    elif vtype == ua.VariantType.ExtensionObject:
        return extensionobject_to_binary(value)
    elif vtype in (ua.VariantType.NodeId, ua.VariantType.ExpandedNodeId):
        return nodeid_to_binary(value)
    elif vtype == ua.VariantType.Variant:
        return variant_to_binary(value)
    else:
        return struct_to_binary(value)
github FreeOpcUa / python-opcua / examples / server-events.py View on Github external
server = Server()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")

    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = server.register_namespace(uri)

    # get Objects node, this is where we should put our custom stuff
    objects = server.get_objects_node()

    # populating our address space
    myobj = objects.add_object(idx, "MyObject")

    # Creating a custom event: Approach 1
    # The custom event object automatically will have members from its parent (BaseEventType)
    etype = server.create_custom_event_type(idx, 'MyFirstEvent', ua.ObjectIds.BaseEventType, [('MyNumericProperty', ua.VariantType.Float), ('MyStringProperty', ua.VariantType.String)])

    myevgen = server.get_event_generator(etype, myobj)

    # Creating a custom event: Approach 2
    custom_etype = server.nodes.base_event_type.add_object_type(2, 'MySecondEvent')
    custom_etype.add_property(2, 'MyIntProperty', ua.Variant(0, ua.VariantType.Int32))
    custom_etype.add_property(2, 'MyBoolProperty', ua.Variant(True, ua.VariantType.Boolean))

    mysecondevgen = server.get_event_generator(custom_etype, myobj)

    # starting!
    server.start()

    try:
        # time.sleep is here just because we want to see events in UaExpert
        import time
github FreeOpcUa / python-opcua / opcua / common / type_dictionary_buider.py View on Github external
def _add_dictionary(self, name):
        dictionary_node_id = self._nodeid_generator()
        node = ua.AddNodesItem()
        node.RequestedNewNodeId = dictionary_node_id
        node.BrowseName = ua.QualifiedName(name, self._idx)
        node.NodeClass = ua.NodeClass.Variable
        node.ParentNodeId = ua.NodeId(ua.ObjectIds.OPCBinarySchema_TypeSystem, 0)
        node.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasComponent, 0)
        node.TypeDefinition = ua.NodeId(ua.ObjectIds.DataTypeDictionaryType, 0)
        attrs = ua.VariableAttributes()
        attrs.DisplayName = ua.LocalizedText(name)
        attrs.DataType = ua.NodeId(ua.ObjectIds.ByteString)
        # Value should be set after all data types created by calling set_dict_byte_string
        attrs.Value = ua.Variant(None, ua.VariantType.Null)
        attrs.ValueRank = -1
        node.NodeAttributes = attrs
        self._session_server.add_nodes([node])

        return dictionary_node_id