FreeOpcUa / python-opcua

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

Fixed load_type_definitions OPCUA types that begin with numbers #1495

Closed RobertHue closed 1 year ago

RobertHue commented 1 year ago

When trying to load_type_definitions, the OPCUA types that begin with numbers, e.g. 1/15, 2D or 3D will result in a SyntaxError: cannot assign to operator, as follows:

<Definition Name="1:SomeEnumeration">
            <Field SymbolicName="S2D" Name="2D" Value="0"/>
            <Field SymbolicName="S3D" Name="3D" Value="1"/>
</Definition>

Reason for the change: Some OPCUA servers use the Enum Value names starting with numbers instead of valid names. Those servers also use a SymbolicName which is not used by python-opcua, but there is a workaround to clean the name with leading numbers by using _clean_name.

See 666c0f182d3a8fae3fdb7e8bd64d9fe534595175

See error:

Traceback (most recent call last): File "C:\Users\RHU\repos\test-framework\src\cli.py", line 127, in main vpu_nodes.setup_opcua_nodes(opc.opcua_client) File "C:\Users\RHU\repos\test-framework\src\common\opcua\opcua_nodes.py", line 251, in setup_opcua_nodes opcua_client.load_type_definitions() # to be able to handle compound types File "C:\Users\RHU\AppData\Local\pypoetry\Cache\virtualenvs\systemtestframework-_FG9QLMh-py3.9\lib\site-packages\opcua\client\client.py", line 626, in load_type_definitions return load_type_definitions(self, nodes) File "C:\Users\RHU\AppData\Local\pypoetry\Cache\virtualenvs\vpu-systemtestframework-_FG9QLMh-py3.9\lib\site-packages\opcua\common\structures.py", line 265, in load_type_definitions generator.get_python_classes(structs_dict) File "C:\Users\RHU\AppData\Local\pypoetry\Cache\virtualenvs\vpu-systemtestframework-_FG9QLMh-py3.9\lib\site-packages\opcua\common\structures.py", line 202, in get_python_classes return _generate_python_class(self.model, env=env) File "C:\Users\RHU\AppData\Local\pypoetry\Cache\virtualenvs\vpu-systemtestframework-_FG9QLMh-py3.9\lib\site-packages\opcua\common\structures.py", line 329, in _generate_python_class exec(code, env) File "", line 9 1/15 = 15 ^ SyntaxError: cannot assign to operator

-> Fix: Used _clean_name that removes characters that might be present in OPC UA structures but cannot be part of of Python class names.