issue_owner_repo listlengths 2 2 | issue_body stringlengths 0 262k ⌀ | issue_title stringlengths 1 1.02k | issue_comments_url stringlengths 53 116 | issue_comments_count int64 0 2.49k | issue_created_at stringdate 1999-03-17 02:06:42 2025-06-23 11:41:49 | issue_updated_at stringdate 2000-02-10 06:43:57 2025-06-23 11:43:00 | issue_html_url stringlengths 34 97 | issue_github_id int64 132 3.17B | issue_number int64 1 215k |
|---|---|---|---|---|---|---|---|---|---|
[
"FreeOpcUa",
"opcua-asyncio"
] | I want to create a simulated clone by getting his xml on a running plc

| Function Request: How do I get the complete xml file code from a running plc | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1144/comments | 0 | 2022-12-07T20:38:19Z | 2022-12-09T19:57:11Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1144 | 1,482,794,200 | 1,144 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
I'm pretty sure that is not a problem of the library, but I can't find another place where ask for help or some direction.
I have some issue to connect to a Simatic S7 1500, without use the client that supplier supply "UA Client 1500". There is a User & Password, its the only things I've hidden.




Until here its all fine, but I would to connect through python to export the data in a programmatically way.
This is my first try with **client-minimal-auth.py** where I've changed **url, client.set_user ,client.set_password**

The modals that I accept with the UA Client 1500 its related to the certificate? I need to ask for the certificate to the supplier?
I've found this on stackoverflow [https://stackoverflow.com/questions/50328537/generate-certificate-for-opc-client](https://stackoverflow.com/questions/50328537/generate-certificate-for-opc-client)
there is this bash script to generate certificates, but I have no luck with:
* client-with-encryption.py (example)
* certificates in the examples folder or self generate certificates
```bash
#!/bin/bash
openssl genrsa -out default_pk.pem 2048
openssl req -new -key default_pk.pem -out cert.csr -subj "/C=IT/ST=RM/L=RM/O=Procosmet/OU=Dev/CN=172.16.1.1"
openssl x509 -req -days 3650 -extfile extensions.cnf -in cert.csr -signkey default_pk.pem -out public.pem
openssl x509 -in public.pem -inform PEM -out public.der -outform DER
```
I really appreciate every tips or direction, its my first time with this kind of integration.
PS: I've tried with the GUI client, the issue is the same.
Thanks
Giovanni
| Simatic S7 1500 - connection issues | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1143/comments | 5 | 2022-12-07T17:23:02Z | 2023-03-14T08:39:44Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1143 | 1,482,434,160 | 1,143 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Not issue, just "how to".
Please tell me how best to implement the subj. It is assumed that I will have 50 or more data changes per second. Is the data change event triggered only for one variable, or is it possible to get all the changes at the moment and perform a batch insert into the database? PostgreSQL database. Thanks! | Best practice of storing data in a database from a client | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1142/comments | 2 | 2022-12-07T13:16:08Z | 2022-12-08T01:22:42Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1142 | 1,481,903,079 | 1,142 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello to everyone!
I have this server:
```
import asyncio
import logging
from asyncua import Server, ua
async def main():
_logger = logging.getLogger("asyncua")
server = Server()
await server.init()
server.set_security_policy([
ua.SecurityPolicyType.NoSecurity,
ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt,
ua.SecurityPolicyType.Basic256Sha256_Sign])
server.set_endpoint("opc.tcp://localhost:4840/freeopcua/server/")
uri = "http://localhost"
idx = await server.register_namespace(uri)
await server.nodes.objects.add_object(idx, "Object")
await server.nodes.objects.add_method(
ua.NodeId("ServerMethod", idx),
ua.QualifiedName("ServerMethod", idx),
[ua.VariantType.Int64],
[ua.VariantType.Int64],
)
async with server:
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
asyncio.run(main(), debug=True)
```
I am trying to add value to Node, and read it:
```
OPC_URL = "opc.tcp://admin@localhost:4840/freeopcua/server/"
OPC_NAMESPACE = "http://localhost"
my_dict = {"ns=2;i=100501": 100501, "ns=2;i=100502": 2}
async with OPClient(url=OPC_URL) as opc_client:
namespace_index: int = await opc_client.get_namespace_index(OPC_NAMESPACE)
tag_obj: Node = await opc_client.nodes.root.get_child(
["0:Objects", f"{namespace_index}:TagsObject"]
)
for tag, value in my_dict.items():
var: Node = await tag_obj.add_variable(namespace_index, tag, value)
print(str(tag) + '-' + str(await var.read_value()))
var = opc_client.get_node(f"ns={namespace_index};i=100501")
node_value = await var.read_value()
```
An d i have error from node_value = await var.read_value():
`asyncua.ua.uaerrors._auto.BadNodeIdUnknown: "The node id refers to a node that does not exist in the server address space."(BadNodeIdUnknown)`
What i am doing wrong?
| Cannot read_value from Node | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1140/comments | 3 | 2022-12-05T07:34:50Z | 2022-12-12T11:26:08Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1140 | 1,475,897,009 | 1,140 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
In my code if the connection to the OPC UA server breaks in any way (e.g. Server crashed) i will try to reconnect to it every 60 seconds. However sometimes it can happen that the tloop thread of one client will be running forever.
After some time (4-5 hours) i can see many tloop threads running (about 50-100) which will sooner or later lead to exceptions that no new Threads can be spawned anymore.
**To Reproduce**<br />
```
from asyncua.sync import Client
import time
connected = False
while not connected:
try:
_opcua_client = Client("tcp.opc://127.0.0.1:4842/")
_opcua_client.connect()
connected = True
except Exception:
print("could not connect")
time.sleep(60)
```
**Expected behavior**<br />
if connection failed, there is no need for the tloop to run. So that thread should quit as soon as possible and not run forever.
**Version**<br />
Python-Version:3.8<br />
opcua-asyncio Version (e.g. master branch, 0.9): 1.0.0
| tloop sometimes won't stop after connection failed | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1139/comments | 2 | 2022-12-02T08:29:25Z | 2023-03-29T12:41:14Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1139 | 1,472,493,739 | 1,139 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello Devs,
I tried to run the example in the examples/sync/client-minimal.py.
If it can't connect to the server, because no OPC-UA Server is running at given host address, the program will never quit (but it should)
If i send a SIGINT signal to the program (CTRL+C) the following error is showing:
```
^CException ignored in: <module 'threading' from '/usr/local/lib/python3.8/threading.py'>
Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 1388, in _shutdown
lock.acquire()
KeyboardInterrupt:
```
(Using the async version of the example works.)
**To Reproduce**<br />
install asyncua in latest version, run the example without any OPC UA Server running.
Program will not stop and quit itself.
**Expected behavior**<br />
Program will stop and quit itselt
**Version**<br />
Python-Version: 3.8 and 3.11 (only these two have been tested)
opcua-asyncio Version 0.9.8, 0.9.98, 1.0.0 (only these versions tested) | Example program not quitting after ConnectionRefused | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1136/comments | 4 | 2022-12-01T13:48:03Z | 2023-03-29T12:41:02Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1136 | 1,471,350,330 | 1,136 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
The endpoint URLs provided by internal_server's get_endpoints function may contain malformatted ipv6 urls when `match_discovery_client_ip` is set to `True` (as it is by default).
According to [RFC2732](https://www.ietf.org/rfc/rfc2732.txt), ipv6 in URLs should be wrapped with square brackets.
This causes some client apps (like the [UA-.DotNetStandard](https://github.com/OPCFoundation/UA-.NETStandard) Reference Client) to be unable to connect to the python asyncua server.
**To Reproduce**<br />
1. Run asyncua server:
```python
#!/usr/bin/env python
import asyncio
import logging
from asyncua import Server
async def main():
_logger = logging.getLogger(__name__)
# setup our server
server = Server()
await server.init()
server.set_endpoint("opc.tcp://localhost:4851/freeopcua/server/")
# server.set_match_discovery_client_ip(False)
_logger.debug(await server.get_endpoints())
# setup our own namespace, not really necessary but should as spec
uri = "http://examples.freeopcua.github.io"
idx = await server.register_namespace(uri)
_logger.info("Starting server!")
async with server:
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
asyncio.run(main(), debug=True)
```
2. Run Reference Client and attempt to connect using `opc.tcp://localhost:4851/freeopcua/server/`.
**Expected behavior**<br />
The server should follow the RFC specification and wrap the ipv6 addresses with square brackets.
This can be fixed by adding a condition on get_endpoints when handling an ipv6 connection.
```diff
diff --git a/asyncua/server/internal_server.py b/asyncua/server/internal_server.py
index 220a3eb..53b0fd7 100644
--- a/asyncua/server/internal_server.py
+++ b/asyncua/server/internal_server.py
@@ -209,7 +209,10 @@ class InternalServer:
edp1 = copy(edp)
url = urlparse(edp1.EndpointUrl)
if self.match_discovery_source_ip:
- url = url._replace(netloc=sockname[0] + ':' + str(sockname[1]))
+ sockaddr, sockport = sockname[0], sockname[1]
+ if ':' in sockaddr:
+ sockaddr = f'[{sockaddr}]'
+ url = url._replace(netloc=f'{sockaddr}:{sockport}')
edp1.EndpointUrl = url.geturl()
edps.append(edp1)
return edps
```
**Version**<br />
Python-Version:<br />
Python 3.10.7
opcua-asyncio Version:<br />
1.0.1
| Server Endpoints can contain invalid URLs when match_discovery_client_ip is set to True | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1129/comments | 0 | 2022-11-23T16:35:22Z | 2023-03-29T12:40:49Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1129 | 1,462,067,807 | 1,129 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I have server:
```
import asyncio
import logging
from asyncua import Server, ua
async def main():
_logger = logging.getLogger("asyncua")
server = Server()
await server.init()
server.set_security_policy([
ua.SecurityPolicyType.NoSecurity,
ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt,
ua.SecurityPolicyType.Basic256Sha256_Sign])
server.set_endpoint("opc.tcp://localhost:4840/freeopcua/server/")
uri = "http://localhost"
idx = await server.register_namespace(uri)
await server.nodes.objects.add_object(idx, "Object")
await server.nodes.objects.add_method(
ua.NodeId("ServerMethod", idx),
ua.QualifiedName("ServerMethod", idx),
[ua.VariantType.Int64],
[ua.VariantType.Int64],
)
async with server:
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
asyncio.run(main(), debug=True)
```
After starting Server i write values to Node Object with this code
```
import asyncio
from asyncua import Client as OPClient
from asyncua.common.node import Node
URL = "opc.tcp://admin@localhost:4840/freeopcua/server/"
NAMESPACE = "http://localhost"
TEST_TAGS = {"test_tag1": 1, "test_tag2": 2}
"""Adding values to Node OPC UA Server"""
print(f"Connecting to OPC UA Server {URL} ...")
async with OPClient(url=URL) as opc_client:
namespace_index: int = await opc_client.get_namespace_index(NAMESPACE)
print(f"Namespace Index for '{NAMESPACE}': {namespace_index}")
tag_obj: Node = await opc_client.nodes.root.get_child(
["0:Objects", f"{namespace_index}:TagsObject"]
)
for tag, value in TEST_TAGS.items():
var: Node = await tag_obj.add_variable(namespace_index, tag, value)
print(str(tag) + '-' + str(await var.read_value()))
```
I want to delete wroten values of Node. how i can do it?
I found only the function to delete node from address space.
Server restart is not my variant too.
Thanks you in advance! And sorry if theme of my question dont match. | How to delete value from Node? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1125/comments | 3 | 2022-11-17T13:13:15Z | 2022-12-05T07:19:28Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1125 | 1,453,325,711 | 1,125 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
`Client.find_servers` method is not working, at least, as my common sense expects it. I have two registered servers in a additional discovery server. When I try to get the registered servers from the discovery server using a client instance I get only one server in the response. Presumably the last registered server.
**To Reproduce**<br />
Run each function using `asyncio.run(main())`
Discovery server
```py
async def main():
server = Server()
await server.init()
server.set_endpoint("opc.tcp://0.0.0.0:4841/freeopcua/server/")
uri = "http://examples.freeopcua.github.io"
idx = await server.register_namespace(uri)
async with server:
logger_.info("Discovery server is running")
while True:
await asyncio.sleep(10)
```
Registered server 1
```py
async def main():
server = Server()
await server.init()
server.set_endpoint("opc.tcp://0.0.0.0:4842/freeopcua/server/")
uri = "http://examples1.freeopcua.github.io"
idx = server.register_namespace(uri)
async with server:
await server.register_to_discovery(url="opc.tcp://localhost:4841", period=10)
logger_.info("Registered server 1 is running")
while True:
await asyncio.sleep(10)
```
Registered server 2
```py
async def main():
server = Server()
await server.init()
server.set_endpoint("opc.tcp://0.0.0.0:4843/freeopcua/server/")
uri = "http://examples.freeopcua.github.io"
idx = server.register_namespace(uri)
async with server:
await server.register_to_discovery(url="opc.tcp://localhost:4841", period=10)
logger_.info("Registered server 2 is running")
while True:
await asyncio.sleep(10)
```
Discovery client
```py
async def main():
client = Client(url="opc.tcp://localhost:4841", timeout=10)
async with client:
logger_.info("Discovery client is running")
while True:
await asyncio.sleep(3)
servers = await client.find_servers()
for server in servers:
logger_.info(f"Servers: {servers}")
```
**Expected behavior**<br />
The `Client.find_servers` should return a list of registered server, however it returns only one server, as shown bellow
```
INFO:DISCOVERY_CLIENT:Servers: [ApplicationDescription(ApplicationUri='urn:freeopcua:python:server', ProductUri='urn:freeopcua.github.io:python:server', ApplicationName=LocalizedText(Locale=None, Text='FreeOpcUa Python Server'), ApplicationType_=<ApplicationType.ClientAndServer: 2>, GatewayServerUri=None, DiscoveryProfileUri=None, DiscoveryUrls=['opc.tcp://0.0.0.0:4842/freeopcua/server/'])]
```
Sometimes the response alternates between one server or the other. I think it is because of the re-register scheduler but I am not sure.

**Version**<br />
Python-Version: 3.10.7
asyncua==0.9.98
| Unexpected behavior finding registered server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1122/comments | 5 | 2022-11-10T19:20:40Z | 2023-03-29T12:40:17Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1122 | 1,444,436,894 | 1,122 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I am trying to implement an isConnected function but I am not very familiar with python. These functions are inside a class.
Connect Function
```
async def connect(self, url):
print("Trying to connect")
self.client = Client(url)
await self.client.connect()
```
isConnected function
```
async def isConnected(self):
print("Check connection")
await self.client.check_connection()
```
When I call isConnected() without calling Connect() it says self.client attribute does not exist. Which is expected and ok.
But when I call Connect() then isConnected() this happens. Bu I am sure I am connected because if I try to run client.get_node(...) it works.
```
Exception in thread Thread-2 (process_request_thread):
Traceback (most recent call last):
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\asyncua\client\client.py", line 478, in _renew_channel_loop
await asyncio.sleep(duration)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 605, in sleep
return await future
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
self.run()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\socketserver.py", line 683, in process_request_thread
self.finish_request(request, client_address)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\socketserver.py", line 747, in __init__
self.handle()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\werkzeug\serving.py", line 363, in handle
super().handle()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\http\server.py", line 427, in
handle
self.handle_one_request()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\http\server.py", line 415, in
handle_one_request
method()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\werkzeug\serving.py", line 335, in run_wsgi
execute(self.server.app)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\werkzeug\serving.py", line 322, in execute
application_iter = app(environ, start_response)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\asgiref\sync.py", line 218, in __call__
return call_result.result()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py",
line 439, in result
return self.__get_result()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py",
line 391, in __get_result
raise self._exception
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\asgiref\sync.py", line 284, in main_wrap
result = await self.awaitable(*args, **kwargs)
File "C:\Users\COSKUN\Desktop\coskun\kalinlik-takip\api\main.py", line 53, in check_connection
print(await client.isConnected())
File "C:\Users\COSKUN\Desktop\coskun\kalinlik-takip\api\opcuaReader.py", line 100, in isConnected
await self.client.check_connection()
File "C:\Users\COSKUN\AppData\Local\Programs\Python\Python310\lib\site-packages\asyncua\client\client.py", line 440, in check_connection
await self._renew_channel_task
asyncio.exceptions.CancelledError
```
Is it a bug or am I doing something wrong? As far as I understand check_connection() should only throw exception if connection is not possible or disconnected.
Is it ok to use client.connect() everytime I try to read value? | check_connection() always throws exception when connected | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1117/comments | 10 | 2022-11-08T09:06:22Z | 2023-03-29T12:39:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1117 | 1,439,775,658 | 1,117 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi there
Recently I found that when I upgrade opcua-asynico to the latest version, and i could not connect the server by this library using opcua-client gui, even when I tried to connect the server example. Could anyone helpe me? thanks a lot.

| opcua-client | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1115/comments | 2 | 2022-11-07T15:19:36Z | 2022-11-08T07:26:38Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1115 | 1,438,538,579 | 1,115 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Values with status code uncertain are replaced with null values
**To Reproduce**<br />
call write_attribute_value with a value and status code for example UncertainSensorCalibration
**Expected behavior**<br />
I expect to get a data change notification containing the value and status code that I wrote.
**Version**<br />
Python-Version: 3.9<br />
opcua-asyncio Version: 1.0
The code refers to https://reference.opcfoundation.org/v104/Core/docs/Part4/7.7.1/ which says:
> The data value. If the StatusCode indicates an error then the value is to be ignored and the Server shall set it to null.
But https://reference.opcfoundation.org/v104/Core/docs/Part4/7.34.1/ says:
> Good Success 00 Indicates that the operation was successful and the associated results may be used.
Uncertain Warning 01 Indicates that the operation was partially successful and that associated results might not be suitable for some purposes.
Bad Failure 10 Indicates that the operation failed and any associated results cannot be used.
Which I interpret as that only "bad failure" statuses should be considered errors.
I propose changing "not value.StatusCode.is_good()" to "value.StatusCode.is_bad()", unless someone who knows more about OpcUa than me can clarify the situation. | server treats uncertain as error, and sends null instead of value | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1102/comments | 1 | 2022-10-28T13:46:52Z | 2022-10-31T11:56:23Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1102 | 1,427,290,892 | 1,102 |
[
"FreeOpcUa",
"opcua-asyncio"
] | sync.py line 394:
return SyncNode(sync_node.tloop, node.Node(sync_node.aio_obj.**server**, nodeid))
should be:
return SyncNode(sync_node.tloop, node.Node(sync_node.aio_obj.**session**, nodeid))
**Describe the bug** <br />
Traceback (most recent call last):
File "C:\Users\15068\develop\code\python\opc\opcua-client-gui-master\venv\lib\site-packages\uawidgets\tree_widget.py", line 242, in fetchMore
self._fetchMore(parent)
File "C:\Users\15068\develop\code\python\opc\opcua-client-gui-master\venv\lib\site-packages\uawidgets\tree_widget.py", line 252, in _fetchMore
self.add_item(desc, parent)
File "C:\Users\15068\develop\code\python\opc\opcua-client-gui-master\venv\lib\site-packages\uawidgets\tree_widget.py", line 210, in add_item
item[0].setData(new_node(parent_node, desc.NodeId), Qt.UserRole)
File "C:\Users\15068\develop\code\python\opc\opcua-client-gui-master\venv\lib\site-packages\asyncua\sync.py", line 394, in new_node
return SyncNode(sync_node.tloop, node.Node(sync_node.aio_obj.server, nodeid))
AttributeError: 'Node' object has no attribute 'server'
**To Reproduce**<br />
run opcua-client-gui app.py, click connect
**Expected behavior**<br />
can't connect to opc server.
**Version**<br />
Python-Version:<br />
asyncua Version (1.0.0):
| asyncua\sync.py line 394 bug | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1100/comments | 4 | 2022-10-28T08:13:26Z | 2023-03-29T12:39:31Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1100 | 1,426,871,179 | 1,100 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Our client creates a DataChangeFilter with Trigger set to OpcUa_DataChangeTrigger_StatusValueTimestamp, but it seems like opcua-asyncio server ignores this and still only sends datachange notifications when status or value changes.
**To Reproduce**<br />
```
/* Sample code for creation of data change filter */
OpcUa_DataChangeFilter* pDataChangeFilter = NULL;
OpcUa_EncodeableObject_CreateExtension(
&OpcUa_DataChangeFilter_EncodeableType,
&createRequest[i].RequestedParameters.Filter,
(OpcUa_Void**)&pDataChangeFilter);
if (pDataChangeFilter)
{
pDataChangeFilter->DeadbandType = OpcUa_DeadbandType_None;
pDataChangeFilter->DeadbandValue = 0.0;
pDataChangeFilter->Trigger = OpcUa_DataChangeTrigger_StatusValueTimestamp;
}
```
**Expected behavior**<br />
DataChange notification when write_attribute_value is called with a new timestamp, even if value and status are unchanged.
**Screenshots**<br />
I tried to follow the logic in the server, and it looks like server.write_attribute_value eventually reaches the following lines in address_space.py:
```
# only send call callback when a value or status code change has happened
if (old.Value != value.Value) or (old.StatusCode != value.StatusCode):
cbs = list(attval.datachange_callbacks.items())
```
Just guessing, but maybe it's possible to remove this hardcoded check, and instead do a test in monitored_item_service.py based on the Trigger value?
**Version**<br />
Python-Version:<br />
opcua-asyncio Version (e.g. master branch, 0.9):
| Server ignores DataChangeFilter trigger value | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1098/comments | 1 | 2022-10-26T12:10:17Z | 2022-10-30T09:00:42Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1098 | 1,423,918,016 | 1,098 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi,
I wrote a code with asyncua in python. I could not synchronize it with KEPSERVER.
Also, I read thee example "client-kepware" but yet the problem remains. What should I do?
I think it is because the username and password.
I would be thankful if you help me.
thanks. | client asyncua to kepware | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1095/comments | 22 | 2022-10-23T08:02:40Z | 2023-03-14T08:43:43Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1095 | 1,419,696,014 | 1,095 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello everyone,
We are currently using this repository to talk to our Opc Ua Server.
Our Server has the base information model, the DI information model and the AutoID information model on top of it.
We want to receive Events with types from the AutoID information model.
We are using the `load_type_definition` function to load the datatype definitions. Our server doesn't yet support the new `load_data_type_definition` function.
The function seem to work fine, however I think that the error we are experiencing is coming from a wrong decoding of the `ScanData` Object we want to receive via an Event we have successfully subscribed to. The `ScanData` has the following bsd definition:
```
<opc:StructuredType BaseType="ua:Union" Name="ScanData">
<opc:Field TypeName="opc:UInt32" Name="SwitchField"/>
<opc:Field SwitchField="SwitchField" TypeName="opc:ByteString" SwitchValue="1" Name="ByteString"/>
<opc:Field SwitchField="SwitchField" TypeName="opc:CharArray" SwitchValue="2" Name="String"/>
<opc:Field SwitchField="SwitchField" TypeName="tns:ScanDataEpc" SwitchValue="3" Name="Epc"/>
<opc:Field SwitchField="SwitchField" TypeName="ua:Variant" SwitchValue="4" Name="Custom"/>
</opc:StructuredType>
```
The resulting datatype the generator is producing looks like this:
```
dataclass
class ScanData:
'''
ScanData structure autogenerated from xml
'''
Encoding:'ua.UInt32' = None
SwitchField:'ua.UInt32' = 0
ByteString: Optional['ua.ByteString'] = None
String: Optional['ua.CharArray'] = None
Epc: Optional['ua.ScanDataEpc'] = None
Custom: Optional['ua.Variant'] = None
```
If the event is getting decoded, for the `ScanData` Object the `SwitchField` gets decoded as an `UInt32` but then the `Encoding` gets also decoded as a `UInt32`. This however, shifts the whole binary data by 4 bytes which results in a decoding error for the selected field `ByteString`` which consists of a 4-byte length field and the data field.
We are getting the following error in the end:
> asyncua.common.utils.NotEnoughData: Not enough data left in buffer, request for 907018466, we have 40
This is because the selected switch field (`ByteString` in our case) has a length value which is now shifted to the data of the `ByteString` by the decoder and therefore is a very large value.
We took a deep look in Wireshark: The `ScanData` field is only transmitted as the `SwitchField` (`UInt32`) + selected field (`ByteString` or `CharArray` or `ScanDataEpc` or `Variant`). There is no additional `Encoding` field transmitted.
If we are using UAExpert, everything works fine. The `SwitchField` shows the correct value and the selected `ByteString` field shows the correct data. | Types with a Switch Field seem to get decoded the wrong way | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1093/comments | 2 | 2022-10-19T14:01:15Z | 2022-11-03T07:08:40Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1093 | 1,415,034,530 | 1,093 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
For example : [BaseDataVariableType](https://reference.opcfoundation.org/Core/VariableTypes/v104/BaseDataVariableType/) should not be abstract, but is found to have isAbstract = True upon inspection with UAExpert.
**To Reproduce**<br />
Run asyncio example server and observe the isAbstract attribute of BaseDataVariableType.
**Expected behavior**<br />
This node should not be marked abstract. If you explicitly set isAbstract = False in standard_address_space_services.py the problem is resolved.
**Version**<br />
Python-Version: 3.9.1
opcua-asyncio Version 0.9.95
| Datatypes marked isAbstract = True for datatypes that should not be abstract | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1084/comments | 1 | 2022-10-15T04:10:06Z | 2022-11-03T07:08:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1084 | 1,410,035,845 | 1,084 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I have an OPCUA client which import OPCUA server nodes.
Of course I need to import all types before import instances.
I notice something strange exploring your python OPCUA server example (./examples/server-example.py) with [UA Expert](https://www.unified-automation.com/products/development-tools/uaexpert.html?gclid=CjwKCAjwkaSaBhA4EiwALBgQaBese3e5mKLDiARME9FgG35xTKRE74sQQXBHO-pEaKe0ChuVn5u5BhoCzRYQAvD_BwE)
All root types, BaseEventType, BaseInterfaceType, BaseObjectType, References and BaseVariableType have DataType icon, while they should have Type icon.
I immediately check the NodeClass attributes of those items, and they are correct.
So I do not understand why they are recognised as DataTypes.
What I found strange is that they have "DataTypeDefinition" attribute specified (the new opcua specification attribute for Structures and Enums).
This attribute is specified only for them, not for subTypes.
I think this can create problems navigating with references and check type consistency.
The attribute on root types is something that you put intentionally?
If yes, why?
**To Reproduce**<br />
Start the example server (./examples/server-example.py) and connect with UAExpert
**Expected behavior**<br />
DataTypeDefinition attribute not present on root types (BaseEventType, BaseInterfaceType, BaseObjectType, References and BaseVariableType)
**Screenshots**<br />


**Version**<br />
Python-Version: **3.10.2**<br />
opcua-asyncio Version (e.g. master branch, 0.9): master (f2ff44b8cbf00da7ac184d03b9106166f08c70b5)
| Problem analyzing OPCUA Server root types. Unexpected DataTypeDefinition attribute found | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1082/comments | 2 | 2022-10-14T13:43:42Z | 2023-03-29T12:39:02Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1082 | 1,409,379,769 | 1,082 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ### Discussed in https://github.com/FreeOpcUa/opcua-asyncio/discussions/1078
<div type='discussions-op-text'>
<sup>Originally posted by **dibyendumca** October 12, 2022</sup>
SCREEN SHOTS ...
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@



PLEASE REFER THE CODE SNIPPET BELOW...
############################################################################################
@uamethod
def Multiply(parent, x, y):
# Function Multiply
msgLog = messageLogger()
res = 0.0
msgLog.WriteLog( LogErr.INF, "Multiply method called with parameters: " + str(x) + ", " + str(y))
try:
res = x * y
except Exception as e:
msgLog.WriteLog(
LogErr.ERR, "Oops!" + sys.exc_info()[0] + "occurred.")
msgLog.WriteLog(
LogErr.ERR, "Oops!" + e.__class__ + "occurred.")
print()
else:
msgLog.WriteLog(LogErr.INF, "Result: " + str(res))
return res
NOW ADDING THE FUNCTION **Multiply**(x, y) ...
# ##########################################################################
inargx = ua.Argument()
inargx.Name = "x"
inargx.DataType = ua.NodeId(ua.ObjectIds.Double)
inargx.ValueRank = -1
inargx.ArrayDimensions = []
inargx.Description = ua.LocalizedText("First number x")
inargy = ua.Argument()
inargy.Name = "y"
inargy.DataType = ua.NodeId(ua.ObjectIds.Double)
inargy.ValueRank = -1
inargy.ArrayDimensions = []
inargy.Description = ua.LocalizedText("Second number y")
outarg = ua.Argument()
outarg.Name = "Result"
outarg.DataType = ua.NodeId(ua.ObjectIds.Double)
outarg.ValueRank = -1
outarg.ArrayDimensions = []
outarg.Description = ua.LocalizedText("Multiplication result")
multiplyNode = await ParamMethods.add_method(spaceNodeId, "Multiply", CustomFeatures.Multiply, [inargx, inargy], [outarg])
# #####################################################################
WHENEVER I AM CALLING THE FUNCTION Multiply(x, y) WITH PARAMETERS x=2 AND y=3 from FreeOpcUa Client tool,
I AM GETTING THE FOLLOWING ERROR ...
###############################################################################################
Multiply method called with parameters: Variant(Value=2.0, VariantType=<VariantType.Double: 11>, Dimensions=None, is_array=False), 3.0
Error executing method call CallMethodRequest(ObjectId=NodeId(Identifier=2, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>), MethodId=NodeId(Identifier=6, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>), InputArguments=[Variant(Value=2.0, VariantType=<VariantType.Double: 11>, Dimensions=None, is_array=False), Variant(Value=3.0, VariantType=<VariantType.Double: 11>, Dimensions=None, is_array=False)]), an exception was raised:
Traceback (most recent call last):
File "...\CustomFeaturesStub.py", line 54, in Multiply
res = x * y
TypeError: unsupported operand type(s) for *: 'Variant' and 'float'
AFTER MODIFYING THE CODE OF THE FUNCTION Multiply(x, y) ...


CODE SNIPPET ....
# ################################################################################
@uamethod
def Multiply(parent, x, y):
# Function Multiply
msgLog = messageLogger()
x = x.Value
y = y.Value
res = 0.0
msgLog.WriteLog(
LogErr.INF, "Multiply method called with parameters: " + str(x) + ", " + str(y))
try:
res = x * y
except Exception as e:
msgLog.WriteLog(
LogErr.ERR, "Oops!" + sys.exc_info()[0] + "occurred.")
msgLog.WriteLog(
LogErr.ERR, "Oops!" + e.__class__ + "occurred.")
print()
else:
msgLog.WriteLog(LogErr.INF, "Result: " + str(res))
return res
# ######################################################################
ERROR ...
Error executing method call CallMethodRequest(ObjectId=NodeId(Identifier=2, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>), MethodId=NodeId(Identifier=6, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>), InputArguments=[Variant(Value=2.0, VariantType=<VariantType.Double: 11>, Dimensions=None, is_array=False), Variant(Value=3.0, VariantType=<VariantType.Double: 11>, Dimensions=None, is_array=False)]), an exception was raised:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\asyncua\server\address_space.py", line 583, in _call
result = await self._run_method(node.call, method.ObjectId, *method.InputArguments)
File "C:\ProgramData\Anaconda3\lib\site-packages\asyncua\server\address_space.py", line 602, in _run_method
res = await asyncio.get_event_loop().run_in_executor(self._pool, p)
File "C:\ProgramData\Anaconda3\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\opcua\common\methods.py", line 69, in wrapper
result = func(self, parent, *[arg.Value for arg in args])
File "D:\MADI04\PROJECTS\PYTHON\ASYNCUA\DacXpertM\CustomFeaturesStub.py", line 51, in Multiply
y = y.Value
AttributeError: 'float' object has no attribute 'Value'
#########################################################################################
WHEN FUNCTION Multiply(x, y) IS MODIFIED AS BELOW THEN THERE IS NO ERROR...


**IS THIS A BUG ???**, @uamethod --> Converting only the 2nd parameter from VARIANT to FLOAT, but not the 1st parameter
</div> | @uamethod decorator --> DOES Automatically convert to and from variants ? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1079/comments | 2 | 2022-10-12T09:40:45Z | 2022-10-12T11:49:00Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1079 | 1,405,898,090 | 1,079 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
we are using the sync wrapper to test out an opcua server. Our code looks like the following:
```
self.client = Client(BASE_ADDRESS_OPCUA)
self.client.set_user(USERNAME)
self.client.set_password(PASSWORD)
self.client.connect()
self.client.load_data_type_definitions()
...
```
So we are trying to get the datatype definitions out of our opcua server.
However, the `load_data_type_definitions()` function returns an error we cannot fix:
> RuntimeError: Unknown datatype for field: StructureField(Name='LocationType', Description=LocalizedText(Locale=None, Text=None), DataType=NodeId(Identifier=3009, NamespaceIndex=4, NodeIdType=<NodeIdType.FourByte: 1>), ValueRank=-1, ArrayDimensions=None, MaxStringLength=0, IsOptional=True) in structure:ScanSettings, please report
If we try to connect our server via UAExpert, no errors are thrown there. So the model should be consistent. Moreover, UAExpert shows the definition of the LocationTypeEnumeration which is represented by node ns=4;i=3009:
<img width="215" alt="image" src="https://user-images.githubusercontent.com/102594442/195080988-28719622-b587-48ec-966a-a5484ee8fdfa.png">
So it should be available.
The ScanSettings Structure is defined in the AutoID information Model in the following form:
```
...
<Alias Alias="LocationTypeEnumeration">ns=1;i=3009</Alias>
...
<UADataType NodeId="ns=1;i=3009" BrowseName="1:LocationTypeEnumeration">
<DisplayName>LocationTypeEnumeration</DisplayName>
<Documentation>https://reference.opcfoundation.org/v104/AutoID/v101/docs/9.2.3</Documentation>
<References>
<Reference ReferenceType="HasProperty">ns=1;i=6040</Reference>
<Reference ReferenceType="HasSubtype" IsForward="false">i=29</Reference>
</References>
<Definition Name="1:LocationTypeEnumeration">
<Field Name="NMEA" Value="0" />
<Field Name="LOCAL" Value="1" />
<Field Name="WGS84" Value="2" />
<Field Name="NAME" Value="3" />
</Definition>
</UADataType>
...
<UADataType NodeId="ns=1;i=3010" BrowseName="1:ScanSettings">
<DisplayName>ScanSettings</DisplayName>
<Documentation>https://reference.opcfoundation.org/v104/AutoID/v101/docs/9.3.7</Documentation>
<References>
<Reference ReferenceType="HasEncoding">ns=1;i=5015</Reference>
<Reference ReferenceType="HasEncoding">ns=1;i=5016</Reference>
<Reference ReferenceType="HasSubtype" IsForward="false">i=22</Reference>
</References>
<Definition Name="1:ScanSettings">
<Field Name="Duration" DataType="Duration" />
<Field Name="Cycles" DataType="Int32" />
<Field Name="DataAvailable" DataType="Boolean" />
<Field Name="LocationType" DataType="LocationTypeEnumeration" IsOptional="true" />
</Definition>
</UADataType>
...
```
We also noticed that the deprecated function `load_type_definitions` works fine whereas we are using the v1.04 nodeset definitions from the OPC Foundation.
Some Specs:
- Python Interpreter: Python 3.8
- Information Models: Base, Di, AutoId, our own to instantiate the an RfidReaderDeviceType
Any ideas? | Unknown Datatype for Field LocationType in AutoID model | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1076/comments | 1 | 2022-10-11T11:51:01Z | 2022-10-11T11:59:16Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1076 | 1,404,504,993 | 1,076 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I have used `asyncua` to create a python simulator of a system, and it exposes the same (in theory) opcua interface as the real system. The real system is being created by another organisation and they have sent me a PLC that I can power up and connect to so I can see the opcua interface.
My server uses the `asyncua.common.XmlImporter` to create the nodes, and then it iterates through them and stores them in a python dictionary of type `Dict[NODE_NAME_ENUM, asyncua.Node]`, where it uses the display name of the imported Node to determine the enum, and raises an exception if there is no corresponding enum.
To be certain that my simulator is exposing the same interface as the real system, and to make any future changes in the real system easier to reflect in my simulator, I would like to replace my XML config that I semi-handwrote with one that is generated from the PLC that I have been sent. I can then run my simulator and be certain that it exposes the same interface.
I do not have access to the source code of the real system as it uses an opcua plugin for the programming environment of the PLC (I think TwinCat).
Is it possible to write a client that can connect to the PLC's opcua interface and create the XML file for me, so then I can load it into my simulator? Alternatively, is it likely I can export the XML file from TwinCAT? What is the name of this format so I know what to search for, or is it `asyncua` specific? If neither of those options are possible, how can achieve what I am trying to do?
Thanks! | Feature request / Question: How to make a Client use the XmlExporter to generate an xml file from an external opcua server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1075/comments | 2 | 2022-10-10T19:15:16Z | 2023-03-29T12:38:42Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1075 | 1,403,605,126 | 1,075 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I've been testing for a couple days and upgrading my version of the 'asyncua' library. A lot seems to have changed and it's still very unclear from documentation and examples how a practical subscription use, in an app will work. I would suggest any practical use case would require very robust connectivity:
1. A means of staying alive over long periods of time
2. A means of making sure updates are not missed.
Below is an example of me testing against a live server. I'm happy to work on this and submit a PR. There are so many use case questions that come up:
1. How to reconnect after an error.
2. How to keep sessions consistent.
3. How to prioritize the reconnection event.
I ran into all kinds of bugs yesterday from, exceeding max sessions to uncaught errors in other concurrent code blocks that threw errors when I tried to asycnio.sleep. I've updated to the latest version: 0.9.98 and am testing again today to see what pops.
```
import unittest
import asyncio
from asyncua import Client, Node, ua
import numpy as np
import config
from datetime import datetime, timedelta
from src.opcua_connection_engine import OpcuaConnectionEngine
import logging
_logger = logging.getLogger('Test')
def log_call(msg, backoff, i, start_time):
n = backoff[i+1] if i < len(backoff) else "NO"
_logger.warning(f'{i} d={datetime.now() - start_time} n={n} s={backoff[0]} {msg}')
return
def calc_backoff(h:float, g:float):
"""Calculate an array of executions time that adhere to a backoff strategy.
Args:
h (int): max time domain of array in hours.
g (_type_): backoff increment in minutes.
Returns:
list: executions times adhereing to backoff strategy.
"""
n = datetime.now()
max = timedelta(hours=h) + n
backoff = [n + timedelta(minutes=g)]
while backoff[-1] < max:
backoff.append(backoff[-1]+timedelta(minutes=(len(backoff)+1)*g))
return backoff
async def update_nodes(nodes_to_read, value):
log_call(f'Begin update', backoff, i, start_time)
client2 = Client(config.OPCUA_URL_CODESYS)
client2.set_user(config.OPCUA_USER_CODESYS)
client2.set_password(config.OPCUA_PASSWORD_CODESYS)
await client2.connect()
log_call(f'Value to write: {value}', backoff, i, start_time)
values = [ua.DataValue(ua.Variant(value, ua.VariantType.Boolean))] * len(nodes_to_read)
log_call(f'Writing values', backoff, i, start_time)
await client2.uaclient.write_attributes(
nodeids= [n.nodeid for n in nodes_to_read],
datavalues= values,
attributeid= ua.AttributeIds.Value
)
log_call(f'Update complete', backoff, i, start_time)
return
class TestConnectivity(unittest.IsolatedAsyncioTestCase):
async def test_subscription(self):
start_time = datetime.now()
backoff = calc_backoff(2, 2)
print([t.isoformat() for t in backoff])
client = Client(config.OPCUA_URL_CODESYS)
client.set_user(config.OPCUA_USER_CODESYS)
client.set_password(config.OPCUA_PASSWORD_CODESYS)
await client.connect()
nodes_to_read = [
'ns=4;s=|var|CODESYS Control Win V3 x64.Application.ioHMIControls.EStopHMI',
'ns=4;s=|var|CODESYS Control Win V3 x64.Application.ioHMIControls.JogHMI',
'ns=4;s=|var|CODESYS Control Win V3 x64.Application.ioHMIControls.RunHMI',
'ns=4;s=|var|CODESYS Control Win V3 x64.Application.ioHMIControls.ThreadHMI',
]
nodes_to_read = [Node(client, n) for n in nodes_to_read]
i=0
class SubHandler:
async def datachange_notification(self, node: Node, val, data):
log_call(f'result: {data}', backoff, i, start_time)
def status_change_notification(self, status):
log_call(f'result: {status}', backoff, i, start_time)
subscription = await client.create_subscription(500, SubHandler())
await subscription.subscribe_data_change(
nodes=nodes_to_read,
attr=ua.AttributeIds.Value,
queuesize=50,
monitoring=ua.MonitoringMode.Reporting,
)
await update_nodes(nodes_to_read, True)#, client)
await asyncio.sleep(3)
await update_nodes(nodes_to_read, False)#, client)
await asyncio.sleep(3)
await update_nodes(nodes_to_read, True)#, client)
await asyncio.sleep(3)
while datetime.now() < backoff[-1]:
if datetime.now() > backoff[i]:
await update_nodes(nodes_to_read, bool(i % 2))
i += 1
print('Sleeping')
await asyncio.sleep(30)
return
```
| Test: long running subscriptions | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1072/comments | 12 | 2022-10-07T16:03:29Z | 2023-03-29T12:38:21Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1072 | 1,401,395,353 | 1,072 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Nodeset import fails due to the error
```
File "/home/ubuntu/.local/lib/python3.11/site-packages/asyncua/server/server.py", line 616, in import_xml
return await importer.import_xml(path, xmlstring)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ubuntu/.local/lib/python3.11/site-packages/asyncua/common/xmlimporter.py", line 154, in import_xml
await self._check_if_namespace_meta_information_is_added()
File "/home/ubuntu/.local/lib/python3.11/site-packages/asyncua/common/xmlimporter.py", line 106, in _check_if_namespace_meta_information_is_added
obj = await self.nodes.namespaces.add_object(idx, uri, ua.ObjectIds.NamespaceMetadataType, False)
^^^^^^^^^^
AttributeError: 'XmlImporter' object has no attribute 'nodes'
```
**To Reproduce**<br />
Start minimal server and import a NodeSet2.xml file generated using SiOME.
**Expected behavior**<br />
Companion Specification NodeSets are imported without error.
**Version**<br />
Python-Version: 3.11
opcua-asyncio Version (e.g. master branch, 0.9): 3.9? Installed using `python3.11 -m pip install asyncua`
**Probable error**<br />
In `XmlImporter._check_if_namespace_meta_information_is_added(self)` `obj` is assigned `await self.nodes.namespaces.add_object(idx, uri, ua.ObjectIds.NamespaceMetadataType, False)`, although XmlIporter has no attribute `nodes`. Should be `obj = await self.server.nodes.namespaces.add_object(idx, uri, ua.ObjectIds.NamespaceMetadataType, False)` instead i guess. | XmlImporter trying to access self.nodes | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1068/comments | 1 | 2022-10-05T16:41:01Z | 2022-10-06T05:30:49Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1068 | 1,398,079,182 | 1,068 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Most types in `ua.uatypes`, for example like `CharArray` and `Float`, are derived from a matching Python datatype.
But this isn't the case for `ua.uatypes.String`. In #609 the typedef is changed from `class String(str):` to `class String:`.
Not sure why this is done and if the original reason is still the case (@oroulet ?). If I change it back and run pytest no new errors are introduced. It even fix an existing issue in the test:
```
./tests/test_common.py::test_alias[client] Failed: [undefined]AttributeError: 'String' object has no attribute 'encode'
```
By having no str as baseclass makes use of the python typing system hard:
```python
my_string : ua.String = "" # due typing invalid
my_string : ua.String = ua.String() # Quite unusable, return empty ua.String object
```
What about changing it back to class `class String(str):`?
| [ua.uatypes.String] used baseclass | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1067/comments | 14 | 2022-10-05T08:04:40Z | 2023-03-21T13:24:03Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1067 | 1,397,401,295 | 1,067 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
In a fresh build with no other changes apart from an upgrade of the asyncua dependency from 0.9.97 to 0.0.98, previously working OPC comms fail with "Error in watchdog loop".
**To Reproduce**<br />
Update asyncua dependency from 0.9.97 to 0.9.98; rebuild and enjoy.
**Expected behavior**<br />
Comms to complete successfully.
~**Screenshots**~ How about **Logs**?<br />
```
2022-10-02 17:28:53,428 | opcUA | DEBUG | read_node | Read value: 3.0 from node: XYZ_ABC.XYZ123.XY123_Ab1_NodeNodeNode\5ec6d85-fa3-10441 Error in watchdog loop
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/asyncua/client/client.py", line 454, in _monitor_server_loop
await asyncio.sleep(timeout) File "/usr/local/lib/python3.7/asyncio/tasks.py", line 595, in sleep
return await future concurrent.futures._base.CancelledError
Error while renewing session Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/asyncua/client/client.py", line 472, in _renew_channel_loop
await asyncio.sleep(duration)
File "/usr/local/lib/python3.7/asyncio/tasks.py", line 595, in sleep
return await future concurrent.futures._base.CancelledError
```
**Version**<br />
Python-Version: `3.7.14`<br />
opcua-asyncio Version (e.g. master branch, 0.9): tag `v0.9.98`
Best I can see, the issue is caused by this change here:

which removes two lines that swallow an `asyncio.CancelledError` and instead let the exception be raised.
Happy to submit a PR to fix but would prefer input first to be sure I'm not undoing something worthy.
| "Error in watchdog loop" after v0.9.98 bump | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1064/comments | 14 | 2022-10-03T06:39:45Z | 2022-11-29T12:22:37Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1064 | 1,394,217,110 | 1,064 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When setting up a simple `server-minimal.py` example, by importing a nodeset, that is generated by TIA portal, v15.1, SIEMENS/SIMANTIC - s7-1500, the `xmlimporter.py` goes into a infinite loop, as the parent node is not found.
No output information is given about this.
in `python-opcua` ( **not** `opcua-asyncio` ), we get output with the same nodeset that states parent node if does not refer to a valid node
```
raise UaStatusCodeError(self.value)
opcua.ua.uaerrors._auto.BadParentNodeIdInvalid: "The parent node id does not to refer to a valid node."(BadParentNodeIdInvalid)
```
**To Reproduce**<br />
```
import asyncio
import logging
import os
from asyncua import Server, ua
from asyncua.common.methods import uamethod
import traceback
from datetime import datetime
build_date = datetime(2022, 6, 15, 17, 00)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
async def main():
_logger = logging.getLogger("asyncua")
# setup our server
server = Server()
await server.init()
await server.set_build_info(
product_uri="https://",
product_name="test asyncio",
manufacturer_name="company",
software_version="alpha",
build_number="202206151700",
build_date=build_date,
)
server.set_security_policy([
ua.SecurityPolicyType.NoSecurity,
])
server.set_security_IDs([
"Anonymous",
])
server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
print("Setup done!")
print(f"current base dir: {BASE_DIR}")
try:
nodes1 = await server.import_xml(os.path.join(BASE_DIR, "examples", "nodesets", "custom", "V03_21.00.01.PLC_1.OPCUA_20220329.xml"))
except Exception as e:
just_the_string = traceback.format_exc()
print(f" Caught exception loading nodeset: {just_the_string}")
_logger.info("Starting server!")
async with server:
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("asyncio").setLevel(logging.DEBUG)
asyncio.run(main(), debug=True)
```
Unfortunately, due to company policy, I cannot attach the nodeset xml.
```
def _sort_nodes_by_parentid(self, ndatas):
"""
Sort the list of nodes according their parent node in order to respect
the dependency between nodes.
:param nodes: list of NodeDataObjects
:returns: list of sorted nodes
"""
sorted_ndatas = []
sorted_nodes_ids = set()
all_node_ids = set(data.nodeid for data in ndatas)
cnt = 0
while len(sorted_nodes_ids) < len(ndatas):
for ndata in ndatas:
print(f"ndata: {ndata} : {cnt}")
cnt = cnt + 1
if ndata.nodeid in sorted_nodes_ids:
continue
elif ndata.parent is None or ndata.parent not in all_node_ids:
sorted_ndatas.append(ndata)
sorted_nodes_ids.add(ndata.nodeid)
else:
# Check if the nodes parent is already in the list of
# inserted nodes
if ndata.parent in sorted_nodes_ids:
sorted_ndatas.append(ndata)
sorted_nodes_ids.add(ndata.nodeid)
return sorted_ndatas
```
The above method goes into an infinite loop as no `ndata` is added to the `sorted_ndatas` or `sorted_nodes_ids` lists.
Thus the `len(sorted_nodes_ids)` is always less than `len(ndatas)`
**Expected behavior**<br />
I expect the Nodeset to be loaded, and the server be accessible via uaexpert, such that I can browse.
**Screenshots**<br />

Screenshot of debugging the `xmlimporter.py` and the method as show above.

so `all_node_ids` has the nodeId's but it does not contain the parent id

output for `ndata` and the values for the `nodeid` and `parent`
**Version**<br />
Python-Version: python 3.8.13<br />
opcua-asyncio Version: asyncua==0.9.98
| xmlimporter loops infinitely when sorting nodes by parentid, when parentid is not found | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1061/comments | 4 | 2022-09-29T20:17:17Z | 2023-03-31T12:12:32Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1061 | 1,391,443,548 | 1,061 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Suggestion or direction how to fix the (de)serializer for the case below are more than welcome.
**Version:**
master d2b48b5a76cb874437651c3894db41a22a25f7a2 (Wed Sep 28 15:11:06 2022 +0200)
**Case:**
Given a nodeset that contains resursive constructions. Like typical tree structures.
Example:
```xml
<UADataType NodeId="ns=1;i=1001" BrowseName="1:MyParameterType">
<DisplayName>MyParameterType</DisplayName>
<References>
<Reference ReferenceType="HasSubtype" IsForward="false">i=22</Reference>
</References>
<Definition Name="1:MyParameterType">
<Field DataType="MyParameterType" ValueRank="1" ArrayDimensions="0" Name="Subparameters"/>
</Definition>
</UADataType>
```
Trying to use the dataclasses generated by `server.load_data_type_definitions`, with method calls and method callbacks.
**Test to validate:**
Add the following test to `tests/test_common.py`:
```python
from asyncua.ua.ua_binary import struct_to_binary
async def test_custom_struct_recursive_serialize(opc):
nodes = await opc.opc.import_xml("tests/custom_struct_recursive.xml")
await opc.opc.load_data_type_definitions()
param =ua.MyParameterType()
bin = struct_to_binary(param)
```
**Problem:**
When MyParameterType is received or send the serialize/deserialize fails due recursive method calls:
```python
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 308, in <listcomp>
encoding_functions = [(f.name, field_serializer(f.type)) for f in data_fields]
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 262, in field_serializer
return create_list_serializer(type_from_list(uatype))
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 372, in create_list_serializer
type_serializer = create_type_serializer(uatype)
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 355, in create_type_serializer
return create_dataclass_serializer(uatype)
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 308, in create_dataclass_serializer
encoding_functions = [(f.name, field_serializer(f.type)) for f in data_fields]
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 308, in <listcomp>
encoding_functions = [(f.name, field_serializer(f.type)) for f in data_fields]
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 262, in field_serializer
return create_list_serializer(type_from_list(uatype))
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 372, in create_list_serializer
type_serializer = create_type_serializer(uatype)
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 355, in create_type_serializer
return create_dataclass_serializer(uatype)
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 308, in create_dataclass_serializer
encoding_functions = [(f.name, field_serializer(f.type)) for f in data_fields]
File "d:\work\opcua-asyncio\asyncua\ua\ua_binary.py", line 308, in <listcomp>
```
**Cause:**
The issue for the serializer is located in `ua_binary.py::create_list_serializer`:
```python
functools.lru_cache(maxsize=None)
def create_list_serializer(uatype) -> Callable[[Any], bytes]:
"""
Given a type, return a function that takes a list of instances
of that type and serializes it.
"""
if hasattr(Primitives1, uatype.__name__):
data_type = getattr(Primitives1, uatype.__name__)
return data_type.pack_array
type_serializer = create_type_serializer(uatype)
none_val = Primitives.Int32.pack(-1)
def serialize(val):
if val is None:
return none_val
data_size = Primitives.Int32.pack(len(val))
return data_size + b''.join(type_serializer(el) for el in val)
return serialize
```
Because the serializer are generated on the fly, it will call resursive `create_type_serializer` of the type of which it is already part.
| Serialize/deserialize of generate dataclasses with recursive structs with load_data_type_definitions fails | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1058/comments | 5 | 2022-09-29T12:12:37Z | 2022-10-02T08:37:59Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1058 | 1,390,766,043 | 1,058 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When the client loses connection to the server, an exception will be caught within `_monitor_server_loop` and is re-raised (see [https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/client/client.py#L447](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/client/client.py#L447)). Additionally, the exception with backtrace is logged because of the `_logger.exception` call. This leads to a rather unpleasant log message which can't be avoided unless logs for asyncua are entirely disabled which I'd rather not do. Would it be possible to not log an exception here (and in `_renew_channel_loop`), but instead maybe log a debug or info message? | _monitor_server_loop and _renew_channel_task spam logs | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1055/comments | 1 | 2022-09-28T12:30:15Z | 2023-06-14T10:55:10Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1055 | 1,389,274,701 | 1,055 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
A script-generated structure has its DataTypeDefinition/BaseDataType written as a BaseDataType (ns=0;i=24) and is written as not abstract.
Generated xml marks BaseDataType as Structure (ns=0;i=22) and as abstract.
**To Reproduce**<br />
1) Create data_type :
```
async def create_ur10_joints(server, idx):
await new_struct(server, idx, "UR10Joints", [
new_struct_field('J1', ua.VariantType.Double),
new_struct_field('J2', ua.VariantType.Double),
new_struct_field('J3', ua.VariantType.Double),
new_struct_field('J4', ua.VariantType.Double),
new_struct_field('J5', ua.VariantType.Double),
new_struct_field('J6', ua.VariantType.Double)
])
await server.load_data_type_definitions()
```
2) Create object type :
```
async def initialize_ur10_object(server, idx):
ur10_obj = await server.nodes.base_object_type.add_object_type(idx, "UR10")
ur10_obj_joints = await ur10_obj.add_variable(idx, "Joints", ua.Variant(ua.UR10Joints(), ua.VariantType.ExtensionObject))
await ur10_obj_joints.set_modelling_rule(True)
await ur10_obj_joints.set_writable()
await server.load_data_type_definitions()
```
3) Instantiate Object:
```
async def instantiate_ur10(server, idx, name):
ur10_obj = await server.nodes.base_object_type.get_child(f'{idx}:UR10')
ur10 = await server.nodes.objects.add_object(idx, name, node._to_nodeid(ur10_obj))
return ur10, target
```
4) Export nodes :
```
nodes = await server.get_root_node().get_children()
customNodes = await LookForNamespaceNodes(nodes, 2)
await server.export_xml(customNodes, "[PATH]\\nodes.xml")
```
```
async def LookForNamespaceNodes(nodes, idx, customNodes = [], ):
for node in nodes:
childNodes = await node.get_children()
if len(childNodes) > 0:
customNodes = await LookForNamespaceNodes(childNodes, idx, customNodes)
namespace = (await node.read_browse_name()).NamespaceIndex
if namespace == idx:
customNodes.append(node)
return customNodes
```
**Expected behavior**<br />
Structure's Subtype is the same in the nodeset.xml and the server.
**Screenshots**<br />
On the server exporting the nodeset :

On the server importing the nodeset :

The UR10 nodeset data type definition :

**Version**<br />
Python-Version: 3.9.4<br />
opcua-asyncio Version : 0.9.97
As i'm only getting started with opcua, I'm not sure which is supposed to be the good version, although I'd favor the first one as I can't seem to read complex types from the server importing the nodeset, while I don't have any problems with the script-generated one.
| Discrepancy between exported xml and created structure | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1051/comments | 1 | 2022-09-26T14:17:42Z | 2022-09-26T15:38:40Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1051 | 1,386,165,166 | 1,051 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When the server sends the certificate chain with its certificate, these lines in create_session are triggered and raise an exception:
```
elif self.security_policy.peer_certificate != response.ServerCertificate:
raise ua.UaError("Server certificate mismatch")
```
**To Reproduce**<br />
Steps to reproduce the behavior incl code:
Try `await client.connect()` to a server which sends its certificate chain with the certificate.
Then try this:
```
await client.connect_socket()
await client.send_hello()
await client.open_secure_channel()
peer_cert = client.security_policy.peer_certificate
client.security_policy.peer_certificate = None
await client.create_session()
client.security_policy.peer_certificate = peer_cert
await client.activate_session()
```
This works because it circumvents the check.
**Expected behavior**<br />
create_session should only check against the certificate, not the entire chain.
**Version**<br />
Python-Version: 3.8.10<br />
opcua-asyncio Version (e.g. master branch, 0.9): 0.9.95 from pip.
| create_session fails if server sends certificate chain | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1045/comments | 3 | 2022-09-21T10:06:26Z | 2023-03-29T07:54:47Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1045 | 1,380,669,963 | 1,045 |
[
"FreeOpcUa",
"opcua-asyncio"
] | # Description
The latest version of the library seems to have problems when reading values from an OPC UA server. Code that worked fine with `asyncua` `0.9.95` now fails with a `TimeoutError`.
# Steps to Reproduce
1. Install [Docker](https://www.docker.com/products/docker-desktop/)
2. Store the following text in a file called `docker-compose.yaml` in a folder of your choice (e.g. `~/Downloads`):
```yaml
version: "3.9"
services:
opcua:
image: mcr.microsoft.com/iot/opc-ua-test-server
command: "-p 4840"
ports:
- "4840:4840"
```
4. Enter the following command in the directory where you stored the file above
```sh
docker compose up
```
5. Install `asyncua-0.9.96`:
```sh
pip install asyncua==0.9.96
```
5. Copy the following code and store it as `test.py`
```py
from asyncio import run
from asyncua import Client
from asyncua.ua import NodeId
async def test():
async with Client(url='opc.tcp://localhost:4840') as client:
node = client.get_node(NodeId('1:CC1001?Input1', 14))
value = await node.read_value()
print(f"Value: {value}")
if __name__ == '__main__':
run(test())
```
6. Run the script
```sh
python test.py
```
# Expected Result
The script finishes successfully and prints the following output:
```
Value: 0.0
```
# Actual Result
The script fails with the following output:
```
Exception raised while parsing message from server
Traceback (most recent call last):
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/client/ua_client.py", line 86, in _process_received_data
msg = self._connection.receive_from_header_and_body(header, buf)
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/common/connection.py", line 404, in receive_from_header_and_body
return self._receive(chunk)
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/common/connection.py", line 426, in _receive
raise ua.UaStatusCodeError(ua.StatusCodes.BadRequestTooLarge)
asyncua.ua.uaerrors._auto.BadRequestTooLarge: "The request message size exceeds limits set by the server."(BadRequestTooLarge)
disconnect_socket was called but connection is closed
Traceback (most recent call last):
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/asyncio/tasks.py", line 456, in wait_for
return fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/rene/Downloads/test.py", line 15, in <module>
run(test())
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/Users/rene/Downloads/test.py", line 8, in test
async with Client(url='opc.tcp://localhost:4840') as client:
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/client/client.py", line 85, in __aenter__
await self.connect()
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/client/client.py", line 277, in connect
await self.open_secure_channel()
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/client/client.py", line 337, in open_secure_channel
result = await self.uaclient.open_secure_channel(params)
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/client/ua_client.py", line 304, in open_secure_channel
return await self.protocol.open_secure_channel(params)
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/site-packages/asyncua/client/ua_client.py", line 224, in open_secure_channel
await asyncio.wait_for(self._send_request(request, message_type=ua.MessageType.SecureOpen), self.timeout)
File "/Users/rene/.pyenv/versions/3.10.6/lib/python3.10/asyncio/tasks.py", line 458, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
```
# Enviornment
Python Version: `3.10.6`
`asyncua` Version: `0.9.96`
# Additional Information
The script works as expected when I use `asyncua` `0.9.95`:
```sh
pip install asyncua==0.9.95
python test.py
# Value: 0.0
``` | Version 0.9.96: Bad Request Too Large Error When Reading Value | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1044/comments | 3 | 2022-09-21T10:03:23Z | 2022-09-21T16:45:41Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1044 | 1,380,665,925 | 1,044 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
We were trying to utilize the FreeOpcUa library to create a server that interfaces with a DIgSILENT PowerFactory ("PF") instance.
Reading and writing values are functional, but reading has to be forced by the PF script. The standard reading mechanism in PF only returns values if it detects changes in the OPC server, which is a behavior that we want to keep.
We also tried running the PF example with the ProSys OPC UA Simulation Server, where the desired behavior is functional. The fact that it works with the ProSys server leads us to believe that there are issues in the configuration of the FreeOpcUa server.
We were wondering if you have any idea on how to change the code in order to replicate the behavior of the ProSys server.
Below is the code that is used to create the server:
```
import os
from random import random
import asyncio
import pandas as pd
from asyncua import ua, Server
type_map = {
2: ua.VariantType.Int32,
4: ua.VariantType.Float
}
class SubHandler(object):
"""
Subscription Handler. To receive events from server for a subscription
"""
def datachange_notification(self, node, val, data):
print("Python: New data change event", node, val)
def event_notification(self, event):
print("Python: New event", event)
async def main():
# now setup our server
server = Server()
await server.init()
server.set_endpoint("opc.tcp://localhost:4840/freeopcua/server/")
server.set_server_name("FreeOpcUa Example Server")
# set all possible endpoint policies for clients to connect through
server.set_security_policy([
ua.SecurityPolicyType.NoSecurity,
ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt,
ua.SecurityPolicyType.Basic256Sha256_Sign])
# setup our own namespace
uri = "http://examples.freeopcua.github.io"
idx = await server.register_namespace(uri)
# load powerfactory configuration into OPC server
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'OPCServerCfg.csv'), 'r') as f:
setup = pd.read_csv(f, skiprows=[0])
objs = server.get_objects_node()
fold = await objs.add_object(idx, 'PF')
for index, row in setup.iterrows():
var = await fold.add_variable(idx, row[1], row[4], type_map[row[3]])
await var.set_writable()
# starting!
async with server:
handler = SubHandler()
sub = await server.create_subscription(500, handler)
myvar = await fold.get_child(f"{idx}:BUS_4_LNE_230KV_LINE_1_P")
handle = await sub.subscribe_data_change(myvar)
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
``` | OPC UA and PowerFactory interaction | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1038/comments | 11 | 2022-09-14T14:19:43Z | 2023-03-29T07:45:27Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1038 | 1,373,070,688 | 1,038 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi, I try to connect an opc server, and when the program starts then this log appears and repeats to try connect to seerver:
ServiceFault (BadTooManySessions, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=None, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None)) from server received in response to CreateSessionRequest
```python
server_state = True
async def opcConnection(server_state, opcServer):
try:
if server_state:
_SERVER_STATE = NodeId(ObjectIds.Server_ServerStatus_State)
opc_url = opcServer
client = Client(opc_url)
print(client)
await client.connect()
client.session_timeout = 20000
server_state = False
return client, server_state
else:
print("opc_server connection Faild !!!")
except:
return None
async def main():
try:
taskOPC = asyncio.create_task(opcConnection(server_state, opcServers[0]))
client, server_state = taskOPC
except:
await main(clientMqtt)
if __name__ == "__main__":
try:
asyncio.run(main(clientMqtt))
except KeyboardInterrupt:
pass
finally:
print("Closing Loop")
```

| ServiceFault from server received in response to CreateSessionRequest | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1037/comments | 13 | 2022-09-13T06:06:10Z | 2023-03-29T07:45:53Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1037 | 1,370,905,864 | 1,037 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Description** <br />
Calling the `register()` method on line 713 of the Node class in [opcua-asyncio](https://github.com/FreeOpcUa/opcua-asyncio)/[asyncua](https://github.com/FreeOpcUa/opcua-asyncio/tree/master/asyncua)/[common](https://github.com/FreeOpcUa/opcua-asyncio/tree/master/asyncua/common)/node.py results in `'TypeError: 'coroutine' object is not subscriptable'`.
**To Reproduce**<br />
```
node = client.get_node(<node_id>) # client may be directly of the class Client, the problem is specifically in the Node class
await node.register()
```
**Expected behavior**<br />
Register node for faster read and write access (if supported by server). Modify the `nodeid` of the node, the original nodeid is
available as `node.basenodeid`.
**Solution**<br />
I think an additional pair brackets is needed for function to work correctly.
now: `nodeid = await self.server.register_nodes([self.nodeid])[0]`
should be: `nodeid = (await self.server.register_nodes([self.nodeid]))[0]`
Similar issue on StackOverflow: https://stackoverflow.com/questions/51459793/python-typeerror-coroutine-object-is-not-subscriptable
**Version**<br />
Python-Version: 3.10
opcua-asyncio Version: master branch | Node class register() method bug | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1035/comments | 0 | 2022-09-10T13:28:37Z | 2022-09-11T08:30:55Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1035 | 1,368,622,471 | 1,035 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ====== Scenario ======
______________________________
[ CNC ] <---> [ client_OPC ]
My acquisition script python use asyncua library and is very similar to the client-substription.py sample script.
The structure is below:
```
import sys
import os
import asyncio
import logging
import Configuration as C
from asyncua import Client, Node
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('asyncua')
class SubscriptionHandler:
"""
The SubscriptionHandler is used to handle the data that is received for the subscription.
"""
def datachange_notification(self, node: Node, val, data):
"""
Callback for asyncua Subscription.
This method will be called when the Client received a data change message from the Server.
"""
logger.info('datachange_notification %r %s', node, val)
async def main():
"""
Main task of this Client-Subscription example.
"""
client_OPC = Client(url=C.url)
async with client:
handler = SubscriptionHandler()
subscription = await client.create_subscription(C.TIME_UPDATE, handler)
await subscription.subscribe_data_change(C.node_list)
await asyncio.sleep(C.TIME_TO_CAPTURE_ACQUISITION)
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
```
I would need automatic reconnection management if the CNC machine is turned off and on again. At the moment I am forced to restart the client-subscription script manually after the CNC is started.
Please do you know if there is a method to check when the server is down? Thanks you in advance. | How to auto-reconnect from client, after restart of CNC machine | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1034/comments | 8 | 2022-09-09T14:39:16Z | 2023-03-29T07:58:11Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1034 | 1,367,929,082 | 1,034 |
[
"FreeOpcUa",
"opcua-asyncio"
] | For reference this is CVE-2022-25304 and GHSA-mfpj-3qhm-976m
GitHub already raised an alert in our sample server implementation.
_Originally posted by @GoetzGoerisch in https://github.com/FreeOpcUa/opcua-asyncio/issues/1013#issuecomment-1234160597_ | CVE-2022-25304 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1023/comments | 6 | 2022-09-07T09:17:53Z | 2022-09-22T11:43:40Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1023 | 1,364,355,536 | 1,023 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
The asyncua does not support **http://opcfoundation.org/UA/** model >1.04.7.
**To Reproduce**<br />
Create a UA model from UAmodeler, with base version 1.04.7 of UA model http://opcfoundation.org/UA/
Export it to a Nodeset.xml (see attached file)
Run the server
```python
async def main():
logging.basicConfig(level=logging.INFO)
server = Server()
await server.init()
# import some nodes from xml
# http://opcfoundation.org/UA/ version 1.04.7 OK
nodes1 = await server.import_xml("server-uamodeler-objecttypes-datatype-1_04_7-v4.xml") # OK Objectype with subobject TransformType -> 3DvectorType et QuaternionType
# http://opcfoundation.org/UA/ version 1.04.11 KO
# nodes1 = await server.import_xml("server-uamodeler-objecttypes-datatype-1_04_7-v4 - 1_04_11.xml") # KO à cause du numéro de version Objectype with subobject TransformType -> 3DvectorType et QuaternionType
# starting!
async with server:
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
```
it works.
Do the exact same thing with http://opcfoundation.org/UA/ version=1.04.11 or above
It does not work
Error is:
Exception has occurred: ValueError
Server doesn't satisfy required XML-Models. Import them first!
**Expected behavior**<br />
Being able to use all versions of UA model
Or
being able to init server with the **Opc.Ua.NodeSet2.xml** used during design phases.
for example by doing:
```python
await server.init("path/to/UAnodeset/1.04.11/Opc.Ua.NodeSet2.xml")
```
**Version**<br />
Python-Version:3.10.4<br />
opcua-asyncio Version (e.g. master branch, 0.9): master branch
Files to test (please modify extension to xml):
[server-uamodeler-objecttypes-datatype-1_04_7-v4 - 1_04_11.xml.txt](https://github.com/FreeOpcUa/opcua-asyncio/files/9495022/server-uamodeler-objecttypes-datatype-1_04_7-v4.-.1_04_11.xml.txt)
[server-uamodeler-objecttypes-datatype-1_04_7-v4.xml.txt](https://github.com/FreeOpcUa/opcua-asyncio/files/9495023/server-uamodeler-objecttypes-datatype-1_04_7-v4.xml.txt)
| OPCUA version not supported "Server doesn't satisfy required XML-Models. Import them first!" | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1019/comments | 8 | 2022-09-06T09:10:23Z | 2023-03-28T18:23:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1019 | 1,362,962,690 | 1,019 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Bug** <br />
With the example of server-with-encryption, it is possible to acces Address Space without encryption and authentication.
I create an issue instead of sending mail following instructions from [How to report a security issue? #902 ](https://github.com/FreeOpcUa/opcua-asyncio/issues/902)
**To Reproduce**<br />
To gain an access to Address Space, we have to send hello message, create a secure channel with security none and create a session (activate the session is not required). After we can try to read and write nodes with regular Read and Write Request.
**Expected behavior**<br />
The expected behaviour would be to require authentication in the application layer (ie session) to provide access to Address Space.
**Version**<br />
Python-Version:Python 3.8.10
opcua-asyncio Version (e.g. master branch, 0.9):
branch master, commit https://github.com/FreeOpcUa/opcua-asyncio/commit/54e54fa6b1383849fac4039f0e9c06902454297c (last commit 29/08/2022)
| Illegal access to Address Space | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1014/comments | 1 | 2022-08-29T14:54:34Z | 2022-09-07T09:17:15Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1014 | 1,354,438,531 | 1,014 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **The bug**
It is possible to create a denial of service by sending a malformed packet. The server will be trap in an infinite loop and consume lot of memory. I create an issue instead of sending mail following instruction from [How to report a security issue? #902 ](https://github.com/FreeOpcUa/opcua-asyncio/issues/902)
**Reproduce**<br />
To reproduce the denial of service, you have to send a packet with a null size.
**Explanation**<br />
The function ```data_received``` in file binary_server_asyncio.py (opcua-asyncio/asyncua/server/binary_server_asyncio.py) continue to work on the same buffer.
```python
def data_received(self, data):
self._buffer += data
# try to parse the incoming data
while self._buffer:
try:
buf = Buffer(self._buffer)
try:
header = header_from_binary(buf)
except NotEnoughData:
logger.debug('Not enough data while parsing header from client, waiting for more')
return
if len(buf) < header.body_size:
logger.debug('We did not receive enough data from client. Need %s got %s', header.body_size,
len(buf))
return
# we have a complete message
self.messages.put_nowait((header, buf))
self._buffer = self._buffer[(header.header_size + header.body_size):]
except Exception:
logger.exception('Exception raised while parsing message from client')
return
```
The value of ```(header.header_size + header.body_size)``` is equal to zero. In the function ```header_from_binary``` in (opcua-asyncio/asyncua/ua/ua_binary.py), the bod_size is equal to zero at the beginning (due to our malformed packet). At the end ```hdr.header_size``` is equal to 12 and ```hdr.body_size``` is equal to -12.
```python
def header_from_binary(data):
hdr = ua.Header()
hdr.MessageType, hdr.ChunkType, hdr.packet_size = struct.unpack("<3scI", data.read(8))
hdr.body_size = hdr.packet_size - 8
if hdr.MessageType in (ua.MessageType.SecureOpen, ua.MessageType.SecureClose, ua.MessageType.SecureMessage):
hdr.body_size -= 4
hdr.ChannelId = Primitives.UInt32.unpack(data)
hdr.header_size = 12
return hdr
```
So in the function ```data_received```, the buffer is never updated, then we are trapped in an infinite loop.
**Version**<br />
Python-Version:Python 3.8.10<br />
opcua-asyncio Version (e.g. master branch, 0.9):
branch master, commit 54e54fa6b1383849fac4039f0e9c06902454297c (last commit 29/08/2022)
| Denial of Service | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1013/comments | 5 | 2022-08-29T14:26:10Z | 2022-09-20T13:45:23Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1013 | 1,354,397,551 | 1,013 |
[
"FreeOpcUa",
"opcua-asyncio"
] | https://reference.opcfoundation.org/v105/Core/docs/Part4/7.2/
https://github.com/FreeOpcUa/opcua-asyncio/blob/280b39b09c6ff59bbb9de25f5453bf23e48ba215/asyncua/ua/uaprotocol_auto.py#L2938-L2939
Suggested improvement: If a string is assigned None, it should have typehint Optional[String]
| None assigned to String Type | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1006/comments | 0 | 2022-08-19T18:59:58Z | 2023-03-29T12:37:01Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1006 | 1,344,802,140 | 1,006 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Trying to write the `value` of a tag in OPC-UA Server, with a `sourceTimestamp` with the following method:
```py
def write_opc_tag(url, tag_id, value):
with Client(url=url) as client:
node = client.get_node(tag_id)
dt = ua.DateTime.utcnow().replace(tzinfo=ua.timezone.utc).astimezone(pytz.timezone("US/Eastern"))
print(dt)
dv = ua.DataValue(ua.Variant(value, VariantType=ua.VariantType.String),
SourceTimestamp=dt)
node.write_value(dv)
print(node.read_value())
```
It's failing with the following error:
`asyncua.ua.uaerrors._auto.BadWriteNotSupported: "The server does not support writing the combination of value, status and timestamps provided."(BadWriteNotSupported)`
I want to understand 2 points
1. Can we publish the value with `SourceTimestamp`, if yes and the above code snippet is correct, could it be the configuration issue on the server side?
2. If we publish the value without `SourceTimestamp`, what is the default `SourceTimestamp` getting set, the time of publishing (set by publisher client), or the time when the server receives the value (set by the server itself)? | Failing while Writing value with sourceTimestamp to OPC-UA Server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/999/comments | 5 | 2022-08-16T14:14:23Z | 2023-03-29T07:58:29Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/999 | 1,340,423,267 | 999 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi ,
I need to connect to a labview opc server, and I can't find any NameSpaces or Identifier for nodes.
Could you tell me how can I get value from this server and it's nodes ?

| Labview OPC server 2016 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/995/comments | 1 | 2022-08-12T16:55:08Z | 2023-03-29T12:36:49Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/995 | 1,337,460,909 | 995 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi,
Can you please suggest your inputs for the below query?
I am trying to use the client API and reading an extension object with nested structures in it. I get Not Enough Data error as shown below. Which configuration parameter can be updated to read a larger blob for the same.
raise NotEnoughData(f"Not enough data left in buffer, request for {size}, we have {self._size}")
asyncua.common.utils.NotEnoughData: Not enough data left in buffer, request for **591983720**, we have **120877**
_Originally posted by @mohitkumaragarwal in https://github.com/FreeOpcUa/opcua-asyncio/discussions/839#discussioncomment-3347668_ | Reading an extension object with nested structures throws NotEnoughData Error | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/994/comments | 5 | 2022-08-10T12:01:34Z | 2022-08-16T09:40:35Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/994 | 1,334,518,778 | 994 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Is there a good reason [DefaultBounds](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/common/node.py#L523) is set to True by default?
It seems more intuitive to set it to False. (or better yet, just make it a required argument) I don't see why people would stream a time range and expect data outside that range. | Should we switch returnBounds to default to False instead? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/989/comments | 5 | 2022-08-05T00:13:27Z | 2023-03-29T08:00:15Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/989 | 1,329,297,637 | 989 |
[
"FreeOpcUa",
"opcua-asyncio"
] | The `AdditionalParametersType` class is missing a `data_type` member variable.
https://github.com/FreeOpcUa/opcua-asyncio/blob/8fffd7e47f01a06c14ef95c41b01eb48cd2a38f7/asyncua/ua/uaprotocol_auto.py#L1572-L1579
Caused by:
https://github.com/FreeOpcUa/opcua-asyncio/blob/8fffd7e47f01a06c14ef95c41b01eb48cd2a38f7/schemas/generate_protocol_python.py#L133-L136
Correct would be:
```
@dataclass(frozen=FROZEN)
class AdditionalParametersType:
"""
https://reference.opcfoundation.org/v105/Core/docs/Part4/7.1
:ivar Parameters:
:vartype Parameters: KeyValuePair
"""
data_type = NodeId(ObjectIds.AdditionalParametersType)
Parameters: List[KeyValuePair] = field(default_factory=list)
```
PR under construction... | Bug in schema generation, uaprotocol_auto.py | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/983/comments | 1 | 2022-08-03T10:54:32Z | 2022-08-16T10:51:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/983 | 1,327,037,835 | 983 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello wise people,
This is my first interaction with github and asyncua, so if a make some mistakes, be patient with me.
I'm tying to make a subscription to an opcua server (in fact it works) but I found two problems along the way.
(i) Sometimes, when a change happends in the server (e.g. one sensor starts to comunicate for first time) I receive an error and the connection closes:
**WARNING:asyncua.client.ua_client.UASocketProtocol:ServiceFault** (BadSessionIdInvalid, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=None, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None)) from server received in response to PublishRequest
**ERROR:asyncua.client.client:Error while renewing session**
Traceback (most recent call last):
File "C:\Users\user1\Python\Python39\lib\site-packages\asyncua\client\client.py", line 413, in _renew_channel_loop
await self.open_secure_channel(renew=True)
File "C:\Users\user1\Python\Python39\lib\site-packages\asyncua\client\client.py", line 306, in open_secure_channel
result = await self.uaclient.open_secure_channel(params)
File "C:\Users\user1\Python\Python39\lib\site-packages\asyncua\client\ua_client.py", line 280, in open_secure_channel
return await self.protocol.open_secure_channel(params)
File "C:\Users\user1\Python\Python39\lib\site-packages\asyncua\client\ua_client.py", line 213, in open_secure_channel
await asyncio.wait_for(self._send_request(request, message_type=ua.MessageType.SecureOpen), self.timeout)
File "C:\Users\user1\Python\Python39\lib\site-packages\asyncua\client\ua_client.py", line 134, in _send_request
self.transport.write(msg)
AttributeError: 'NoneType' object has no attribute 'write'
(ii) When this error happends, the sesion doesn't close well, and in the server, the connection keeps (I only have a limited allowed connections).
My code is:
---------------------------------------- CODE START
```
import sys
sys.path.insert(0, "..")
import os
os.environ['PYOPCUA_NO_TYPO_CHECK'] = 'True'
import asyncio
import logging
from datetime import datetime
from dateutil import tz
import time
import colorama
from colorama import Fore
queue = asyncio.Queue()
from asyncua import Client, Node, ua
logging.basicConfig(level=logging.WARNING)
_logger = logging.getLogger('asyncua')
class SubscriptionHandler:
def datachange_notification(self, node: Node, val, data):
_logger.info('datachange_notification %r %s', node, val)
timestamp_ns = data.monitored_item.Value.SourceTimestamp.timestamp()
quality = data.monitored_item.Value.StatusCode
tagname = node.nodeid.Identifier #Resultado: "DL04.NI_0073.Value"
if (tagname !=2258 ):
queue.put_nowait({'timestamp': timestamp_ns, 'var': tagname, 'value': val, 'statuscode': quality})
else:
print ("...keep alive... server UTC timestamp: " + str(val))
async def main():
ip = "172.16.1.55"
port = "4840"
client = Client(url='opc.tcp://' + ip + ':' + port)
client.session_timeout = 600000
client.set_user('MyUSer')
client.set_password('MyPassword')
dataloggers_array = ["DL01", "DL02", "DL03", "DL04", "DL05", "DL06", "DL07", "DL08", "DL09", "DL10", "DL11", "DL12", "DL13", "DL14", "DL15", "DL16"]
sensors_array = ["LI_0007", "LI_0008", "LI_0072", "NI_0039", "NI_0040", "NI_0041", "NI_0044", "NI_0045", "NI_0046", "NI_0047", "NI_0048", "NI_0056", "NI_0057", "NI_0064", "NI_0065", "NI_0068", "NI_0070", "NI_0073", "NI_0078"]
colorama.init()
async with client:
idx = await client.get_namespace_index('http://opcfoundation.org/UA/')
_logger.info('Namespace index: %s', idx)
var_array = []
for x in range(0, len(dataloggers_array)):
for y in range(0, len(sensors_array)):
try:
var_array.append(await client.nodes.root.get_child(["0:Objects", "2:" + dataloggers_array [x], "2:" + sensors_array[y], "2:Value"]))
except Exception as e1:
s1 = str(e1)
print ("Exception: " + Fore.YELLOW + dataloggers_array [x]+ "." + sensors_array[y] + " " + s1 + Fore.WHITE)
var_array.append(client.get_node(ua.ObjectIds.Server_ServerStatus_CurrentTime))
handler = SubscriptionHandler()
params = ua.CreateSubscriptionParameters()
params.RequestedPublishingInterval = 500
params.RequestedLifetimeCount = 7200
params.RequestedMaxKeepAliveCount = 900
today = datetime.now()
f = open ('C:\\Users\\user1\\workplace\\opcua_sub_all_log.csv','a')
f.write("---SUBSCRIPTION---;---START---;---" + str(today) + "---\n")
f.close()
# We create a Client Subscription.
subscription = await client.create_subscription(params, handler)
print ("INFO: Subscription RUNNING with id:", subscription.subscription_id)
# We subscribe to data changes for two nodes (variables).
await subscription.subscribe_data_change(var_array)
# do things
while True:
data = await queue.get()
# Auto-detect local hour zone
to_zone = tz.tzlocal()
timestamp = data.get('timestamp')
dt_timestamp = datetime.fromtimestamp(timestamp)
dt_timestamp_local = dt_timestamp.astimezone(to_zone)
print ("Event time: " + str(dt_timestamp_local))
f = open ('C:\\Users\\user1\\workplace\\opcua_sub_all_log.csv','a')
toSaveInFile = (str(dt_timestamp_local) + ";" + str(data.get('var')) + ";" + str(data.get('value')) + "\n")
f.write(toSaveInFile)
f.close()
queue.task_done()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```
---------------------------------------- CODE END
How I can treat this problem? If this problem is not avoidable, How can I close the session and the subscription in a proper way?
Thanks in advance guys.
| Two problems with subscription | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/980/comments | 3 | 2022-07-29T10:39:03Z | 2023-03-29T12:35:21Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/980 | 1,322,068,584 | 980 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
**Describe the bug** <br />
Connect to an S7 with opcua-client, client attempts to negotiate a timeout of an hour but gets only 30s.
`asyncua.client.client - WARNING - Requested session timeout to be 3600000ms, got 30000ms instead')`
After 30s client gets BadSessionIdInvalid and crashes.
```
asyncua.client.ua_client.UASocketProtocol - WARNING - ServiceFault (BadSessionIdInvalid, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=None, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None)) from server received in response to ReadRequest')
uawidgets.utils - ERROR - "The session id is not valid."(BadSessionIdInvalid)')
Traceback (most recent call last):
File "/home/jtatsch/.local/lib/python3.8/site-packages/opcua_widgets-0.6.1-py3.8.egg/uawidgets/utils.py", line 21, in wrapper
result = func(self, *args)
File "/home/jtatsch/.local/lib/python3.8/site-packages/opcua_client-0.8.4-py3.8.egg/uaclient/mainwindow.py", line 437, in _update_actions_state
if node.read_node_class() == ua.NodeClass.Method:
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/sync.py", line 94, in wrapper
result = self.tloop.post(aio_func(*args, **kwargs))
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/sync.py", line 52, in post
return futur.result()
File "/usr/lib/python3.8/concurrent/futures/_base.py", line 444, in result
return self.__get_result()
File "/usr/lib/python3.8/concurrent/futures/_base.py", line 389, in __get_result
raise self._exception
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/common/node.py", line 144, in read_node_class
result = await self.read_attribute(ua.AttributeIds.NodeClass)
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/common/node.py", line 302, in read_attribute
result = await self.server.read(params)
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/client/ua_client.py", line 365, in read
data = await self.protocol.send_request(request)
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/client/ua_client.py", line 154, in send_request
self.check_answer(data, f" in response to {request.__class__.__name__}")
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/client/ua_client.py", line 163, in check_answer
hdr.ServiceResult.check()
File "/home/jtatsch/.local/lib/python3.8/site-packages/asyncua-0.9.94-py3.8.egg/asyncua/ua/uatypes.py", line 328, in check
raise UaStatusCodeError(self.value)
asyncua.ua.uaerrors._auto.BadSessionIdInvalid: "The session id is not valid."(BadSessionIdInvalid)
```
**Expected behavior**<br />
I would expect some kind of keep alive mechanism to keep the session alive so it does not become invalid and crash.
**Version**<br />
Python-Version: 3.8<br />
opcua-asyncio Version (e.g. master branch, 0.9): master branch
| BadSessionIdInvalid after 30s | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/977/comments | 5 | 2022-07-28T17:01:46Z | 2023-03-29T08:01:28Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/977 | 1,321,231,480 | 977 |
[
"FreeOpcUa",
"opcua-asyncio"
] | The current implementation of 'Read History' should support reading from multiple nodes instead of just a [single node](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/common/node.py#L523-L569). The client could easily want to read nodes from 1000+ at once and if we just assume an API call took about 1 second per node (as in my case), that would be pretty poor performance.
We can currently implement this ourselves but new users are often unaware of what the OPC-UA spec is and will possibly think they can only read from one node. | Add API call for reading from multiple nodes with 'read history' | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/976/comments | 0 | 2022-07-28T00:06:05Z | 2023-03-29T08:01:50Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/976 | 1,320,239,782 | 976 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
`async def _renew_channel_loop(self)` and the related task created in `async def create_session(self):` does not raise Exceptions correctly. If any exceptions occur within the _renew_channel_loop task, the client stops working but does not crash.
**To Reproduce**<br />
Throw an exception in the "while True" loop of `_renew_channel_loop(self)`
**Expected behavior**<br />
The client should crash which would enable the user to handle it. The exception of the created task `_renew_channel_task` should be raised by e.g. calling `_renew_channel_task.result()`
**Screenshots**<br />

**Version**<br />
Python-Version: 3.9.13
opcua-asyncio Version (e.g. master branch, 0.9): master branch, 0.9.94
| Raise exception of _renew_channel_task correctly | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/974/comments | 2 | 2022-07-27T10:06:57Z | 2022-09-20T17:06:39Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/974 | 1,319,325,553 | 974 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
Im trying to import a simple XML nodeset from UaModeller but I keep getting the following error:
```
Traceback (most recent call last):
File "c:\Users\SVL\OneDrive - University of Cambridge\unified-architecture\opcua-server\xml-server.py", line 25, in <module>
asyncio.run(main())
File "C:\Users\SVL\AppData\Local\Programs\Python\Python39-32\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\SVL\AppData\Local\Programs\Python\Python39-32\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "c:\Users\SVL\OneDrive - University of Cambridge\unified-architecture\opcua-server\xml-server.py", line 15, in main
knauer = await objects.get_child("1:Kanuer")
File "C:\Users\SVL\AppData\Local\Programs\Python\Python39-32\lib\site-packages\asyncua\common\node.py", line 503, in get_child
result.StatusCode.check()
File "C:\Users\SVL\AppData\Local\Programs\Python\Python39-32\lib\site-packages\asyncua\ua\uatypes.py", line 328, in check
raise UaStatusCodeError(self.value)
asyncua.ua.uaerrors._auto.BadNoMatch: "The requested operation has no match to return."(BadNoMatch)
```
My code is based off the example xml-server and comprises of a single object "knauer" and a variable "Pressure" which is being populated with a random number ever 100ms. Simply importing the XML without trying to link to the nodes works with the nodes appearing in UaExpert. However, when I try to link to the nodes using get_child() I get an error?
```
import asyncio
from asyncua import ua, Server
from asyncua.common.methods import uamethod
import random
async def main():
server = Server()
server.set_endpoint('opc.tcp://0.0.0.0:4840')
await server.init()
await server.import_xml(r'opcua-server\p4_1s.xml')
objects = server.nodes.objects
knauer = await objects.get_child("1:Kanuer")
pressure = await knauer.get_child("1:Pressure")
async with server:
while True:
await pressure.write_value(random.random())
await asyncio.sleep(0.1)
if __name__ == '__main__':
asyncio.run(main())
```
My model was generated using UaModeller.
```
<?xml version="1.0" encoding="utf-8"?>
<UANodeSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:uax="http://opcfoundation.org/UA/2008/02/Types.xsd" xmlns="http://opcfoundation.org/UA/2011/03/UANodeSet.xsd" xmlns:s1="http://github.com/om327/unified-automation/Types.xsd" xmlns:ua="http://unifiedautomation.com/Configuration/NodeSet.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<NamespaceUris>
<Uri>http://github.com/om327/unified-automation</Uri>
</NamespaceUris>
<Aliases>
<Alias Alias="Boolean">i=1</Alias>
<Alias Alias="Double">i=11</Alias>
<Alias Alias="String">i=12</Alias>
<Alias Alias="DateTime">i=13</Alias>
<Alias Alias="Organizes">i=35</Alias>
<Alias Alias="HasTypeDefinition">i=40</Alias>
<Alias Alias="HasProperty">i=46</Alias>
<Alias Alias="HasComponent">i=47</Alias>
<Alias Alias="IdType">i=256</Alias>
<Alias Alias="NumericRange">i=291</Alias>
</Aliases>
<Extensions>
<Extension>
<ua:ModelInfo Tool="UaModeler" Hash="oDfr+Nds+p0BjkomhYVqGA==" Version="1.6.6"/>
</Extension>
</Extensions>
<UAObject NodeId="ns=1;i=5001" BrowseName="1:Knauer">
<DisplayName>Knauer</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=58</Reference>
<Reference ReferenceType="HasComponent">ns=1;i=6008</Reference>
<Reference ReferenceType="Organizes" IsForward="false">i=85</Reference>
</References>
</UAObject>
<UAVariable DataType="Double" NodeId="ns=1;i=6008" BrowseName="1:Pressure" AccessLevel="3">
<DisplayName>Pressure</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=63</Reference>
<Reference ReferenceType="HasComponent" IsForward="false">ns=1;i=5001</Reference>
</References>
<Value>
<uax:Double>0</uax:Double>
</Value>
</UAVariable>
<UAObject SymbolicName="http___github_com_om327_unified_automation" NodeId="ns=1;i=5002" BrowseName="1:http://github.com/om327/unified-automation">
<DisplayName>http://github.com/om327/unified-automation</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=11616</Reference>
<Reference ReferenceType="HasComponent" IsForward="false">i=11715</Reference>
<Reference ReferenceType="HasProperty">ns=1;i=6001</Reference>
<Reference ReferenceType="HasProperty">ns=1;i=6002</Reference>
<Reference ReferenceType="HasProperty">ns=1;i=6003</Reference>
<Reference ReferenceType="HasProperty">ns=1;i=6004</Reference>
<Reference ReferenceType="HasProperty">ns=1;i=6005</Reference>
<Reference ReferenceType="HasProperty">ns=1;i=6006</Reference>
<Reference ReferenceType="HasProperty">ns=1;i=6007</Reference>
</References>
</UAObject>
<UAVariable DataType="Boolean" ParentNodeId="ns=1;i=5002" NodeId="ns=1;i=6001" BrowseName="IsNamespaceSubset">
<DisplayName>IsNamespaceSubset</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=68</Reference>
<Reference ReferenceType="HasProperty" IsForward="false">ns=1;i=5002</Reference>
</References>
<Value>
<uax:Boolean>false</uax:Boolean>
</Value>
</UAVariable>
<UAVariable DataType="DateTime" ParentNodeId="ns=1;i=5002" NodeId="ns=1;i=6002" BrowseName="NamespacePublicationDate">
<DisplayName>NamespacePublicationDate</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=68</Reference>
<Reference ReferenceType="HasProperty" IsForward="false">ns=1;i=5002</Reference>
</References>
<Value>
<uax:DateTime>2022-07-22T00:15:42Z</uax:DateTime>
</Value>
</UAVariable>
<UAVariable DataType="String" ParentNodeId="ns=1;i=5002" NodeId="ns=1;i=6003" BrowseName="NamespaceUri">
<DisplayName>NamespaceUri</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=68</Reference>
<Reference ReferenceType="HasProperty" IsForward="false">ns=1;i=5002</Reference>
</References>
<Value>
<uax:String>http://github.com/om327/unified-automation</uax:String>
</Value>
</UAVariable>
<UAVariable DataType="String" ParentNodeId="ns=1;i=5002" NodeId="ns=1;i=6004" BrowseName="NamespaceVersion">
<DisplayName>NamespaceVersion</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=68</Reference>
<Reference ReferenceType="HasProperty" IsForward="false">ns=1;i=5002</Reference>
</References>
<Value>
<uax:String>1.0.0</uax:String>
</Value>
</UAVariable>
<UAVariable DataType="IdType" ParentNodeId="ns=1;i=5002" ValueRank="1" NodeId="ns=1;i=6005" ArrayDimensions="0" BrowseName="StaticNodeIdTypes">
<DisplayName>StaticNodeIdTypes</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=68</Reference>
<Reference ReferenceType="HasProperty" IsForward="false">ns=1;i=5002</Reference>
</References>
</UAVariable>
<UAVariable DataType="NumericRange" ParentNodeId="ns=1;i=5002" ValueRank="1" NodeId="ns=1;i=6006" ArrayDimensions="0" BrowseName="StaticNumericNodeIdRange">
<DisplayName>StaticNumericNodeIdRange</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=68</Reference>
<Reference ReferenceType="HasProperty" IsForward="false">ns=1;i=5002</Reference>
</References>
</UAVariable>
<UAVariable DataType="String" ParentNodeId="ns=1;i=5002" NodeId="ns=1;i=6007" BrowseName="StaticStringNodeIdPattern">
<DisplayName>StaticStringNodeIdPattern</DisplayName>
<References>
<Reference ReferenceType="HasTypeDefinition">i=68</Reference>
<Reference ReferenceType="HasProperty" IsForward="false">ns=1;i=5002</Reference>
</References>
</UAVariable>
</UANodeSet>
```
interestingly there was another error when importing if the following lines were present in the XML:
```
<Models>
<Model ModelUri="http://github.com/om327/unified-automation" PublicationDate="2022-07-22T00:15:42Z" Version="1.0.0">
<RequiredModel ModelUri="http://opcfoundation.org/UA/" PublicationDate="2022-01-24T00:00:00Z" Version="1.05.01"/>
</Model>
</Models>
```
Any help would be fantastic!
Thanks!
| Unable to get_child() from UaModeller xml nodeset | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/973/comments | 8 | 2022-07-22T01:13:06Z | 2023-03-29T08:02:30Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/973 | 1,314,009,388 | 973 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I am trying to use asyncua.sync but the ThreadLoop runs only once, why is that? (I am using version 0.9.94)
I have made a simple test with an OPC UA server that toggles a boolean variable (outBOOL) every second, I found the examples for having a sync Client and made a simple code to be able to read the `outBOOL` variable
My expectation is that the value will be printed every second and therefore show the True, False, True, False, ... sequence but somehow after the first time it stops and executes the line `print('tloop stopped')`, how can I keep the loop running and therefore print the value of the node?
```
import time
from IPython import embed
from IPython.display import clear_output
from asyncua.sync import Client, ThreadLoop
# Create cycle
def sleep(duration, get_now=time.perf_counter):
now = get_now()
end = now + duration
while now < end:
now = get_now()
class SubHandler(object):
"""
Subscription Handler. To receive events from server for a subscription
data_change and event methods are called directly from receiving thread.
Do not do expensive, slow or network operation there. Create another
thread if you need to do such a thing
"""
def datachange_notification(self, node, val, data):
print("Python: New data change event", node, val)
def event_notification(self, event):
print("Python: New event", event)
# Environment variables
ip = '127.0.0.1'
port = '4840'
with ThreadLoop() as tloop:
with Client(f'opc.tcp://{ip}:{port}', tloop = tloop) as client:
clear_output(wait=True)
st = time.time()
print(client.tloop, client.close_tloop)
client.load_data_type_definitions()
node = client.get_node('ns=6;s=::testOPCUA:outBOOL')
print(node.read_value())
sleep(0.5-(time.time() - st))
print('tloop stopped')
```
If I create a subscription and `subscribe_events` also doesn't work, unless I use the `embed()` function, why is that? Is there no way to keep the thread running?
This works:
```
import time
from IPython import embed
from IPython.display import clear_output
from asyncua.sync import Client, ThreadLoop
# Create cycle
def sleep(duration, get_now=time.perf_counter):
now = get_now()
end = now + duration
while now < end:
now = get_now()
class SubHandler(object):
"""
Subscription Handler. To receive events from server for a subscription
data_change and event methods are called directly from receiving thread.
Do not do expensive, slow or network operation there. Create another
thread if you need to do such a thing
"""
def datachange_notification(self, node, val, data):
print("Python: New data change event", node, val)
def event_notification(self, event):
print("Python: New event", event)
# Environment variables
ip = '127.0.0.1'
port = '4840'
#inBOOL = PVNode(client,'ns=6;s=::testOPCUA:outBOOL', 'BOOL')
with ThreadLoop() as tloop:
with Client(f'opc.tcp://{ip}:{port}', tloop = tloop) as client:
clear_output(wait=True)
st = time.time()
print(client.tloop, client.close_tloop)
client.load_data_type_definitions()
node = client.get_node('ns=6;s=::testOPCUA:outBOOL')
handler = SubHandler()
sub = client.create_subscription(500, handler)
handle = sub.subscribe_data_change(node)
sleep(0.5-(time.time() - st))
sub.subscribe_events()
embed() #How to make it work without the embed function?
print('tloop stopped')
```
| ThreadLoop starts and runs only once | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/972/comments | 6 | 2022-07-21T02:58:05Z | 2022-07-25T06:10:03Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/972 | 1,312,415,471 | 972 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I've written a function to recursively get all tags with no children under an OPC-UA node (so all atomic tags, effectively). It stays stable up to 100+ OPC-UA tags, however when I push it to 500+ it throws (apparently) a timeout error (see below error message). What's confusing is that, if I re-run the function once or twice, it will then recursively retrieve the tags just fine.
Because of the nature of my application, I have to run the OPC-UA client globally and have different threads call functions on the client, but none of them should interfere as I only ever work with one thread. I don't believe it's a problem with my use of threading directly, but rather some interaction between the asyncio and threading modules.
**To Reproduce**<br />
The recursive function in question:
```python
def get_tag_definitions(
starting_node, tag_definitions, path='', search_string=''
):
nodes = starting_node.get_children()
for node in nodes:
node_name = node.read_browse_name().to_string()
if path == '':
delimiter = ''
else:
delimiter = ','
node_path = path + delimiter + node_name
if len(node.get_children()) == 0:
node_id = node.aio_obj.nodeid.to_string()
tag_definitions[node_id] = {
'node_id': node_id
}
print(
'Found relevant node: {}'.format(tag_definitions[node_id])
)
else:
get_tag_definitions(
node,
tag_definitions,
path=node_path,
search_string=search_string,
)
```
It's initialized with a lower-level directory within the OPC-UA server (not the root node) and an empty dictionary.
Resulting error message:
```python
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.9/asyncio/tasks.py", line 492, in wait_for
fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "/home/fshriver/test/test.py", line 155, in init_func
dataclient.find_all_tags(profile_name, device_name)
File "/home/fshriver/test/opc_ua_client.py", line 246, in find_all_tags
get_tag_definitions(root_node, all_tags, search_string=name)
File "/home/fshriver/test/opc_ua_client.py", line 110, in get_tag_definitions
nodes = starting_node.get_children()
File "/home/fshriver/testenv/lib/python3.9/site-packages/asyncua/sync.py", line 94, in wrapper
result = self.tloop.post(aio_func(*args, **kwargs))
File "/home/fshriver/testenv/lib/python3.9/site-packages/asyncua/sync.py", line 52, in post
return futur.result()
File "/usr/lib/python3.9/concurrent/futures/_base.py", line 440, in result
return self.__get_result()
File "/usr/lib/python3.9/concurrent/futures/_base.py", line 389, in __get_result
raise self._exception
File "/home/fshriver/testenv/lib/python3.9/site-packages/asyncua/common/node.py", line 348, in get_children
return await self.get_referenced_nodes(refs, ua.BrowseDirection.Forward, nodeclassmask)
File "/home/fshriver/testenv/lib/python3.9/site-packages/asyncua/common/node.py", line 421, in get_referenced_nodes
references = await self.get_references(refs, direction, nodeclassmask, includesubtypes)
File "/home/fshriver/testenv/lib/python3.9/site-packages/asyncua/common/node.py", line 401, in get_references
results = await self.server.browse(params)
File "/home/fshriver/testenv/lib/python3.9/site-packages/asyncua/client/ua_client.py", line 342, in browse
data = await self.protocol.send_request(request)
File "/home/fshriver/testenv/lib/python3.9/site-packages/asyncua/client/ua_client.py", line 145, in send_request
data = await asyncio.wait_for(self._send_request(request, timeout, message_type), timeout if timeout else None)
File "/usr/lib/python3.9/asyncio/tasks.py", line 494, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
```
**Expected behavior**<br />
Like I said, there are only 520 tags in total, and they're all located under a single folder (the root node I pass in), so I don't expect there to be a huge issue even trawling through a bunch of paths, much less dealing with this number of tags. I'm not entirely sure what the issue is with threading here.
**Version**<br />
Python-Version: 3.9.2 <br />
opcua-asyncio Version: 0.9.94
| Timeout using sync client for recursive tag discovery | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/968/comments | 1 | 2022-07-16T16:40:31Z | 2023-03-29T08:04:44Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/968 | 1,306,851,381 | 968 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When importing a TIA Portal generated xml file the following error appears for like every node:
```
INFO:asyncua.common.xmlparser:Not implemented tag: <Element '{http://opcfoundation.org/UA/2011/03/UANodeSet.xsd}Extensions' at 0x7fb522dcac00>
```
Maybe as a result of this these nodes are not visible for browsing with the gui.
opcua-asyncio Version : master branch
| xmlparser cannot parse TIA Portal xml due to Not implemented tag: <Element '{http://opcfoundation.org/UA/2011/03/UANodeSet.xsd}Extensions' | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/967/comments | 2 | 2022-07-16T08:51:37Z | 2023-03-31T12:11:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/967 | 1,306,751,407 | 967 |
[
"FreeOpcUa",
"opcua-asyncio"
] | In my fork of python-opcua for both SelectClauses and WhereClauses, I had to define TypeDefinitionId with the BaseEventType.
```
op.TypeDefinitionId = NodeId(identifier=ua.ObjectIds.BaseEventType, namespaceidx=0, nodeidtype=NodeIdType.Numeric)
```
Without this, subscribing to events was broken. The server would return the same error message for all the select clauses `BadTypeDefinitionError: "'"The type definition node id does not reference an appropriate type node."'` | Subscribing to events requires TypeDefinitionId in some cases | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/964/comments | 2 | 2022-07-12T15:54:58Z | 2022-07-18T08:58:54Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/964 | 1,302,256,174 | 964 |
[
"FreeOpcUa",
"opcua-asyncio"
] | My server uses the following identifier "ns=3;s=EquipSetParam(E=93;SP=204)" to identify object parameters. when I get a node, the identifier is truncated to something like this "ns=3;s=EquipSetParam(E=93", so I can't get the node and data. I looked at the source code of the package, there is a semicolon separation. What should I do to start get data by my IDs? | NodeID string is truncated | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/962/comments | 2 | 2022-07-12T09:36:20Z | 2023-03-29T12:34:04Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/962 | 1,301,803,072 | 962 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello! Following the discussion on Gitter I figured I should summarize my findings an add an example to reproduce the problem.
I've observed that when moving from asyncua 0.8.4 to the latest 0.9.9X the servers take substantially longer to start.
**To Reproduce**<br />
I included a minimal server as well as an example server import file here: [example.zip](https://github.com/FreeOpcUa/opcua-asyncio/files/9090982/example.zip).
The script itself just initializes a server, imports data from a file, starts and stops.
```python
import asyncio
import pathlib
from time import time
from asyncua import Server
cur_dir = pathlib.Path(__file__).parent.resolve()
example_import_xml = cur_dir / "example.xml"
async def main():
start = time()
server = Server()
await server.init()
server.set_endpoint('opc.tcp://0.0.0.0:4841/freeopcua/server/')
time_init = time()
await server.import_xml(path=example_import_xml)
time_import_xml = time()
await server.start()
await server.stop()
stop = time()
duration_init = time_init - start
duration_import_xml = time_import_xml - time_init
total = stop - start
print("init {:.3f} s, import {:.3f} s, total {:.3f} s".format(duration_init, duration_import_xml, total))
if __name__ == "__main__":
asyncio.run(main())
```
**Benchmarks**<br />
| | init (sec) | import (sec) | total (sec) |
|--------|------------|--------------|-------------|
| 0.8.4 | 1.203 | 2.063 | 3.266 |
| 0.9.94 | 2.359 | 119.655 | 123.062 |
It seems that `import_xml` is now taking close to 60 times more than previously.
I'll add the profiling results in a comment soon.
**Version**<br />
Python-Version:3.9.10 (but also reproduced on 3.10)<br />
opcua-asyncio Version (e.g. master branch, 0.9): 0.9.94 (master) | Server import_xml performance downgrade from 0.8.4 to 0.9.94 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/961/comments | 11 | 2022-07-12T08:25:57Z | 2022-07-16T07:49:24Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/961 | 1,301,720,816 | 961 |
[
"FreeOpcUa",
"opcua-asyncio"
] | https://github.com/FreeOpcUa/opcua-asyncio/blob/0f4f68cdaee8a5a9ba193272876a1c7ac66937eb/asyncua/crypto/security_policies.py#L555-L556
`client_pk` is in fact the private key for the host certificate and as such `host_pk` should be a better name. | SecurityPolicyBasic256: confusing argument name | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/960/comments | 4 | 2022-07-10T09:02:19Z | 2023-03-29T12:33:32Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/960 | 1,299,868,108 | 960 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ### Please read, before you post!
This is a _**BUG REPORT for issues in the existing code**_.
If you have general questions, code handling problems or ideas, please use the:
Discussionsboard: https://github.com/FreeOpcUa/opcua-asyncio/discussions <br/> or <br />
Gitter-Channel: https://gitter.im/FreeOpcUa/opcua-asyncio
---
To save some time, please provide us following informations, if possible:
**Describe the bug** <br />
A clear and concise description of what the bug is.
export_xml generates a dateTime value such as '2021-09-22 00:00:00+00:00'. Should be '2021-09-22T00:00:00+00:00' according to w3 standards (noticed trying to import generated xml to SIOME)
**To Reproduce**<br />
Steps to reproduce the behavior incl code:
**Expected behavior**<br />
A clear and concise description of what you expected to happen.
**Screenshots**<br />
If applicable, add screenshots to help explain your problem. <br />
You can post Screenshots directly to github, please don't use 3rd Party webpages
**Version**<br />
Python-Version:<br />
opcua-asyncio Version (e.g. master branch, 0.9):
| export_xml generates incorrect data time format | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/959/comments | 1 | 2022-07-09T15:51:59Z | 2023-03-29T12:33:19Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/959 | 1,299,710,988 | 959 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When connecting to a Siemens s7 opcua crashes here on a string within a string:
```
asyncua/common/structures104.py", line 284, in _generate_object
exec(code, env)
File "<string>", line 10
data_type = ua.NodeId.from_string("ns=3;s=DT_"LCB_15x_ActuatorSpeed_B_1"."scInternalCtrl"")
^
SyntaxError: invalid syntax
It seems the culprit is using the non pythonized "LCB_15x_ActuatorSpeed_B_1"."scInternalCtrl" instead of _LCB_15x_ActuatorSpeed_B_1_scInternalCtrl_ may be the culprit here?
happens on opcua-asyncio master branch
| asyncua/common/structures104.py", line 284, in _generate_object doesnt properly sanitize node name | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/957/comments | 12 | 2022-07-07T15:27:36Z | 2022-07-14T17:02:10Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/957 | 1,297,640,898 | 957 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello
I can get all nodes and there parent, but i want to store them like a tree network.
Have anyone any suggestion ?

| How to get all node's parents and store them one after another ? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/955/comments | 0 | 2022-07-04T08:29:32Z | 2023-03-29T12:33:07Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/955 | 1,292,817,674 | 955 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi
I want to connect to Prosys opcua server simulation, and i need to find all nodes on server.so i use ua_utils.get_node_children(client.nodes.objects) but I get this error:
_'NoneType' object has no attribute 'send_request'_
//////////////////////////////
```ruby
import logging
import asyncio
from asyncua import Client , Node ,ua
from asyncua.common import ua_utils
async def main():
client = Client("opc.tcp://localhost:53530/OPCUA/SimulationServer/")
client.session_timeout = 2000
root = client.nodes.root
while True:
allVariables = []
node_List = await ua_utils.get_node_children(client.nodes.objects)
for i in node_List:
nodeClass = await i.read_node_class()
if nodeClass == ua.NodeClass.Variable:
allVariables.append(n)
print(allVariables)
await asyncio.sleep(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.WARN)
asyncio.run(main())
```
//////////////////////////////

| Unable to find all nodes by ua_utils.get_node_children() | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/952/comments | 31 | 2022-06-27T13:17:23Z | 2025-03-26T09:36:24Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/952 | 1,285,795,596 | 952 |
[
"FreeOpcUa",
"opcua-asyncio"
] | @ZuZuD the HA client seems broken again: https://github.com/FreeOpcUa/opcua-asyncio/runs/7048622278?check_suite_focus=true
not sure what is happening, all merged requests I merged passed (As far as I remember) | HA client tests seems to fail on python 3.10 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/950/comments | 1 | 2022-06-25T17:17:23Z | 2022-06-28T09:29:24Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/950 | 1,284,663,621 | 950 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Using the example server-custom-structures-and-enums.py we have 2 struct definitions like
snode1, _ = await new_struct(server, idx, "MyStruct", [
new_struct_field("MyBool", ua.VariantType.Boolean),
new_struct_field("MyUInt32List", ua.VariantType.UInt32, array=True),
])
snode3, _ = await new_struct(server, idx, "MyNestedStruct", [
new_struct_field("MyStructArray", snode1, array=True),
new_struct_field("UUID", ua.VariantType.String),
])
snode3 uses a field of type snode1. When looking at the generated XML code we have the following:
```
<UADataType NodeId="ns=1;i=1" BrowseName="1:MyStruct">
<DisplayName>MyStruct</DisplayName>
<Description>MyStruct</Description>
<References>
<Reference ReferenceType="HasSubtype" IsForward="false">i=22</Reference>
<Reference ReferenceType="HasEncoding">ns=1;i=2</Reference>
</References>
<Definition Name="MyStruct">
<Field Name="MyBool" DataType="i=1" />
<Field Name="MyUInt32List" DataType="i=7" ValueRank="0" ArrayDimensions="1" />
</Definition>
</UADataType>
<UADataType NodeId="ns=1;i=5" BrowseName="1:MyNestedStruct">
<DisplayName>MyNestedStruct</DisplayName>
<Description>MyNestedStruct</Description>
<References>
<Reference ReferenceType="HasSubtype" IsForward="false">i=22</Reference>
<Reference ReferenceType="HasEncoding">ns=1;i=6</Reference>
</References>
<Definition Name="MyNestedStruct">
<Field Name="MyStructArray" DataType="ns=2;i=1" ValueRank="0" ArrayDimensions="1" />
<Field Name="UUID" DataType="i=12" />
</Definition>
</UADataType>
```
The MyStruct data type has node id : ns=1;i=1. The MyNestedStruct data type has node id ns=1;i=5.
If we look at the definition of the field MyStructArray, we see it refers to DatatType ns=2;i=1, but this node does not exists. Importing this into UA modeler for example gives an error. I think the DataType reference should be ns1;i=1.
Used asyncua 0.9.4, python 3.9.9
| XML generated reference seems incorrect for Datatype in nested struct | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/945/comments | 2 | 2022-06-22T08:34:39Z | 2022-07-17T19:52:18Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/945 | 1,279,782,408 | 945 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Using opcua-asyncio server works perfectly without encryption and OPCUA expert as client.
First without any encryption (no security policy set), and changing publishing interval works without problem.
Then when a security policy is set like
`server.set_security_policy([ua.SecurityPolicyType.Basic256Sha256_SignAndEncrypt], permission_ruleset=SimpleRoleRuleset())`
It still works, but as soon you try to change the publishing interval it fails with an error.
I found out that in the file crypto/permission_rules.py in the class SimpleRoleRuleset, we have a method check_validity.
This method fails because UAExpert asks for the 2 following requests:
ua.ObjectIds.ModifySubscriptionRequest_Encoding_DefaultBinary,
ua.ObjectIds.TransferSubscriptionsRequest_Encoding_DefaultBinary
I've added those in the READ_TYPES array, and now the error is gone.
The version i've used is
**asyncua Version** 0.9.94
**Python-Version**: 3.9.9<br />
Thanks!
| UAexpert: change publishing interval & encrypted sessions fails | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/942/comments | 2 | 2022-06-21T09:26:40Z | 2022-06-21T11:44:37Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/942 | 1,278,160,587 | 942 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
I have an OPC.xml dumped from a Siemens s7 I would like to load, so I can simulate it and work on it.
When I try to load it looks okay except for that one warning:
```
...
INFO:asyncua.common.xmlimporter:Importing xml node (QualifiedName(NamespaceIndex=2, Name='REMOTE'), NodeId(Identifier=3066, NamespaceIndex=2, NodeIdType=<NodeIdType.Numeric: 2>)) as (QualifiedName(NamespaceIndex=2, Name='REMOTE') NodeId(Identifier=3066, NamespaceIndex=2, NodeIdType=<NodeIdType.Numeric: 2>))
WARNING:asyncua.common.xmlimporter:failure adding node NodeData(nodeid:NodeId(Identifier=3066, NamespaceIndex=2, NodeIdType=<NodeIdType.Numeric: 2>))
WARNING:asyncua:"The parent node id does not to refer to a valid node."(BadParentNodeIdInvalid)
INFO:asyncua:Starting server!
WARNING:asyncua.server.server:Endpoints other than open requested but private key and certificate are not set.
INFO:asyncua.server.internal_server:starting internal server
INFO:asyncio:<Server sockets=(<asyncio.TransportSocket fd=6, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 4840)>,)> is serving
INFO:asyncua.server.binary_server_asyncio:Listening on 127.0.0.1:4840
DEBUG:asyncua.server.server:OPC UA Server(opc.tcp://127.0.0.1:4840) server started
```
But when I inspect the contents on the server with the opcua-client I cannot find any of the defined nodes/variables etc.
**To Reproduce**<br />
My XML is imported like this:
```
async def main():
server = Server()
await server.init()
await server.import_xml("OPC.xml")
server.set_endpoint('opc.tcp://127.0.0.1:4840')
async with server:
while True:
await asyncio.sleep(1)
```
In the xml node 3065 got parsed just fine but 3066 doesn't have a references node.
Maybe that causes the warning and cancels the parsing altogether?
```
<UADataType NodeId="ns=1;i=3065" BrowseName="1:ANY">
<DisplayName>ANY</DisplayName>
<References>
<Reference ReferenceType="HasSubtype">ns=1;i=3066</Reference>
<Reference ReferenceType="HasSubtype" IsForward="false">i=3</Reference>
</References>
</UADataType>
<UADataType NodeId="ns=1;i=3066" BrowseName="1:REMOTE">
<DisplayName>REMOTE</DisplayName>
</UADataType>
```
And the opcua-client also shows 2 warnings which may be related?
```
asyncua.client.client - WARNING - Deprecated since spec 1.04, call load_data_type_definitions')
asyncua.client.client - WARNING - Deprecated since spec 1.04, call load_data_type_definitions')
```
**Expected behavior**<br />
I expect to see the same nodes/variables as defined in the s7.
**Version**<br />
Python-Version: 3.10
opcua-asyncio Version: master
OPC.xml generated by Generator Product="TIA Portal" Edition="STEP 7 - Server Interface Generation" Version="V1.0.0"
| asyncua.common.xmlimporter: failure adding node NodeData | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/941/comments | 10 | 2022-06-20T19:13:39Z | 2022-07-18T19:57:49Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/941 | 1,277,299,471 | 941 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi, I couldn't find this in the docs or examples:
On server side I created some node that is made writable ` await mynode.set_writable(True)`. The client can now change it and I want to listen to that change on server side. How to listen to a change value of a node on server side?
| Listening to a change in a writable value server side | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/936/comments | 2 | 2022-06-16T09:37:27Z | 2023-03-29T12:31:47Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/936 | 1,273,309,627 | 936 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
If you set the client certificate ahead of activating the session, the method "Client.activate_session() overrides previously set client certificate.
**To Reproduce**<br />
```
client = Client(url=url)
client.application_uri = "python-opcua"
await client.load_private_key(user_key_file)
await client.load_client_certificate(user_cert_file)
await client.set_security(
policy=SecurityPolicyBasic256Sha256,
mode=MessageSecurityMode.SignAndEncrypt,
certificate=app_cert_file,
private_key=app_key_file,
)
try:
await client.connect_socket()
await client.send_hello()
await client.open_secure_channel()
await client.create_session()
await client.activate_session()
```
**Expected behavior**<br />
The call of Client.activate_session() without arguments does not override a previously set user certificate.
**Screenshots**<br />
Exception caught "The user identity token is not valid."(BadIdentityTokenInvalid)
**Version**<br />
Python-Version: 3.10.4<br />
opcua-asyncio Version (e.g. master branch, 0.9):
latest on master | Client.activate_session() overrides previously set client certificate | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/929/comments | 0 | 2022-06-14T11:02:01Z | 2022-06-24T20:22:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/929 | 1,270,629,803 | 929 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When calling Node.read_value() on a property the following error is thrown:
_Exception caught Not enough data in buffer, request of 4, we have 0._
The recent change in uatypes line 953 leads to the described error.
The current code leads to the described error:
```
@dataclass(frozen=True)
class DataValue:
...
Value: Variant = field(default_factory=Variant)
...
```
The old code works:
```
@dataclass(frozen=True)
class DataValue:
...
Value: Optional[Variant] = None
...
```
**To Reproduce**<br />
Just call read_value() on a property node,
**Expected behavior**<br />
Read the value of the property node.
**Version**<br />
Python-Version: 3.10.4 <br />
opcua-asyncio Version (e.g. master branch, 0.9):
latest on master | Node.read_value() does not work any more due to recent change in uatypes.py | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/928/comments | 12 | 2022-06-14T08:30:22Z | 2022-06-24T20:27:16Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/928 | 1,270,446,183 | 928 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
I've been working on integrating some asyncio servers with LabVIEW's SystemLink OPC UA plug-in.
Following a couple of service requests we've noticed that there is a slight difference how DataType is represented. In the older opcua-python library this is represended as, for example 'String' or 'Double'. The asyncio version seems to display DataType as an ENUM for example i=12 (string). Is there a reason for this change and is it possible to enforce a particular format for DataType as it seems to prevent some clients from connecting?
Many thanks! | DataType syntax | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/926/comments | 21 | 2022-06-10T14:12:20Z | 2023-03-29T08:03:35Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/926 | 1,267,612,297 | 926 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I have a very simple OPC-UA server, a "blackbox" client send data to this server and everything is working fine except the timestamp.
When I add value to a variable using set_value, the source timestamp is updated. However when the client write data value, the Source Timestamp is replaced by 01:00:00:000.
The Server timestamp stay at the value (01:00:00:000) whatever I write value from the python code or from outside.
Is there a way to update the Server Timestamp or source timestamp when values are written from outside the python code ? | ServerTimestamp not updated when data are written from outside | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/925/comments | 2 | 2022-06-10T08:34:29Z | 2022-06-15T09:46:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/925 | 1,267,236,861 | 925 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When executed under Windows 10 the "client-with-encryption.py" example throws the following error:
```
.../opcua-asyncio/examples/client-with-encryption.py
INFO:asyncua.client.client:connect
INFO:asyncua.client.ua_client.UaClient:opening connection
Traceback (most recent call last):
File "...\opcua-asyncio\examples\client-with-encryption.py", line 41, in <module>
main()
File "...\opcua-asyncio\examples\client-with-encryption.py", line 36, in main
loop.run_until_complete(task(loop))
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "...\opcua-asyncio\examples\client-with-encryption.py", line 25, in task
async with client:
File "...\opcua-asyncio\examples\..\asyncua\client\client.py", line 69, in __aenter__
await self.connect()
File "...\opcua-asyncio\examples\..\asyncua\client\client.py", line 252, in connect
await self.connect_socket()
File "...\opcua-asyncio\examples\..\asyncua\client\client.py", line 279, in connect_socket
await self.uaclient.connect_socket(self.server_url.hostname, self.server_url.port)
File "...\opcua-asyncio\examples\..\asyncua\client\ua_client.py", line 279, in connect_socket
await asyncio.wait_for(asyncio.get_running_loop().create_connection(protocol, host, port),
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 481, in wait_for
return fut.result()
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1056, in create_connection
raise exceptions[0]
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1041, in create_connection
sock = await self._connect_sock(
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 955, in _connect_sock
await self.sock_connect(sock, address)
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 702, in sock_connect
return await self._proactor.connect(sock, address)
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 812, in _poll
value = callback(transferred, key, ov)
File "...\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 599, in finish_connect
ov.getresult()
OSError: [WinError 1214] Das Format des angegebenen Netzwerknamens ist unzulässig
```
The error translates to "The format of the specified network name is invalid".
I tested the same example script using a ubuntu vm and did not get any errors.
**To Reproduce**<br />
Execute the example script "client-with-encryption.py" on Windows 10.
**Expected behavior**<br />
The client connects to the server of example file "server-with-encryption.py".
**Screenshots**<br />
If applicable, add screenshots to help explain your problem. <br />
You can post Screenshots directly to github, please don't use 3rd Party webpages
**Version**<br />
Python-Version: 3.9.6<br />
opcua-asyncio Version (e.g. master branch, 0.9): master branch, commit af45287235f65466110cd88e71d0005b454efb5d [af45287] of Tuesday 7. June 2022 12:56:07
. | Client with encrpytion example not working under windows because of path delimiter | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/922/comments | 1 | 2022-06-09T16:29:46Z | 2022-06-10T12:06:36Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/922 | 1,266,388,444 | 922 |
[
"FreeOpcUa",
"opcua-asyncio"
] | <br />
Using the example server-custom-structures-and-enums.py and changing the code like
mynode = await server.nodes.objects.add_variable(idx, "my_struct", ua.Variant(ua.MyStruct(), ua.VariantType.ExtensionObject))
and then adding the mynode variable in the list of nodes to export to xml with:
await server.export_xml([server.nodes.objects, server.nodes.root, snode1, snode2, snode3, enode, valnode, mynode], "structs_and_enum.xml")
in the generated xml it generates wrong syntax inside the UAVariable element that describes my_struct node
`
<Value>
<uax:ExtensionObject>
<uax:TypeId>
<uax:Identifier>ns=2;i=1</uax:Identifier>
</uax:TypeId>
<uax:Body>
<uax:ns=1;i=1>
<uax:MyBool>true</uax:MyBool>
<uax:MyUInt32List />
</uax:ns=1;i=1>
</uax:Body>
</uax:ExtensionObject>
</Value>
`
The line <uax:ns=1;i=1> inside the uax:Body element is not correctly generated, a syntax checker for xml fails on it.
Python-Version: 3.9.9<br />
opcua-asyncio Version : 0.9.94
[examples.zip](https://github.com/FreeOpcUa/opcua-asyncio/files/8868042/examples.zip)
| Export xml generates invalid xml with variables of type ExtensionObject | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/921/comments | 2 | 2022-06-09T07:43:39Z | 2023-03-29T12:31:14Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/921 | 1,265,729,908 | 921 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ```python
asyncua/common/statemachine.py:188: error: "BaseEvent" has no attribute "Message"
asyncua/common/statemachine.py:189: error: "BaseEvent" has no attribute "Severity"
asyncua/common/statemachine.py:190: error: "BaseEvent" has no attribute "ToState"
asyncua/common/statemachine.py:192: error: "BaseEvent" has no attribute "Transition"
asyncua/common/statemachine.py:193: error: "BaseEvent" has no attribute "FromState"
``` | check StateMachine.change_state | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/915/comments | 1 | 2022-06-06T20:17:16Z | 2023-03-29T12:30:56Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/915 | 1,262,362,360 | 915 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
type `OpenSecureChannelResponse` has no member `RequestType`
```python
self._open_secure_channel_exchange = struct_from_binary(ua.OpenSecureChannelResponse, msg.body())
self._open_secure_channel_exchange.ResponseHeader.ServiceResult.check()
self._connection.set_channel(self._open_secure_channel_exchange.Parameters, params.RequestType, params.ClientNonce)
```
maybe `OpenSecureChannelParameters` is correct
```python
self._open_secure_channel_exchange = struct_from_binary(ua.OpenSecureChannelParameters, msg.body())
``` | UASocketProtocol._process_received_data check _open_secure_channel_exchange | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/914/comments | 1 | 2022-06-06T19:36:40Z | 2022-06-10T06:14:59Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/914 | 1,262,303,114 | 914 |
[
"FreeOpcUa",
"opcua-asyncio"
] | static code analyse with mypy complains in the following places:
`"NodeId" has no attribute "read_browse_name"`
- [x] https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/common/events.py#L176
- [x] https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/common/events.py#L178 | select_clauses_from_evtype, "NodeId" has no attribute "read_browse_name" | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/909/comments | 1 | 2022-06-06T11:44:13Z | 2022-06-06T17:01:52Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/909 | 1,261,733,242 | 909 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I tried connecting to a server using a security certificate with the correct configuration options and got a security error
`"The security policy does not meet the requirements set by the server."(BadSecurityPolicyRejected).`
The same certificate and corresponding code worked using the deprecated `python-opcua` library.
**To Reproduce**<br />
* Create a certificate using the [provided script](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/examples/generate_certificate.sh)
* Run the following code specifying the server configuration:
```
import asyncio
from asyncua import Client
URL = ###
URI = ###
POLICY = "Basic256Sha256"
MODE = "SignAndEncrypt"
CERTIFICATE_PATH = "client_cert.der"
PRIVATE_KEY_PATH = "client_private_key.pem"
SECURITY_STRING = ",".join([POLICY, MODE, CERTIFICATE_PATH, PRIVATE_KEY_PATH])
async def run_client(url: str, uri: str, security_string: str):
client = Client(url=url)
client.application_uri = uri
await client.set_security_string(security_string)
async with Client(url=url) as client:
while True:
print("Children of root are: %r", await client.nodes.root.get_children())
await asyncio.sleep(1.)
# do something
if __name__ == '__main__':
asyncio.run(
run_client(url=URL, uri=URI, security_string=SECURITY_STRING)
)
```
**Expected behavior**<br />
The expected behaviour is to get the following error when I first try and connect:
`Connection failed. BadSecurityChecksFailed: An error occurred verifying security.`
This error means the server needs to trust the certificate and then I can establish a connection.
The same server configuration and certificate worked using the deprecated library `python-opcua`. Code below:
```
from opcua import Client
URL = ###
URI = ###
POLICY = "Basic256Sha256"
MODE = "SignAndEncrypt"
CERTIFICATE_PATH = "client_cert.der"
PRIVATE_KEY_PATH = "client_private_key.pem"
SECURITY_STRING = ",".join([POLICY, MODE, CERTIFICATE_PATH, PRIVATE_KEY_PATH])
def run_client(url: str, uri: str, security_string: str):
client = Client(url=url)
client.set_security_string(security_string)
client.application_uri = uri
try:
client.connect()
idx = client.get_namespace_index(uri)
print(f"idx: {idx}")
root = client.get_root_node()
print(f"Root: {root}")
print(f"Root children: {root.get_children()}")
finally:
client.disconnect()
if __name__ == '__main__':
run_client(url=URL, uri=URI, security_string=SECURITY_STRING)
```
**Version**<br />
`Python` version: `3.8`
`opcua-asyncio` version: `0.9.92`
`python-opcua` version: `0.98.13`
| BadSecurityPolicyRejected - same policy works with python-opcua library | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/907/comments | 2 | 2022-06-06T08:20:23Z | 2022-06-06T16:31:40Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/907 | 1,261,513,157 | 907 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I see that in https://github.com/FreeOpcUa/opcua-asyncio/pull/415 we added support for variables with properties but it looks like we're still missing `NodeClass.Object` in that filter. These can then contain their own properties, variables, or nested objects.
| Add event support for nested objects (NodeClass.Object) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/905/comments | 6 | 2022-06-03T19:40:24Z | 2022-06-08T18:46:24Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/905 | 1,260,296,544 | 905 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I was looking at the logic for how event attributes get added when you subscribe to them and don't quite understand why the child event includes the attributes of it's parents.
Isn't the other way around (Parent including the attributes of all its children) more intuitive?
This seems like a bug to me | Why does subscribing to child events process through its parent for attributes? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/904/comments | 7 | 2022-05-26T00:27:14Z | 2022-06-07T00:45:20Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/904 | 1,248,942,452 | 904 |
[
"FreeOpcUa",
"opcua-asyncio"
] | We would like to responsibly report on a vulnerability we found in python opcua-asyncio. Where should we send our detailed report?
Additionally I would like to suggest adding a security policy to the repository to help other security researchers reach out to you properly.
Thanks!
Team82 Claroty Research
https://claroty.com/team82/ | How to report a security issue? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/902/comments | 4 | 2022-05-23T13:18:09Z | 2022-09-20T13:47:08Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/902 | 1,245,158,560 | 902 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When I initially connect to a Siemens S7 using the gui it dies due to this:
```
uawidgets.utils - ERROR - Unknown datatype for field: StructureField(Name='awInt', Description=LocalizedText(Locale=None, Text=None), DataType=NodeId(Identifier=3002, NamespaceIndex=3, NodeIdType=<NodeIdType.FourByte: 1>), ValueRank=1, ArrayDimensions=[3], MaxStringLength=0, IsOptional=False) in structure:_some_structure_, please report')
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/uawidgets/utils.py", line 21, in wrapper
result = func(self, *args)
File "/home/user/.local/lib/python3.8/site-packages/uaclient/mainwindow.py", line 354, in connect
self.uaclient.connect(uri)
File "/home/user/.local/lib/python3.8/site-packages/uaclient/uaclient.py", line 126, in connect
self.client.load_data_type_definitions()
File "/home/user/.local/lib/python3.8/site-packages/asyncua/sync.py", line 94, in wrapper
result = self.tloop.post(aio_func(*args, **kwargs))
File "/home/user/.local/lib/python3.8/site-packages/asyncua/sync.py", line 52, in post
return futur.result()
File "/usr/lib/python3.8/concurrent/futures/_base.py", line 444, in result
return self.__get_result()
File "/usr/lib/python3.8/concurrent/futures/_base.py", line 389, in __get_result
raise self._exception
File "/home/user/.local/lib/python3.8/site-packages/asyncua/client/client.py", line 676, in load_data_type_definitions
return await load_data_type_definitions(self, node, overwrite_existing=overwrite_existing)
File "/home/user/.local/lib/python3.8/site-packages/asyncua/common/structures104.py", line 324, in load_data_type_definitions
env = await _generate_object(dts.name, dts.sdef, data_type=dts.data_type)
File "/home/user/.local/lib/python3.8/site-packages/asyncua/common/structures104.py", line 242, in _generate_object
code = make_structure_code(data_type, name, sdef)
File "/home/user/.local/lib/python3.8/site-packages/asyncua/common/structures104.py", line 192, in make_structure_code
raise RuntimeError(f"Unknown datatype for field: {sfield} in structure:{struct_name}, please report")
```
**Describe the bug** <br />
asyncua is unable to handle an array of datatype word within a struct and raises a runtime error
This is the array of words inside a structure it chokes on:
<img width="503" alt="Bildschirmfoto 2022-05-20 um 20 43 47" src="https://user-images.githubusercontent.com/3080674/169592773-09034823-54a0-4bf1-ab7b-15f80c907f67.png">
**Expected behavior**<br />
Should not raise a runtime error but handle the datatype word correctly.
**Version**<br />
Python-Version: 3.8<br />
opcua-asyncio: 0.9.92:
| Unknown datatype for field Unknown data - Not handling type word correctly | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/899/comments | 7 | 2022-05-20T18:53:37Z | 2022-08-28T16:28:39Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/899 | 1,243,506,611 | 899 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I need to create a nested struct (ie., an struct array from a custom dataType). However, if I do so, the server returns that the custom dataType "has no len".
**To Reproduce**<br />
```
snode1, _ = await new_struct(server, idx, "MyStruct", [
new_struct_field("MyBool", ua.VariantType.Boolean),
new_struct_field("MyUInt32", ua.VariantType.UInt32),
])
snode2, _ = await new_struct(server, idx, "MyNestedStruct", [
new_struct_field("MyStructArray", snode1, array=True),
])
```
This triggers ``TypeError: object of type 'MyStruct' has no len()``
**Expected behavior**<br />
The goal would be something like this:

**Version**<br />
opcua-asyncio Version: 0.9.93 (from pip on 2022-May-19)
| It's impossible to defined nested array structs | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/893/comments | 0 | 2022-05-19T00:45:28Z | 2022-05-20T07:47:04Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/893 | 1,240,846,606 | 893 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Expected behavior**<br />
1. Correct the filename from "amd" to "and" -- ie., from `server-custom-structures-amd-enums.py` to `server-custom-structures-and-enums.py`
2. On line 41, add `datatype` to the enum variable: `valnode = await server.nodes.objects.add_variable(idx, "my_enum", ua.MyEnum.toto, datatype=enode.nodeid)`
**Screenshots**<br />
Without datatype:

With datatype:

**Version**<br />
opcua-asyncio Version: master branch, 0.9.93 (on `setup.py`)
| Improving custom structures example | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/892/comments | 1 | 2022-05-18T20:26:19Z | 2023-03-29T12:30:40Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/892 | 1,240,479,144 | 892 |
[
"FreeOpcUa",
"opcua-asyncio"
] | static code analyse with mypy complains in the following places
- [x] `Reconciliator` has no attribute `hook_mi_request`
https://github.com/FreeOpcUa/opcua-asyncio/blob/4f48eb2df8d998e8f576779fbae8c5c913fddab5/asyncua/client/ha/reconciliator.py#L323
https://github.com/FreeOpcUa/opcua-asyncio/blob/4f48eb2df8d998e8f576779fbae8c5c913fddab5/asyncua/client/ha/reconciliator.py#L293
- [x] `Reconciliator` has no attribute `hook_mi_request`
https://github.com/FreeOpcUa/opcua-asyncio/blob/4f48eb2df8d998e8f576779fbae8c5c913fddab5/asyncua/client/ha/reconciliator.py#L384
- [x] `Reconciliator` has no attribute `hook_add_to_map`
https://github.com/FreeOpcUa/opcua-asyncio/blob/4f48eb2df8d998e8f576779fbae8c5c913fddab5/asyncua/client/ha/reconciliator.py#L411
- [x] `Reconciliator` has no attribute `hook_add_to_map_error`
https://github.com/FreeOpcUa/opcua-asyncio/blob/4f48eb2df8d998e8f576779fbae8c5c913fddab5/asyncua/client/ha/reconciliator.py#L432
related to #878 | Reconciliator, has undefined attributes/functions | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/885/comments | 2 | 2022-05-16T19:47:08Z | 2022-06-06T17:32:50Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/885 | 1,237,633,729 | 885 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Server sync method create_subscription is missing, the code fails with:
```
AttributeError: 'Server' object has no attribute 'create_subscription'
```
**To Reproduce**<br />
Uncomment subscription in _opcua-asyncio/examples/sync/server-example.py_
```
# enable following if you want to subscribe to nodes on server side
#handler = SubHandler()
#sub = server.create_subscription(500, handler)
#handle = sub.subscribe_data_change(myvar)
```
**Expected behavior**<br />
A demonstration of a working subscription.
**Version**<br />
Python-Version: 3.8.10<br />
opcua-asyncio Version (e.g. master branch, 0.9): 0.9.92
| Server sync method create_subscription is missing. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/884/comments | 4 | 2022-05-16T09:24:49Z | 2022-06-08T09:35:14Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/884 | 1,236,871,192 | 884 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Nested structure:
await client.load_type_definitions()
after = await struct.read_value()
---------------------------------------
File "C:\Program Files\Python38\lib\site-packages\asyncua\ua\ua_binary.py", line 73, in unpack
b = _Bytes.unpack(data)
File "C:\Program Files\Python38\lib\site-packages\asyncua\ua\ua_binary.py", line 61, in unpack
return data.read(length)
File "C:\Program Files\Python38\lib\site-packages\asyncua\common\utils.py", line 59, in read
raise NotEnoughData(f"Not enough data left in buffer, request for {size}, we have {self._size}")
asyncua.common.utils.NotEnoughData: Not enough data left in buffer, request for 256, we have 95
| Not enough data left in buffer。 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/883/comments | 6 | 2022-05-16T02:13:46Z | 2022-05-19T02:39:03Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/883 | 1,236,527,164 | 883 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I wrote the following code
async def main(config):
try:
url = config["url"]
async with Client(url=url) as client:
await client.connect()
handler = SubHandler()
subscription = await client.create_subscription(500, handler) # 10
subscribed_nodes = config["subscribed_nodes"]
server_status_current_time = client.get_node(ua.ObjectIds.Server_ServerStatus_CurrentTime)
nodes = [server_status_current_time]
for subscribed_node in subscribed_nodes:
node = client.get_node(subscribed_node)
nodes.append(node)
handle = await subscription.subscribe_data_change(nodes)
global _handler, _handle, _client, _subscription
_handle = handle
_client = client
_subscription = subscription
await asyncio.sleep(0.1)
while True:
await asyncio.sleep(1)
finally:
print("Exit Python application")
if _handle and _subscription:
await _subscription.unsubscribe(_handle)
await _subscription.delete()
if _client:
await _client.disconnect()
if __name__ == "__main__":
config_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "./configuration.json"))
with open(config_path, 'r') as f:
config = json.load(f)
asyncio.run(main(config))
### requirements.txt
asyncua==0.9.92
The code continue to run before the **finally** statement in the loop:
while True:
await asyncio.sleep(1)
### And obtain the following error when running for 6 - 10 hours:
**Exception raised while parsing message from server**
Traceback (most recent call last):
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\client\ua_client.py", line 78, in _process_received_d
msg = self._connection.receive_from_header_and_body(header, buf)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\common\connection.py", line 344, in receive_from_head
self._check_sym_header(security_header)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\common\connection.py", line 296, in _check_sym_header
raise ua.UaError(f"Security token id {security_hdr.TokenId} has timed out " f"({timeout} < {datetime.utcnow()})")
asyncua.ua.uaerrors._base.UaError: **Security token id 12 has timed out (2022-05-12 21:20:38.893618 < 2022-05-15 06:28:32.133270)
Error while renewing session**
Traceback (most recent call last):
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\client\client.py", line 405, in _renew_channel_loop
val = await self.nodes.server_state.read_value()
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\common\node.py", line 177, in read_value
result = await self.read_data_value()
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\common\node.py", line 188, in read_data_value
return await self.read_attribute(ua.AttributeIds.Value)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\common\node.py", line 302, in read_attribute
result = await self.server.read(params)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\client\ua_client.py", line 362, in read
data = await self.protocol.send_request(request)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\client\ua_client.py", line 148, in send_request
raise ConnectionError("Connection is closed") from None
**ConnectionError: Connection is closed
Task exception was never retrieved**
future: <Task finished name='Task-3' coro=<Client._renew_channel_loop() done, defined at c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.ven 188, in read_data_value
188, in read_data_value
return await self.read_attribute(ua.AttributeIds.Value)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\common\node.py", line 302, in read_attribute
result = await self.server.read(params)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\client\ua_client.py", line 362, in read
data = await self.protocol.send_request(request)
File "c:\Development\opc\Tools\opcua-asyncio-master\opcua-asyncio-master\.venv\lib\site-packages\asyncua\client\ua_client.py", line 148, in send_request
raise ConnectionError("Connection is closed") from None
**ConnectionError: Connection is closed**
As i understood one of the solutions is to retry connection.
How can I catch the exception?, How and where reconnect?
Regards | Exception raised when running for long time | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/881/comments | 1 | 2022-05-15T11:13:32Z | 2023-03-29T12:30:21Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/881 | 1,236,257,548 | 881 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Not issue just question. How to get server timestamp for value in datachange notification?
def datachange_notification(self, node, val, data):
print("New data change event", node, val)
Thanks! | Getting server timestamp | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/880/comments | 2 | 2022-05-11T15:28:00Z | 2022-05-11T16:05:40Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/880 | 1,232,836,618 | 880 |
[
"FreeOpcUa",
"opcua-asyncio"
] | In xmlimporter.py line 165 following the condition
if ref.reftype in [
self.server.nodes.HasComponent.nodeid,
self.server.nodes.HasProperty.nodeid
]:
seems to be incomplete. Ich have an example generated from Siemens SIOME where I would need
if ref.reftype in [
self.server.nodes.HasComponent.nodeid,
self.server.nodes.HasProperty.nodeid,
self.server.nodes.HasEncoding.nodeid
]:
Seems to me the list is somewhat incomplete. | Adding missing parents conditions seem to be incomplete in xmlimporter.py | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/879/comments | 0 | 2022-05-09T10:49:50Z | 2023-03-29T12:29:12Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/879 | 1,229,523,823 | 879 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I've created a custom struct with `asyncua.common.structures104.new_struct()` and tried to convert it to "Union". Then the `.read_value()` from the nodeset is empty. If disable keep it as a regular struct (ie., `is_union=False`) it works good.
**Screenshots**<br />
`is_union=False`:

`is_union=True`:

**Version**<br />
Python-Version: 3.10
opcua-asyncio Version: master branch, 0.9.92 from early May 2022
| `new_struct(..., is_union=True)` is not working as expected | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/875/comments | 2 | 2022-05-03T23:26:44Z | 2022-05-16T15:51:17Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/875 | 1,224,764,452 | 875 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Problem ** <br />
I am trying to connect to a new generation OPC UA server.
Connexion works fine with uaExpert with these parameters :

However, using asyncua I obtain :
`asyncua.ua.uaerrors._base.UaError: Unsupported security policy http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep`
My code that work with another server :
```
async def task():
url = influx.machine_cfg.opc_url
client = Client(url=url)
client.set_user("toto")#influx.machine_cfg.opc_user)
client.set_password("toto")#influx.machine_cfg.opc_password)
#print(url,influx.machine_cfg.opc_user,influx.machine_cfg.opc_password,opc.cert,opc.private_key)
await client.set_security(
SecurityPolicyBasic256Sha256,
certificate=opc.cert,
private_key=opc.private_key
)
async with client:
handler = opc.SubscriptionHandler()
subscription = await client.create_subscription(100, handler)
nodes = []
for node in list_var_nodes:
nodes.append(client.get_node(node))
print(nodes)
# We subscribe to data changes for two nodes (variables).
await subscription.subscribe_data_change(nodes)
# We let the subscription run for ten seconds
await asyncio.sleep(3600000)
# We delete the subscription (this un-subscribes from the data changes of the two variables).
# This is optional since closing the connection will also delete all subscriptions.
await subscription.delete()
# After one second we exit the Client context manager - this will close the connection.
await asyncio.sleep(1)
```
| Unable to connect to new server using Aes128_Sha256_RsaOaep | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/874/comments | 14 | 2022-05-03T13:36:49Z | 2023-03-29T12:28:38Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/874 | 1,224,118,954 | 874 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Problem:
On systems such as raspberry pi with 32-bit OS, the Python built-in hash() function is a 32-bit integer.
Considering that the keys for storing nodedata in the address space are based on this hash (ref 1, 2), and given that I have recently encountered a situation with 15.000 nodes, a collision probability of 2.5% is not acceptable.
Solution:
- nodeid hash = binary representation of a numeric nodeid?
- other...?

Source: https://preshing.com/20110504/hash-collision-probabilities/
(ref 1)
https://github.com/FreeOpcUa/opcua-asyncio/blob/018c93bb3e7702168c102bfe41aed50c88854c1d/asyncua/server/address_space.py#L617
(ref 2)
https://github.com/FreeOpcUa/opcua-asyncio/blob/018c93bb3e7702168c102bfe41aed50c88854c1d/asyncua/ua/uatypes.py#L426 | On address space keys and hash collisions... | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/872/comments | 0 | 2022-04-28T16:00:53Z | 2023-03-29T12:27:07Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/872 | 1,218,946,172 | 872 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I exported some nodes using `asyncua.common.xmlexporter.XmlExporter` then loaded them to a `Server` using the `import_xml()` method. The exported XML has some nodes with `MinimumSamplingInterval="10.0"`. The floating point string trips up the importer and results in the following exception / traceback:
```
File "/usr/local/lib/python3.9/dist-packages/asyncua/server/server.py", line 585, in import_xml
return await importer.import_xml(path, xmlstring)
File "/usr/local/lib/python3.9/dist-packages/asyncua/common/xmlimporter.py", line 103, in import_xml
dnodes = self.parser.get_node_datas()
File "/usr/local/lib/python3.9/dist-packages/asyncua/common/xmlparser.py", line 166, in get_node_datas
node = self._parse_node(tag, child)
File "/usr/local/lib/python3.9/dist-packages/asyncua/common/xmlparser.py", line 177, in _parse_node
self._set_attr(key, val, obj)
File "/usr/local/lib/python3.9/dist-packages/asyncua/common/xmlparser.py", line 206, in _set_attr
obj.minsample = int(val)
ValueError: invalid literal for int() with base 10: '10.0'
```
The exporter should probably be writing these with integer formatting, but I don't see why the parser couldn't just coerce the number to an int. Maybe only throw an exception if it is supposed to be an int but there is something other than a zero after the `.`?
I'm running asyncua 0.9.92.
| ValueError when importing MinimiumSamplingInterval with decimal point (generated by XmlExporter) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/869/comments | 1 | 2022-04-27T01:32:18Z | 2022-04-27T16:55:26Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/869 | 1,216,665,118 | 869 |
[
"FreeOpcUa",
"opcua-asyncio"
] | In the docstring at https://github.com/FreeOpcUa/opcua-asyncio/blob/f2f7722d945dbbc04ab20a87f6aff17496f7edf1/asyncua/server/server.py#L58 and on the project documentation at https://pypi.org/project/asyncua/ it is mentioned that one can pass a cache file to the server to improve startup time.
But nowhere it is mentioned *how* to do this. Is this still possible? Or is the documentation just outdated and it isn't possible anymore? | How to pass the cache file to the server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/867/comments | 2 | 2022-04-26T14:13:14Z | 2024-02-21T16:42:33Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/867 | 1,216,023,736 | 867 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
**Describe the bug** <br />
I get the error shown in the traceback below from time to time.
**To Reproduce**<br />
Currently I don't know how to reproduce this error consistently. It just happens now and then.
**Traceback**<br />
````
ERROR:asyncua.client.ua_client.UASocketProtocol:Exception raised while parsing message from server
Traceback (most recent call last):
File "D:\SVN\FLOW\Python\AcoposDriver\venv\lib\site-packages\asyncua\client\ua_client.py", line 88, in
_process_received_data
data = bytes(buf)
TypeError: __bytes__ returned non-bytes (type bytearray)
````
**Version**<br />
Python-Version: Python 3.10.4 on Windows 10<br />
opcua-asyncio Version: 0.9.92
| UASocketProtocol Exception: Exception raised while parsing message from server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/858/comments | 7 | 2022-04-11T15:53:39Z | 2022-04-22T15:49:48Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/858 | 1,200,179,845 | 858 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi everyone thanks a lot for your good job and this nice python library, i know this should be a discussion but i sadly am not able to start one the start button stays light green in my case.
We decide to use the library to automate some system test we currently run manually, a test case we have that works with another opcua client dictates that a tag is writen with a bad quality and then is read back to verify this works sadly this throws the following error
```
./env/lib/python3.8/site-packages/asyncua/ua/uatypes.py", line 318, in check
raise UaStatusCodeError(self.value)
```
I checked the master code since i am using 0.9.92 and this check and throw is also there but in line 303.
Then I took a look at https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/ua/uatypes.py and found this cryptic message in the check function that causes this 'Use the is_good() method if you do not want an exception.' and to be honest i dont see a way this could work as.
For me it seems like a without reason restriction and i have some ideas on how this restriction could be removed i would be happy to provide a pull request if you agree with me.
Sample code to reproduce this.
```
from asyncua.sync import Client
from asyncua import ua
client = Client('url')
try:
client.connect()
value = client.get_node('ns=1;i=9')
variant= ua.Variant("_", ua.VariantType.Boolean)
dataValue = ua.DataValue(variant)
object.__setattr__(datavalue, 'StatusCode_', ua.StatusCode(ua.StatusCodes.Bad))
value .set_value(dataValue)
result = value .read_attribute(ua.AttributeIds.Value)
print(result)
finally:
client.disconnect()
```
| Client should be able to read Tag with a Bad Quality | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/856/comments | 4 | 2022-04-07T11:14:18Z | 2022-04-27T11:52:29Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/856 | 1,195,894,462 | 856 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
`asyncua.common.structures104.new_enum` triggers a **message** error. Functionality appears to be fine.
**To Reproduce**<br />
Any (successful) call of `new_enum` (eg., *opcua-asyncio/examples/server-custom-structures-amd-enums.py*)
**Expected behavior**<br />
We should not see an error message.
**Screenshots**<br />
```
INFO:asyncua.common.structures104:Registring Enum NodeId(Identifier=5, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>) MyEnum OptionSet=False
INFO:asyncua.common.structures104:Registering data type NodeId(Identifier=5, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>) QualifiedName(NamespaceIndex=2, Name='MyEnum')
ERROR:asyncua.common.structures104:tutu - EnumField(Value=2, DisplayName=LocalizedText(Locale=None, Text='tutu'), Description=LocalizedText(Locale=None, Text=None), Name='tutu') False
class MyEnum(IntEnum):
'''
MyEnum EnumInt autogenerated from EnumDefinition
'''
titi = 0
toto = 1
tutu = 2
INFO:asyncua.ua.uatypes:registring new enum: MyEnum NodeId(Identifier=5, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>) <enum 'MyEnum'>
INFO:asyncua.common.structures104:Registering data type NumericNodeId(Identifier=258, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) QualifiedName(NamespaceIndex=0, Name='Node')
INFO:asyncua.common.structures104:Registering data type NumericNodeId(Identifier=285, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) QualifiedName(NamespaceIndex=0, Name='ReferenceNode')
```
**Version**<br />
Python-Version: 3.9 <br />
opcua-asyncio Version: 0.9.92
| `new_enum` triggers an Error message | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/851/comments | 2 | 2022-03-29T23:40:15Z | 2022-04-27T06:13:48Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/851 | 1,185,605,218 | 851 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi! How could I close the session of an active user manually from the server? For example, if the password of the client has expired I want the server to eject him. What sequence should I follow to stop the communication with only that client?
Thank you | Close Session Manually | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/849/comments | 4 | 2022-03-29T09:40:18Z | 2024-11-25T11:46:24Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/849 | 1,184,588,982 | 849 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Good afternoon,I'm come form china
I wrote the code below:
``from opcua import Client
import time
from threading import Thread
import queue
work = queue.Queue(1000)
client = Client("opc.tcp://127.0.0.1:49320")
def task1(): # 定义任务1
try:
while 1:
client.connect()
T = client.get_node('ns=2;s=test.mac.TA1').get_value()
work.put(T)
time.sleep(0.1)
except Exception as e:
print(e)
finally:
client.disconnect()
def task2():
while 1:
time.sleep(0.5)
print(work.get())
def main(): # 定义main函数
t1 = Thread(target=task1) # 定义线程t1,线程任务为调用task1函数,task1函数的参数是6
t2 = Thread(target=task2) # 定义线程t2,线程任务为调用task2函数,task2函数无参数
t1.start() # 开始运行t1线程
t2.start() # 开始运行t2线程
if name == 'main':
main() # 调用main函数`
Error Meessage:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\chenh\AppData\Local\Programs\Python\Python39\lib\site-packages\opcua\client\client.py", line 299, in disconnect
self.close_secure_channel()
File "C:\Users\chenh\AppData\Local\Programs\Python\Python39\lib\site-packages\opcua\client\client.py", line 343, in close_secure_channel
return self.uaclient.close_secure_channel()
File "C:\Users\chenh\AppData\Local\Programs\Python\Python39\lib\site-packages\opcua\client\ua_client.py", line 282, in close_secure_channel
return self._uasocket.close_secure_channel()
File "C:\Users\chenh\AppData\Local\Programs\Python\Python39\lib\site-packages\opcua\client\ua_client.py", line 223, in close_secure_channel
future = self._send_request(request, message_type=ua.MessageType.SecureClose)
File "C:\Users\chenh\AppData\Local\Programs\Python\Python39\lib\site-packages\opcua\client\ua_client.py", line 72, in _send_request
self._socket.write(msg)
File "C:\Users\chenh\AppData\Local\Programs\Python\Python39\lib\site-packages\opcua\common\utils.py", line 118, in write
self.socket.sendall(data)
OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。`
How can i fix it?
Now in china,many engineer want use Python in electric design.
But only some people use FreeOpcUA in CSDN
No one knows haw to use it in internet | Thread Error:OSError: [WinError 10038] 在一个非套接字上尝试了一个操作 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/847/comments | 4 | 2022-03-28T11:24:58Z | 2022-03-28T13:29:29Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/847 | 1,183,292,556 | 847 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When importing an XML in a server, the newly created namespace is added to the namespace_array of the server but not to the server.nodes.namespaces shortcuts child nodes.
This leads to a bug when importing models, which require one another, since the check for required models on the server is depending on the server.nodes.namespaces shortcut.
Importing [Opc.Ua.Di.NodeSet2.xml](http://opcfoundation.org/UA/DI/) works fine. Trying to afterwards import [Opc.Ua.Plc.NodeSet2.xml ](http://PLCopen.org/OpcUa/IEC61131-3/) leads to an exception, since the check for required models does not recognize, that [Opc.Ua.Di.NodeSet2.xml](http://opcfoundation.org/UA/DI/) is already imported. Commenting out the exception leads to the warning log, however the import passes and the server can be started. | Importing NodeSet does not register the namespace to the server.nodes.namespaces shortcut | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/846/comments | 7 | 2022-03-25T09:21:08Z | 2023-03-29T12:26:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/846 | 1,180,538,861 | 846 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi, is there a way to list all the clients that are connected to the server? I mean, their names for example. | List connected clients | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/844/comments | 0 | 2022-03-24T10:55:35Z | 2022-03-24T10:56:43Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/844 | 1,179,341,823 | 844 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.