FreeOpcUa / python-opcua

LGPL Pure Python OPC-UA Client and Server
http://freeopcua.github.io/
GNU Lesser General Public License v3.0
1.36k stars 658 forks source link

Get/set custom structures #432

Open ghost opened 7 years ago

ghost commented 7 years ago

Is it possible to simply add an custom object to my server without setting every attribute? For example:

class Color(Enum):
    RED = 1
    BLUE = 2

class Obj(object):
    def __init__(self, a: str, b: int, color: Color):
        self.a = a
        self.b = b
        self.color = color

foo = Obj("bar", 6)
foo_node = server.nodes.objects.add_object(idx, "foo1", foo)

After that I want to get this object from my client. I got the following code from this example https://github.com/FreeOpcUa/python-opcua/blob/master/examples/client_read-custom_structures.py

# struct = client.get_node("ns=2;i=10239")
struct = root.get_child(["0:Objects", "2:foo1"])
# before = struct.get_value()
client.import_and_register_structures()  # scan server for custom structures and import them
after = struct.get_value()

It throws the following error:

    client.import_and_register_structures()  # scan server for custom structures and import them
AttributeError: 'Client' object has no attribute 'import_and_register_structures'

Is this method not yet implemented?

zerox1212 commented 7 years ago

You can't pass a Python object to that function. I don't know if you are new to OPC UA, but the language ("object", "type", "property") are almost always in the scope of the OPC UA spec. That function expects an OPC UA object. The objecttype parameter of add_object is a structure of nodes that are defined in the server as an "object type". add_object with the object type parameter will instantiate a copy of the object type structure.

In other words you first have to define your custom structure as OPC UA obect type.

Are your using the package or running the code from the master? I do not think that feature is in the released package. I recommend you pull the code from the master and try it.