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"
] | ### There seems to be a slight mixup between
- security policies (None, Basic256Sha256, Aes128Sha256RsaOaep, Aes256Sha256RsaPss)
- supported UserTokenTypes (Anonymous, UserName, Certificate, IssuedToken)
- these map 1:1 to UserIdentityTokens (AnonymousIdentityToken, UserNameIdentityToken, X509IdentityToken, IssuedIdentityToken)
- supported UserTokenPolicies (combination of UserTokenType, SecurityPolicy, etc.)
### Misconceptions
- **Configuring authentication**
current state: set_security_IDs(["Basic256Sha256", "Username"])
better: set_identity_tokens([ua.X509IdentityToken, ua.UserNameIdentityToken])
Why does "Basic256Sha256" imply to accept a client certificate?
Where does the name of the method come from? I assume that it was originally related to UserTokenPoliciy.PolicyId
- **Not using UserTokenPolicy.SecurityPolicyUri**
UserTokenPolicy.SecurityPolicyUri defines how the UserIdentityToken gets signed/encrypted when passed in ActivateSession, see https://reference.opcfoundation.org/Core/Part4/v105/docs/7.41.
(https://github.com/FreeOpcUa/opcua-asyncio/pull/1720 fixes an issue with open62541 there, but that's not what I'm talking about.)
- UserTokenType.Anonymous: Uri can always be "#None", because there is no data to sign/encrypt.
- UserTokenType.UserName: When using a SecureChannel security policy of "None", the password will be sent in cleartext, which some clients deny by throwing BadSecurityModeInsufficient. We should explicitly set an Uri here, which allows the password to be encrypted. That also means, that ServerCertificate needs to be set for a SecureChannel security policy of "None".
Because of the fallback mentioned in the ticket above, using a SecureChannel security policy of Aes256Sha256RsaPss currently leads to the password being encrypted (again) with rsa-oaep-sha2-256, which is currently not accepted in check_user_token()
- UserTokenType.Certificate: For X509IdentityTokens, a signature is mandatory, otherwise the server can't verify if the client possesses the private key. That also means, that the signature should be done with the algorithm specified via Uri, not with the signature algorithm that was used for certificate generation. Currently, this signature also isn't verified in the server, leading to a security issue, because only the public(!) key is then used for authorization.
- **Default PolicyId in client**
According to https://reference.opcfoundation.org/Core/Part4/v105/docs/7.42, the PolicyId is assigned by the Server. A client can't guess it, so it should default to an empty string.
I will create some PRs to address these issues. | SecurityPolicy vs UserIdentityTokens | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1727/comments | 1 | 2024-10-18T10:36:45Z | 2024-12-04T13:03:50Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1727 | 2,597,159,979 | 1,727 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I run into a case where, a private key generated with `generate_private_key` cannot be loaded with `load_private_key`.
The minimal example is,
```py
from asyncua.crypto.uacrypto import load_private_key
from asyncua.crypto.cert_gen import generate_private_key, dump_private_key_as_pem
from pathlib import Path
async def main():
key_file = Path("/tmp/cert.key")
key = generate_private_key()
key_file.write_bytes(dump_private_key_as_pem(key))
key2 = await load_private_key(key_file)
if __name__ == '__main__':
import asyncio
asyncio.run(main())
```
which produces the exception below,
```py
Traceback (most recent call last):
File "check_private_key.py", line 16, in <module>
asyncio.run(main())
File "lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "check_private_key.py", line 11, in main
key2 = await load_private_key(key_file)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "lib/python3.11/site-packages/asyncua/crypto/uacrypto.py", line 80, in load_private_key
return serialization.load_der_private_key(content, password=password, backend=default_backend())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "lib/python3.11/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 494, in _handle_key_loading_error
raise ValueError(
ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [<OpenSSLError(code=109052072, lib=13, reason=168, reason_text=wrong tag)>, <OpenSSLError(code=109576458, lib=13, reason=524554, reason_text=nested asn1 error)>])
```
maybe due the cryptography / openssl combination. This was obtained with
**Version**<br />
Python: 3.11
opcua-asyncio Version 1.0.6 (but I checked that none of the used function had relevant changes since)
cryptography: 42.0.8
pyopenssl 24.0.0
MacOS with conda environment where OpenSSL 3.2.1 was installed with conda
I'll try different versions in a follow up comment
| generate_private_key produces key that can't be loaded with load_private_key | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1722/comments | 2 | 2024-10-15T10:10:07Z | 2024-10-15T11:34:45Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1722 | 2,588,292,396 | 1,722 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi,
I have an OPCUA server with custom events that are periodically published. I can correctly monitor them and check the event history using UAExpert client. The events inherit from BaseEventType and have extra fields.
On the other hand, I have an opcua_asyncio client and I can correctly view the actual events using a subscription. However, when I try to check the event history, the data is not correctly mapped from the fields to the Event. This is how I try to read the history data:

The 54424 number is the nodeId from the custom event type that I had created.
Thank you,
Iván | Check node event history with custom fields | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1721/comments | 0 | 2024-10-15T07:32:07Z | 2024-10-15T07:32:07Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1721 | 2,587,898,042 | 1,721 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When calling mulptily method in examples/server-methods.py from OPC Router (https://opc-router.com), following error message is created:
```
INFO:asyncua.server.uaprocessor:Read request (User(role=<UserRole.User: 3>, name=None))
DEBUG:asyncua.server.binary_server_asyncio:_process_received_message 57 57
DEBUG:asyncua.server.uaprocessor:process_message NodeId(Identifier=554, NamespaceIndex=0, NodeIdType=<NodeIdType.FourByte: 1>) RequestHeader(AuthenticationToken=NodeId(Identifier=1005, NamespaceIndex=0, NodeIdType=<NodeIdType.FourByte: 1>), Timestamp=datetime.datetime(2024, 10, 3, 11, 47, 20, 83604, tzinfo=datetime.timezone.utc), RequestHandle=22, ReturnDiagnostics=0, AuditEntryId=None, TimeoutHint=0, AdditionalHeader=ExtensionObject(TypeId=NodeId(Identifier=0, NamespaceIndex=0, NodeIdType=<NodeIdType.TwoByte: 0>), Body=None))
INFO:asyncua.server.uaprocessor:translate browsepaths to nodeids request (User(role=<UserRole.User: 3>, name=None))
ERROR:asyncua.server.uaprocessor:Error while processing message
Traceback (most recent call last):
File "D:\Projektit\test\OMA_test\venv\Lib\site-packages\asyncua\server\uaprocessor.py", line 143, in process_message
return await self._process_message(typeid, requesthdr, seqhdr, body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Projektit\test\OMA_test\venv\Lib\site-packages\asyncua\server\uaprocessor.py", line 319, in _process_message
paths = await self.session.translate_browsepaths_to_nodeids(params.BrowsePaths)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Projektit\test\OMA_test\venv\Lib\site-packages\asyncua\server\internal_session.py", line 184, in translate_browsepaths_to_nodeids
return self.iserver.view_service.translate_browsepaths_to_nodeids(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Projektit\test\OMA_test\venv\Lib\site-packages\asyncua\server\address_space.py", line 188, in translate_browsepaths_to_nodeids
results.append(self._translate_browsepath_to_nodeid(path))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Projektit\test\OMA_test\venv\Lib\site-packages\asyncua\server\address_space.py", line 194, in _translate_browsepath_to_nodeid
if not path.RelativePath.Elements[-1].TargetName:
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^
IndexError: list index out of range
```
UaExpert works fine with this method, so there might be also implementation problem in the OPC Router, but I'm not familiar enough with the library and protocol to tell what is happening.
**To Reproduce**<br />
Steps to reproduce the behavior incl code:
1. Run server-methods.py
2. Call mulptiply method from OPC Router
**Expected behavior**<br />
A clear and concise description of what you expected to happen.
Method returns the correct value with out no errors.
**Version**<br />
Python-Version: 3,12.5 <br />
opcua-asyncio Version (e.g. master branch, 0.9): 1.1.5
| Error "list index out of range" when calling method in server-methods.py | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1716/comments | 5 | 2024-10-03T12:06:57Z | 2024-10-30T06:41:48Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1716 | 2,563,886,456 | 1,716 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I have a simple program that uses `asyncua.sync.Client`. The program simply connects to the server, disconnects, then re-connects. When attempting the second connect (or re-connect) I get an error.
The code:
```
import sys
from time import sleep
from asyncua.sync import Client
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__file__)
# end point
url = 'opc.tcp://10.0.1.56:55105'
class Handler():
def datachange_notification(self, node, val, data):
logger.info('value is:', val)
try:
client = Client(url)
logger.info('user connect')
client.connect()
sleep(1)
logger.info('user disconnect')
client.disconnect()
sleep(1)
logger.info('user connect')
client.connect()
except Exception as err:
logger.exception(err)
finally:
client.disconnect()
```
The output:
```
$ cd /home/david/python/opcua ; /usr/bin/env /home/david/python/opcua/.venv/bin/python3 /home/david/.vscode/extensions/ms-python.debugpy-2024.10.0-linux-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher 55907 -- /home/david/python/opcua/main.py
INFO:/home/david/python/opcua/main.py:user connect
INFO:asyncua.client.client:connect
INFO:asyncua.client.ua_client.UaClient:opening connection
INFO:asyncua.uaprotocol:updating client limits to: TransportLimits(max_recv_buffer=65536, max_send_buffer=65536, max_chunk_count=640, max_message_size=41943040)
INFO:asyncua.client.ua_client.UASocketProtocol:open_secure_channel
INFO:asyncua.client.ua_client.UaClient:create_session
INFO:asyncua.client.client:find_endpoint [EndpointDescription(EndpointUrl='opc.tcp://SNetV16:55105', Server=ApplicationDescription(ApplicationUri='urn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)', ProductUri='Siemens/SimaticNet/OpcUaServer/S7OPT', ApplicationName=LocalizedText(Locale='en', Text='OPC.SimaticNET.S7OPT'), ApplicationType_=<ApplicationType.Server: 0>, GatewayServerUri=None, DiscoveryProfileUri=None, DiscoveryUrls=['opc.tcp://SNetV16:55105']), ServerCertificate=b'0\x82\x04T0\x82\x03<\xa0\x03\x02\x01\x02\x02\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x1e\x17\r210116154629Z\x17\r410116154629Z081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x82\x01"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x000\x82\x01\n\x02\x82\x01\x01\x00\xbe\xb4^\xd9\xb5\xd8\xde|\x10\xe9\xc6\xec\x9e)*\xdd\x00io\xd8\x84>h\x1c\x12\xd9\x9d\xdf\x94\x89\x13\xb2C\x93\x1dW\xdcq/\x97@5\xd5$\x0f\xcf}\xfd\xd7#\xdfY\x0e\x04\\\x12\xba?==\xa9\xddJ\xa5jd3\x11L\xc8\xbfN\xc8"+Ti\x91\xbeA\xd4\xba\xbf\xcc[\xcf\x82\x8d$Y\x88)\xb7\xd8\xf8\xf7b\xa31\x16\xf4x\x92\xfcJ\xc2C\xf3\xd4\xc1;\xd1\xc8\xbd;vr)t\x868\x8a\xe3\xb34a\xb3)\x1d\xdf\tf\x8dx\x8c\xfa\xedm\xf3\xda\xae`\xfa\x80{\xcef6\xe2o+\xab\x11\xb1!\xeaB@\x03HD\xa9\x9ap\xc8\xec\xd9\xb1\xe6=\x84\x8a\x10\x868p\x18\x956\xed\xf54\xde\xfd\x18\x9b\xb9\xd7\xac\xba\xcb\xf3i\xf1fuC\xc90\x9f\xad\x7fq\xe7VI\xb2zv\x18Z\xd4\xc1<3f\x8c\x92\xde\xe3\xd0\x9e\xd8\x1c\x8f\x95\xb0\xea\xcaT\x83F\xf6\x9ej\xc7"\xe8I\x06P\x02Z?\x18\xa3N\xc7\xc6,\xb9\xac5r\'K\x02\x03\x01\x00\x01\xa3\x82\x01_0\x82\x01[0\x0c\x06\x03U\x1d\x13\x01\x01\xff\x04\x020\x000\x0e\x06\x03U\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x02\xf40 \x06\x03U\x1d%\x01\x01\xff\x04\x160\x14\x06\x08+\x06\x01\x05\x05\x07\x03\x01\x06\x08+\x06\x01\x05\x05\x07\x03\x020,\x06\t`\x86H\x01\x86\xf8B\x01\r\x04\x1f\x16\x1dOpenSSL Generated Certificate0\x1d\x06\x03U\x1d\x0e\x04\x16\x04\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr0h\x06\x03U\x1d#\x04a0_\x80\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr\xa1<\xa4:081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV16\x82\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0b\x06\x03U\x1d\x11\x04[0Y\x86Nurn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)\x82\x07SNetV160\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00\x03\x82\x01\x01\x00Q\xd3_\xedP0\xd2u\t\x04\xde\xe0\xef\x00(\xd21Tz2\xb8\xa4F&\xdeWl\x9a7Q=`n\xa5&\xb8Dv\x95y\x87H\xb1\xfa\xbf\x95\xc3\x11\xb4\x06\'\xb0\xf5\x05P\xcd\xd5;x\x97:\xaf\xe8\x8f\x1d\xf2\xc1\xe3\xbb\xef\r\xac4\xadLW(\x1awm\x94\x1f]\xec]\x86\xf8\xf2\xa7b\xbd\x91\x84%\xbf\x94y@\xb5\xe9\x89\xb6\x8c\xed\xc4\xb6a\xa9\\\xf7\xc3\xf3\xa9\xd7\xfc\xec\xc8\xb1\xfc\x93\xd6\xeaRQ\xbbr\xea\xef\xe2\xc7U\xe4z]\x88\xea\xfe\x99yI\xa3\xcf\xc3\xc4\xaf\xd7\xb3%\x0c|\xb2\xea\nB\xb5\xcb\xd9\xbfE\'\xa3\x14\x96\x8e\x1c\xd84$^\x93)7>\xa2E!y\x1a\x08\xff\r\xe5\x1f\xd2\x13\xa6\x05z\xe89\x9aF\x08A#\x8b\x0ep\xedr\xa3]\x841\xb7\xbd\xdb\x93g\xc4\x0e$\xe5\x00\x11\x94j\xbc\xf9\x8c>1\x18ek\x16E\x89\x17\xe3 \xf4h\x1d\x98R\xc1I\xfa\xa1\xdaG\xef^W\xe2\xa46{s\xef\xa8\xa7\x97\x1a\r', SecurityMode=<MessageSecurityMode.None_: 1>, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#None', UserIdentityTokens=[UserTokenPolicy(PolicyId='Anonymous', TokenType=<UserTokenType.Anonymous: 0>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri=None), UserTokenPolicy(PolicyId='UserName', TokenType=<UserTokenType.UserName: 1>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#Basic256')], TransportProfileUri='http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary', SecurityLevel=0), EndpointDescription(EndpointUrl='opc.tcp://SNetV16:55105', Server=ApplicationDescription(ApplicationUri='urn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)', ProductUri='Siemens/SimaticNet/OpcUaServer/S7OPT', ApplicationName=LocalizedText(Locale='en', Text='OPC.SimaticNET.S7OPT'), ApplicationType_=<ApplicationType.Server: 0>, GatewayServerUri=None, DiscoveryProfileUri=None, DiscoveryUrls=['opc.tcp://SNetV16:55105']), ServerCertificate=b'0\x82\x04T0\x82\x03<\xa0\x03\x02\x01\x02\x02\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x1e\x17\r210116154629Z\x17\r410116154629Z081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x82\x01"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x000\x82\x01\n\x02\x82\x01\x01\x00\xbe\xb4^\xd9\xb5\xd8\xde|\x10\xe9\xc6\xec\x9e)*\xdd\x00io\xd8\x84>h\x1c\x12\xd9\x9d\xdf\x94\x89\x13\xb2C\x93\x1dW\xdcq/\x97@5\xd5$\x0f\xcf}\xfd\xd7#\xdfY\x0e\x04\\\x12\xba?==\xa9\xddJ\xa5jd3\x11L\xc8\xbfN\xc8"+Ti\x91\xbeA\xd4\xba\xbf\xcc[\xcf\x82\x8d$Y\x88)\xb7\xd8\xf8\xf7b\xa31\x16\xf4x\x92\xfcJ\xc2C\xf3\xd4\xc1;\xd1\xc8\xbd;vr)t\x868\x8a\xe3\xb34a\xb3)\x1d\xdf\tf\x8dx\x8c\xfa\xedm\xf3\xda\xae`\xfa\x80{\xcef6\xe2o+\xab\x11\xb1!\xeaB@\x03HD\xa9\x9ap\xc8\xec\xd9\xb1\xe6=\x84\x8a\x10\x868p\x18\x956\xed\xf54\xde\xfd\x18\x9b\xb9\xd7\xac\xba\xcb\xf3i\xf1fuC\xc90\x9f\xad\x7fq\xe7VI\xb2zv\x18Z\xd4\xc1<3f\x8c\x92\xde\xe3\xd0\x9e\xd8\x1c\x8f\x95\xb0\xea\xcaT\x83F\xf6\x9ej\xc7"\xe8I\x06P\x02Z?\x18\xa3N\xc7\xc6,\xb9\xac5r\'K\x02\x03\x01\x00\x01\xa3\x82\x01_0\x82\x01[0\x0c\x06\x03U\x1d\x13\x01\x01\xff\x04\x020\x000\x0e\x06\x03U\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x02\xf40 \x06\x03U\x1d%\x01\x01\xff\x04\x160\x14\x06\x08+\x06\x01\x05\x05\x07\x03\x01\x06\x08+\x06\x01\x05\x05\x07\x03\x020,\x06\t`\x86H\x01\x86\xf8B\x01\r\x04\x1f\x16\x1dOpenSSL Generated Certificate0\x1d\x06\x03U\x1d\x0e\x04\x16\x04\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr0h\x06\x03U\x1d#\x04a0_\x80\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr\xa1<\xa4:081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV16\x82\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0b\x06\x03U\x1d\x11\x04[0Y\x86Nurn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)\x82\x07SNetV160\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00\x03\x82\x01\x01\x00Q\xd3_\xedP0\xd2u\t\x04\xde\xe0\xef\x00(\xd21Tz2\xb8\xa4F&\xdeWl\x9a7Q=`n\xa5&\xb8Dv\x95y\x87H\xb1\xfa\xbf\x95\xc3\x11\xb4\x06\'\xb0\xf5\x05P\xcd\xd5;x\x97:\xaf\xe8\x8f\x1d\xf2\xc1\xe3\xbb\xef\r\xac4\xadLW(\x1awm\x94\x1f]\xec]\x86\xf8\xf2\xa7b\xbd\x91\x84%\xbf\x94y@\xb5\xe9\x89\xb6\x8c\xed\xc4\xb6a\xa9\\\xf7\xc3\xf3\xa9\xd7\xfc\xec\xc8\xb1\xfc\x93\xd6\xeaRQ\xbbr\xea\xef\xe2\xc7U\xe4z]\x88\xea\xfe\x99yI\xa3\xcf\xc3\xc4\xaf\xd7\xb3%\x0c|\xb2\xea\nB\xb5\xcb\xd9\xbfE\'\xa3\x14\x96\x8e\x1c\xd84$^\x93)7>\xa2E!y\x1a\x08\xff\r\xe5\x1f\xd2\x13\xa6\x05z\xe89\x9aF\x08A#\x8b\x0ep\xedr\xa3]\x841\xb7\xbd\xdb\x93g\xc4\x0e$\xe5\x00\x11\x94j\xbc\xf9\x8c>1\x18ek\x16E\x89\x17\xe3 \xf4h\x1d\x98R\xc1I\xfa\xa1\xdaG\xef^W\xe2\xa46{s\xef\xa8\xa7\x97\x1a\r', SecurityMode=<MessageSecurityMode.SignAndEncrypt: 3>, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256', UserIdentityTokens=[UserTokenPolicy(PolicyId='Anonymous', TokenType=<UserTokenType.Anonymous: 0>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri=None), UserTokenPolicy(PolicyId='UserName', TokenType=<UserTokenType.UserName: 1>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256')], TransportProfileUri='http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary', SecurityLevel=115), EndpointDescription(EndpointUrl='opc.tcp://SNetV16:55105', Server=ApplicationDescription(ApplicationUri='urn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)', ProductUri='Siemens/SimaticNet/OpcUaServer/S7OPT', ApplicationName=LocalizedText(Locale='en', Text='OPC.SimaticNET.S7OPT'), ApplicationType_=<ApplicationType.Server: 0>, GatewayServerUri=None, DiscoveryProfileUri=None, DiscoveryUrls=['opc.tcp://SNetV16:55105']), ServerCertificate=b'0\x82\x04T0\x82\x03<\xa0\x03\x02\x01\x02\x02\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x1e\x17\r210116154629Z\x17\r410116154629Z081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x82\x01"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x000\x82\x01\n\x02\x82\x01\x01\x00\xbe\xb4^\xd9\xb5\xd8\xde|\x10\xe9\xc6\xec\x9e)*\xdd\x00io\xd8\x84>h\x1c\x12\xd9\x9d\xdf\x94\x89\x13\xb2C\x93\x1dW\xdcq/\x97@5\xd5$\x0f\xcf}\xfd\xd7#\xdfY\x0e\x04\\\x12\xba?==\xa9\xddJ\xa5jd3\x11L\xc8\xbfN\xc8"+Ti\x91\xbeA\xd4\xba\xbf\xcc[\xcf\x82\x8d$Y\x88)\xb7\xd8\xf8\xf7b\xa31\x16\xf4x\x92\xfcJ\xc2C\xf3\xd4\xc1;\xd1\xc8\xbd;vr)t\x868\x8a\xe3\xb34a\xb3)\x1d\xdf\tf\x8dx\x8c\xfa\xedm\xf3\xda\xae`\xfa\x80{\xcef6\xe2o+\xab\x11\xb1!\xeaB@\x03HD\xa9\x9ap\xc8\xec\xd9\xb1\xe6=\x84\x8a\x10\x868p\x18\x956\xed\xf54\xde\xfd\x18\x9b\xb9\xd7\xac\xba\xcb\xf3i\xf1fuC\xc90\x9f\xad\x7fq\xe7VI\xb2zv\x18Z\xd4\xc1<3f\x8c\x92\xde\xe3\xd0\x9e\xd8\x1c\x8f\x95\xb0\xea\xcaT\x83F\xf6\x9ej\xc7"\xe8I\x06P\x02Z?\x18\xa3N\xc7\xc6,\xb9\xac5r\'K\x02\x03\x01\x00\x01\xa3\x82\x01_0\x82\x01[0\x0c\x06\x03U\x1d\x13\x01\x01\xff\x04\x020\x000\x0e\x06\x03U\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x02\xf40 \x06\x03U\x1d%\x01\x01\xff\x04\x160\x14\x06\x08+\x06\x01\x05\x05\x07\x03\x01\x06\x08+\x06\x01\x05\x05\x07\x03\x020,\x06\t`\x86H\x01\x86\xf8B\x01\r\x04\x1f\x16\x1dOpenSSL Generated Certificate0\x1d\x06\x03U\x1d\x0e\x04\x16\x04\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr0h\x06\x03U\x1d#\x04a0_\x80\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr\xa1<\xa4:081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV16\x82\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0b\x06\x03U\x1d\x11\x04[0Y\x86Nurn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)\x82\x07SNetV160\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00\x03\x82\x01\x01\x00Q\xd3_\xedP0\xd2u\t\x04\xde\xe0\xef\x00(\xd21Tz2\xb8\xa4F&\xdeWl\x9a7Q=`n\xa5&\xb8Dv\x95y\x87H\xb1\xfa\xbf\x95\xc3\x11\xb4\x06\'\xb0\xf5\x05P\xcd\xd5;x\x97:\xaf\xe8\x8f\x1d\xf2\xc1\xe3\xbb\xef\r\xac4\xadLW(\x1awm\x94\x1f]\xec]\x86\xf8\xf2\xa7b\xbd\x91\x84%\xbf\x94y@\xb5\xe9\x89\xb6\x8c\xed\xc4\xb6a\xa9\\\xf7\xc3\xf3\xa9\xd7\xfc\xec\xc8\xb1\xfc\x93\xd6\xeaRQ\xbbr\xea\xef\xe2\xc7U\xe4z]\x88\xea\xfe\x99yI\xa3\xcf\xc3\xc4\xaf\xd7\xb3%\x0c|\xb2\xea\nB\xb5\xcb\xd9\xbfE\'\xa3\x14\x96\x8e\x1c\xd84$^\x93)7>\xa2E!y\x1a\x08\xff\r\xe5\x1f\xd2\x13\xa6\x05z\xe89\x9aF\x08A#\x8b\x0ep\xedr\xa3]\x841\xb7\xbd\xdb\x93g\xc4\x0e$\xe5\x00\x11\x94j\xbc\xf9\x8c>1\x18ek\x16E\x89\x17\xe3 \xf4h\x1d\x98R\xc1I\xfa\xa1\xdaG\xef^W\xe2\xa46{s\xef\xa8\xa7\x97\x1a\r', SecurityMode=<MessageSecurityMode.SignAndEncrypt: 3>, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep', UserIdentityTokens=[UserTokenPolicy(PolicyId='Anonymous', TokenType=<UserTokenType.Anonymous: 0>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri=None), UserTokenPolicy(PolicyId='UserName', TokenType=<UserTokenType.UserName: 1>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#Aes128_Sha256_RsaOaep')], TransportProfileUri='http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary', SecurityLevel=120), EndpointDescription(EndpointUrl='opc.tcp://SNetV16:55105', Server=ApplicationDescription(ApplicationUri='urn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)', ProductUri='Siemens/SimaticNet/OpcUaServer/S7OPT', ApplicationName=LocalizedText(Locale='en', Text='OPC.SimaticNET.S7OPT'), ApplicationType_=<ApplicationType.Server: 0>, GatewayServerUri=None, DiscoveryProfileUri=None, DiscoveryUrls=['opc.tcp://SNetV16:55105']), ServerCertificate=b'0\x82\x04T0\x82\x03<\xa0\x03\x02\x01\x02\x02\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x1e\x17\r210116154629Z\x17\r410116154629Z081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV160\x82\x01"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x000\x82\x01\n\x02\x82\x01\x01\x00\xbe\xb4^\xd9\xb5\xd8\xde|\x10\xe9\xc6\xec\x9e)*\xdd\x00io\xd8\x84>h\x1c\x12\xd9\x9d\xdf\x94\x89\x13\xb2C\x93\x1dW\xdcq/\x97@5\xd5$\x0f\xcf}\xfd\xd7#\xdfY\x0e\x04\\\x12\xba?==\xa9\xddJ\xa5jd3\x11L\xc8\xbfN\xc8"+Ti\x91\xbeA\xd4\xba\xbf\xcc[\xcf\x82\x8d$Y\x88)\xb7\xd8\xf8\xf7b\xa31\x16\xf4x\x92\xfcJ\xc2C\xf3\xd4\xc1;\xd1\xc8\xbd;vr)t\x868\x8a\xe3\xb34a\xb3)\x1d\xdf\tf\x8dx\x8c\xfa\xedm\xf3\xda\xae`\xfa\x80{\xcef6\xe2o+\xab\x11\xb1!\xeaB@\x03HD\xa9\x9ap\xc8\xec\xd9\xb1\xe6=\x84\x8a\x10\x868p\x18\x956\xed\xf54\xde\xfd\x18\x9b\xb9\xd7\xac\xba\xcb\xf3i\xf1fuC\xc90\x9f\xad\x7fq\xe7VI\xb2zv\x18Z\xd4\xc1<3f\x8c\x92\xde\xe3\xd0\x9e\xd8\x1c\x8f\x95\xb0\xea\xcaT\x83F\xf6\x9ej\xc7"\xe8I\x06P\x02Z?\x18\xa3N\xc7\xc6,\xb9\xac5r\'K\x02\x03\x01\x00\x01\xa3\x82\x01_0\x82\x01[0\x0c\x06\x03U\x1d\x13\x01\x01\xff\x04\x020\x000\x0e\x06\x03U\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x02\xf40 \x06\x03U\x1d%\x01\x01\xff\x04\x160\x14\x06\x08+\x06\x01\x05\x05\x07\x03\x01\x06\x08+\x06\x01\x05\x05\x07\x03\x020,\x06\t`\x86H\x01\x86\xf8B\x01\r\x04\x1f\x16\x1dOpenSSL Generated Certificate0\x1d\x06\x03U\x1d\x0e\x04\x16\x04\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr0h\x06\x03U\x1d#\x04a0_\x80\x14\xe7X\xf6\xc2\xb1\xb1\n\xb8\x1a\xc4H\xff61\xe5\x83\xde\x16Vr\xa1<\xa4:081\x1d0\x1b\x06\x03U\x04\x03\x0c\x14OPC.SimaticNET.S7OPT1\x170\x15\x06\n\t\x92&\x89\x93\xf2,d\x01\x19\x16\x07SNetV16\x82\t\x00\x80X\x0c\xd3\xfd\x19\xbf\x0b0b\x06\x03U\x1d\x11\x04[0Y\x86Nurn:Siemens.Automation.SimaticNET.S7OPT:(B1707412-DBE3-456B-98F1-40029ACA9F7E)\x82\x07SNetV160\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00\x03\x82\x01\x01\x00Q\xd3_\xedP0\xd2u\t\x04\xde\xe0\xef\x00(\xd21Tz2\xb8\xa4F&\xdeWl\x9a7Q=`n\xa5&\xb8Dv\x95y\x87H\xb1\xfa\xbf\x95\xc3\x11\xb4\x06\'\xb0\xf5\x05P\xcd\xd5;x\x97:\xaf\xe8\x8f\x1d\xf2\xc1\xe3\xbb\xef\r\xac4\xadLW(\x1awm\x94\x1f]\xec]\x86\xf8\xf2\xa7b\xbd\x91\x84%\xbf\x94y@\xb5\xe9\x89\xb6\x8c\xed\xc4\xb6a\xa9\\\xf7\xc3\xf3\xa9\xd7\xfc\xec\xc8\xb1\xfc\x93\xd6\xeaRQ\xbbr\xea\xef\xe2\xc7U\xe4z]\x88\xea\xfe\x99yI\xa3\xcf\xc3\xc4\xaf\xd7\xb3%\x0c|\xb2\xea\nB\xb5\xcb\xd9\xbfE\'\xa3\x14\x96\x8e\x1c\xd84$^\x93)7>\xa2E!y\x1a\x08\xff\r\xe5\x1f\xd2\x13\xa6\x05z\xe89\x9aF\x08A#\x8b\x0ep\xedr\xa3]\x841\xb7\xbd\xdb\x93g\xc4\x0e$\xe5\x00\x11\x94j\xbc\xf9\x8c>1\x18ek\x16E\x89\x17\xe3 \xf4h\x1d\x98R\xc1I\xfa\xa1\xdaG\xef^W\xe2\xa46{s\xef\xa8\xa7\x97\x1a\r', SecurityMode=<MessageSecurityMode.SignAndEncrypt: 3>, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#Aes256_Sha256_RsaPss', UserIdentityTokens=[UserTokenPolicy(PolicyId='Anonymous', TokenType=<UserTokenType.Anonymous: 0>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri=None), UserTokenPolicy(PolicyId='UserName', TokenType=<UserTokenType.UserName: 1>, IssuedTokenType=None, IssuerEndpointUrl=None, SecurityPolicyUri='http://opcfoundation.org/UA/SecurityPolicy#Aes256_Sha256_RsaPss')], TransportProfileUri='http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary', SecurityLevel=125)] <MessageSecurityMode.None_: 1> 'http://opcfoundation.org/UA/SecurityPolicy#None'
INFO:asyncua.client.ua_client.UaClient:activate_session
INFO:/home/david/python/opcua/main.py:user disconnect
INFO:asyncua.client.client:disconnect
INFO:asyncua.client.ua_client.UaClient:close_session
INFO:asyncua.client.ua_client.UASocketProtocol:close_secure_channel
INFO:asyncua.client.ua_client.UASocketProtocol:Request to close socket received
INFO:asyncua.client.ua_client.UASocketProtocol:Socket has closed connection
INFO:/home/david/python/opcua/main.py:user connect
ERROR:/home/david/python/opcua/main.py:could not post <coroutine object Client.connect at 0x79c47c74bed0> since asyncio loop in thread has not been started or has been stopped
Traceback (most recent call last):
File "/home/david/python/opcua/main.py", line 30, in <module>
client.connect()
File "/home/david/python/opcua/.venv/lib/python3.12/site-packages/asyncua/sync.py", line 110, in wrapper
result = self.tloop.post(aio_func(*args, **kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/david/python/opcua/.venv/lib/python3.12/site-packages/asyncua/sync.py", line 64, in post
raise ThreadLoopNotRunning(f"could not post {coro} since asyncio loop in thread has not been started or has been stopped")
asyncua.sync.ThreadLoopNotRunning: could not post <coroutine object Client.connect at 0x79c47c74bed0> since asyncio loop in thread has not been started or has been stopped
/home/david/python/opcua/main.py:33: RuntimeWarning: coroutine 'Client.connect' was never awaited
logger.exception(err)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "/home/david/python/opcua/.venv/lib/python3.12/site-packages/asyncua/sync.py", line 257, in disconnect
self.tloop.post(self.aio_obj.disconnect())
File "/home/david/python/opcua/.venv/lib/python3.12/site-packages/asyncua/sync.py", line 64, in post
raise ThreadLoopNotRunning(f"could not post {coro} since asyncio loop in thread has not been started or has been stopped")
asyncua.sync.ThreadLoopNotRunning: could not post <coroutine object Client.disconnect at 0x79c47c6720c0> since asyncio loop in thread has not been started or has been stopped
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/david/python/opcua/main.py", line 36, in <module>
client.disconnect()
File "/home/david/python/opcua/.venv/lib/python3.12/site-packages/asyncua/sync.py", line 260, in disconnect
self.tloop.stop()
File "/home/david/python/opcua/.venv/lib/python3.12/site-packages/asyncua/sync.py", line 58, in stop
self.loop.call_soon_threadsafe(self.loop.stop)
File "/usr/lib/python3.12/asyncio/base_events.py", line 840, in call_soon_threadsafe
self._check_closed()
File "/usr/lib/python3.12/asyncio/base_events.py", line 541, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'Client.disconnect' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
```
Version:
```
$ pip show asyncua
Name: asyncua
Version: 1.1.5
Summary: Pure Python OPC-UA client and server library
Home-page: http://freeopcua.github.io/
Author: Olivier Roulet-Dubonnet
Author-email: olivier.roulet@gmail.com
License: GNU Lesser General Public License v3 or later
Location: /home/david/python/opcua/.venv/lib/python3.12/site-packages
Requires: aiofiles, aiosqlite, cryptography, pyOpenSSL, python-dateutil, pytz, sortedcontainers, typing-extensions
Required-by:
```
```
$ uname -a
Linux DevLaptop 6.8.0-45-generic #45-Ubuntu SMP PREEMPT_DYNAMIC Fri Aug 30 12:02:04 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux
```
| error when re-connecting to server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1712/comments | 0 | 2024-09-25T04:07:33Z | 2024-09-25T04:07:33Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1712 | 2,546,850,404 | 1,712 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello everyone,
is it possible using the _PermissionRuleSet_ class to restrict the access of one user (e.g. UserRole.Operator1) to only certain nodes in the OPC UA AddressSpace by giving a concrete list of nodes in the _permission_dict?
[permission_rules.py](https://github.com/FreeOpcUa/opcua-asyncio/blob/1343fa761ce5b2ece79b64041463b86486b81534/asyncua/crypto/permission_rules.py)

[users.py](https://github.com/FreeOpcUa/opcua-asyncio/blob/1343fa761ce5b2ece79b64041463b86486b81534/asyncua/server/users.py)

| Modifiying SimpleRoleRuleSet to achieve role based security | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1711/comments | 0 | 2024-09-24T09:49:39Z | 2024-09-24T09:49:39Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1711 | 2,544,911,441 | 1,711 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
I'm currently having the following issue:
I am using `server.register_to_discovery(discovery_url)` successfully to register to an open62541 LDS.
The LDS runs on port 4840.
The registered server runs on port 4844: `INFO:asyncua.server.binary_server_asyncio:Listening on localhost:4844`
When I create a client and use `client.connect_and_find_servers()` the following information is returned from the LDS:
INFO:adapter_opc_ua: ApplicationUri: https://test/my_application_uri
INFO:adapter_opc_ua: ApplicationName: FreeOpcUa Python Server
INFO:adapter_opc_ua: ApplicationType: ClientAndServer
INFO:adapter_opc_ua: DiscoveryProfileUri: None
INFO:adapter_opc_ua: DiscoveryUrls: ['opc.tcp://localhost:4840']
However I would expect to return the discovery url opc.tcp://localhost:4844 such that I can in the next step fetch the endpoints to connect.
If I do the same client approach with open62541, the LDS returns the correct informations:
Server[1]:
Name: FreeOpcUa Python Server
Application URI: https://test/my_application_uri
Product URI: urn:freeopcua.github.io:python:server
Type: Client and Server
Discovery URLs:
[0]: opc.tcp://localhost:4844
What could be the reason for this? What could be the reason for this mismatch?
| LDS returns wrong discovery url of registered opcua-asyncio server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1708/comments | 0 | 2024-09-11T15:20:49Z | 2024-09-11T15:20:49Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1708 | 2,520,054,130 | 1,708 |
[
"FreeOpcUa",
"opcua-asyncio"
] | This is a _**BUG REPORT for issues in the existing code**_.
**Describe the bug** <br />
I'm using the `get_path(as_string=True)` function from the node class.
The function chooses a 'wrong' path so that the `translate_browsepaths()` function generates the status code "BadNoMatch"
The Prosys Browser can also export a browse path (right click on node) which does find a match via the `translate_browsepaths()` function.
The node 'exists' in both paths but only the path from prosys works.
**To Reproduce**<br />
Steps to reproduce the behavior incl code:
```
import asyncio
from asyncua import Client, ua
from asyncua.ua.status_codes import get_name_and_doc
async def main():
url = "opc.tcp://uademo.prosysopc.com:53530/OPCUA/SimulationServer/"
async with Client(url=url) as client:
# The node these paths should lead to:
# ns=4;s=1001/0:Direction
# Working path: /Objects/3:Simulation/3:Counter/2:Signal/4:Direction
results: ua.BrowsePathResult = await client.translate_browsepaths(
starting_node=client.nodes.root.nodeid,
relative_paths=[
"/Objects/3:Simulation/3:Counter/2:Signal/4:Direction",
"/0:Objects/0:Server/2:ValueSimulations/2:Signal/4:Direction",
],
)
for x in results:
print(get_name_and_doc(x.StatusCode.value), x)
# Output
# ('Good', 'The operation succeeded.') BrowsePathResult(StatusCode_=StatusCode(value=0), Targets= [BrowsePathTarget(TargetId=ExpandedNodeId(Identifier='1001/0:Direction', NamespaceIndex=4, NodeIdType= <NodeIdType.String: 3>, NamespaceUri=None, ServerIndex=0), RemainingPathIndex=4294967295)])
# ('BadNoMatch', 'The requested operation has no match to return.') BrowsePathResult(StatusCode_=StatusCode(value=2154758144), Targets=[])
if __name__ == "__main__":
asyncio.run(main())
```
The browse path that was exported from Prosys works: `/Objects/3:Simulation/3:Counter/2:Signal/4:Direction`
**Expected behavior**<br />
The function `get_path(as_string=True)` should generate a path that works with the `translate_browsepaths()` function.
**Screenshots**<br />
<img width="987" alt="image" src="https://github.com/user-attachments/assets/6ba8d7c6-3ae7-4a80-a888-11e5749193a2">
**Version**<br />
Python-Version:3.11.5<br />
opcua-asyncio Version (e.g. master branch, 0.9):
| get_path created BrowsePath finds not match via tranlate_browsepaths | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1706/comments | 12 | 2024-09-05T12:04:21Z | 2024-09-06T13:49:16Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1706 | 2,507,591,066 | 1,706 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When following the example (https://github.com/FreeOpcUa/opcua-asyncio/blob/master/examples/client_to_uanet_alarm_conditions.py) to subscribe to alarms and conditions events the client receives a BadEncoding error and disconnects.
**To Reproduce**<br />
The code I use is a bit more elaborate than this but this is the minimum required to get the error we are seeing:
```python
import asyncio
import os
import sys
from asyncua import Client, ua
URL = os.getenv("OPC_SERVER_ADDRESS")
class SubHandler:
async def event_notification(self, event):
print(event)
async def main():
async with Client(url=URL, ) as client:
alarmConditionType = client.get_node("ns=0;i=2915")
# Create subscription for AlarmConditionType
msclt = SubHandler()
sub = await client.create_subscription(0, msclt)
handle = await sub.subscribe_alarms_and_conditions(sourcenode=client.nodes.server, evtypes=alarmConditionType) # <-- this call fails with the badencodingerror
await asyncio.sleep(10)
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
```
After running this code the connection to the server is created, the node id to the root node is succesfully retrieved but we see an error message like this from the `subscribe_alarms_and_conditions` call:
```
CRITICAL:asyncua.client.ua_client.UASocketProtocol:Received an error: ErrorMessage(Error=StatusCode(value=2147876864), Reason='')
INFO:asyncua.client.ua_client.UASocketProtocol:Request to close socket received
ERROR:asyncua.client.ua_client.UASocketProtocol:Got error status from server: Encoding halted because of invalid data in the objects being serialized.(BadEncodingError)
```
**Expected behavior**<br />
I expect the subhandler to receive alarms when they change their respective values. Or at least the alarm subscription to be created without throwing an error
**Version**<br />
We are working with an Experion HS R520.2
python 3.12.3
opcua-asyncio Version: 1.1.5
| Receive BadEncoding error when subscribing to alarms | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1705/comments | 5 | 2024-09-03T14:48:13Z | 2024-09-04T11:23:41Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1705 | 2,503,085,353 | 1,705 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I encountered an issue with asyncua when installing in a Docker environment on arm devices (Raspberrypi 4/5).
The issue is not exactly related to asyncua, but rather `cryptography` because it gets compiled in rust.
The issue occurs on debian images. So here I provided a basic Dockerfile, which should work with all versions from `cryptography`.
Reasons:
- you need to have rust toolchain installed and not only cargo
- you need to have `libssl-dev` and `libeffi-dev` installed
- when rust compiles `cryptography` it looks for the openssl libraries with pkg-config so you need it too
```Dockerfile
FROM debian:bookworm-slim
RUN apt update
RUN apt install curl python3.11 python3-pip libffi-dev libssl-dev pkg-config -y
RUN curl -L sh.rustup.rs | sh -s -- -y
RUN PATH="/root/.cargo/bin:${PATH}" pip install asyncua --break-system-packages
```
related issues:
- #1283
here is what it would like if you only install cargo:
[https://github.com/rust-lang/rust/issues/64248](https://github.com/rust-lang/rust/issues/64248) | Using Docker with asyncua on arm! | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1701/comments | 0 | 2024-08-28T15:42:32Z | 2024-08-28T15:42:32Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1701 | 2,492,452,451 | 1,701 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hey,
im currently developing a project, where I start multiple server from a single project (main.py) file.
**Describe the bug**
For these server, is wrote some code to generate custom OPC UA Structures from a custom format. However, when i use the
await server.load_data_type_definitions() function, only the first server started will return the correct types.
**Screenshots**
Here are some screen shots from my example code:


**Expected behavior**
The expected behavior would be, that both servers can load the same customd ata types. However, only the first does.
Client are also only able to load the types from the first server (if multiple servers are started from a single script)
**To Reproduce**
Here is a small python project to reproduce the Error
[bug_report_python_opcua.zip](https://github.com/user-attachments/files/16766021/bug_report_python_opcua.zip)
**Version**
python 3.10.14
asyncua 1.1.5
| Error when loading custom data types from multiple server in single script | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1700/comments | 1 | 2024-08-27T16:38:42Z | 2024-10-28T09:01:38Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1700 | 2,489,878,143 | 1,700 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Hello, I am successfully connecting to my OPC server and would like to discover all the children nodes starting from a specific one.
To reduce network overheads, I want to use BrowseRequests, which allows me to send a batch of NodeIds in a single request, but when I do so, the References list of the BrowseResult is empty.
This problem doesn't occur when I use get_children to retrieve the children of a single node.
**To Reproduce**<br />
```python
root_node = client.get_node('ns=2;s=/my/node/')
print('Children', await root_node.get_children()) # Works!
browsing = await client.browse_nodes([root_node])
print('Browse', browsing) # References of the BrowseResult is an empty list ...
```
**Expected behavior**<br />
The References list should contain all the children nodes instead of being empty.
**Version**<br />
Python-Version: 3.10
opcua-asyncio: master branch (1.1.5)
| Client.browse_nodes returns no references when a node has children | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1699/comments | 9 | 2024-08-26T11:48:34Z | 2024-08-28T08:47:00Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1699 | 2,486,666,986 | 1,699 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Using a OPCUA open62541 C Client it is possible to create on a OPCUA open62541 C Server Objets Nodes and Variables Nodes with. The nodes are fully created with their properties i.e DisplayName or Value.
Using the same OPCUA open62541 C Client code on asyncua/FreeOpcua server, **nodes are created correctly but without their properties.** User is identifed with admin role by user manager.
Wireshark shows clearly the client message contains nodes properties, so problem may be on freeopcua stack, or I missed a sprecific parameter creating the python asyncua server.
Steps to reproduce the behavior incl code:
**open62541 stack client object node using displayName and description attributes.**
static UA_StatusCode addDeviceObjectNode(UA_Client *client, char* name, char *displayName, char *description) {
UA_NodeId deviceId;
UA_ObjectAttributes deviceAttr = UA_ObjectAttributes_default;
deviceAttr.displayName = UA_LOCALIZEDTEXT("en-US", displayName);
deviceAttr.description = UA_LOCALIZEDTEXT("en-US", description);
UA_StatusCode status = UA_Client_addObjectNode(client,
UA_NODEID_STRING(OPCUA_NAMESPACE, name), // NodeId
UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), // parentNodeId
UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), // referenceTypeId
UA_QUALIFIEDNAME(OPCUA_NAMESPACE, name), // browseName
UA_NODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE), // typeDefinition
deviceAttr, // attributes
&deviceId); // outNewNodeId, the new created node
if (status != UA_STATUSCODE_GOOD) {
nodesCreated = false;
} else {
}
return status;
}
**Asyncua server**
async def main():
_logger = logging.getLogger(__name__)
# setup our server
server = Server(user_manager=UserManager())
await server.init()
server.set_endpoint("opc.tcp://192.168.7.8:4840/")
# set up 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(20)
**Screenshots**<br />






[asyncua.log](https://github.com/user-attachments/files/16571671/asyncua.log)
**Version**<br />
Python-Version: 3.11.2
opcua-asyncio : 1.0.2
Thanks !
| opcua-asyncio/freeopcua stack major interoperability bug with open62541 stack : error on handling node attributes (BadAttributeIdInvalid) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1694/comments | 0 | 2024-08-11T05:52:01Z | 2024-08-11T05:52:01Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1694 | 2,459,438,250 | 1,694 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
I was testing the Client with an OPC UA server that implements **OPC 40100-1: Machine Vision - Control, Configuration management, recipe management, result management**
https://reference.opcfoundation.org/MachineVision/v100/docs/
NodeSet -> https://github.com/OPCFoundation/UA-Nodeset/tree/latest/MachineVision
The problem is that when I try to load the server data types (load_data_types_definitions() ) I get the following error:
```
File "C:\Users\aaa\ooo\vvv\EventTest.py", line 42, in main
await client.load_data_type_definitions()
File "C:\Users\aaa\AppData\Local\Programs\Python\Python311\Lib\site-packag
es\asyncua\client\client.py", line 864, in load_data_type_definitions
return await load_data_type_definitions(self, node, overwrite_existing=overw
rite_existing)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^
File "C:\Users\aaa\AppData\Local\Programs\Python\Python311\Lib\site-packag
es\asyncua\common\structures104.py", line 481, in load_data_type_definitions
env = await _generate_object(dts.name, dts.sdef, data_type=dts.data_type, lo
g_fail=log_ex)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^
File "C:\Users\aaa\AppData\Local\Programs\Python\Python311\Lib\site-packag
es\asyncua\common\structures104.py", line 295, in _generate_object
code = make_structure_code(data_type, name, sdef, log_error=log_fail)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\aaa\AppData\Local\Programs\Python\Python311\Lib\site-packag
es\asyncua\common\structures104.py", line 219, in make_structure_code
raise RuntimeError(f"Unknown datatype for field: {sfield} in structure:{stru
ct_name}, please report")
RuntimeError: Unknown datatype for field: StructureField(Name='Id', Description=
LocalizedText(Locale='', Text='Id is a system-wide unique name for identifying t
he recipe.'), DataType=NodeId(Identifier=3017, NamespaceIndex=2, NodeIdType=<Nod
eIdType.FourByte: 1>), ValueRank=-1, ArrayDimensions=[], MaxStringLength=0, IsOp
tional=False) in structure:BinaryIdBaseDataType, please report
Process finished with exit code 1
```
This structure data type BinaryIdBaseDataType is an abstract and is the parent to other data types such as "ConfigurationIdDataType".

Since the exception mentions to report it here i am.
Python-Version: 3.11.4
opcua-asyncio Version 1.1.0
| Error when loading DataTypes with the same name (different namespace). | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1693/comments | 2 | 2024-08-09T10:11:41Z | 2024-10-11T07:22:54Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1693 | 2,457,585,296 | 1,693 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I'm trying to instantiate an Object using an ObjectType defined in an XML NodeSet file created with UaModeler. The result differs from what UaModeler creates when I instantiate the same ObjectType directly in the model. Specifically, Organizes references from FunctionalGroups to Nodes that are Components of the ObjectType itself or e.g. a ParameterSet/MethodSet create new Nodes if I instantiate the type using asyncua, but not if instantiated directly in UaModeler.
**To Reproduce**<br />
I created a very stripped-down example in UaModeler that illustrates what I mean. The example can also be found on GitHub for anyone willing to play around with this themselves: https://github.com/FMeinicke/asyncua-references-instantiate-issue
The gist is that I have a custom Device type derived from OPC UA DI's DeviceType. This type overrides the Identification FunctionalGroup, the ParameterSet, and the MethodSet. For all of these, my type changes the ModellingRule to Mandatory. Additionally, I create the Operational FunctionalGroup.
In the Identification FunctionalGroup, I add Organizes references to the Properties of the Component type which are made Mandatory by the Device type.
The ParameterSet gets a Variable and a Property as its child nodes, and the MethodSets gets a method. All of these are references from the Operational FunctionalGroup using Organizes references again.
The final model looks like this:

To compare the instantiation of UaModeler to the one from asyncua, I also add an instance of MyDeviceType to the DeviceSet Object in UaModeler.
Using asyncua, I create a basic server that loads the OPC UA DI NodeSet XML and my custom one (note that I have to edit the XML file created by UaModeler to make it compatible with asyncua because UaModeler uses OPC UA v1.05.03 but asyncua only works with v1.05.02 - I left this out here for brevity).
```python
import asyncio
import logging
from pathlib import Path
import asyncua
from asyncua import Server, ua
_logger = logging.getLogger(__name__)
async def load_nodesets(server: Server) -> tuple:
nodeset_dir = Path(__file__).parent.joinpath("nodesets")
_logger.info("Importing OPC UA DI nodeset...")
await server.import_xml(nodeset_dir.joinpath("Opc.Ua.Di.v1.05.03.NodeSet2.xml"))
opc_ua_di_ns = await server.get_namespace_index("http://opcfoundation.org/UA/DI/")
_logger.info("Patching example nodeset...")
# ...
_logger.info("Importing example nodeset...")
await server.import_xml(nodeset_dir.joinpath("asyncua-references-instantiate-issue.xml"))
example_ns = await server.get_namespace_index("http://example.com/UA/")
return opc_ua_di_ns, example_ns
```
After this, I instantiate a second Object in the DeviceSet Object using MyDeviceType:
```python
async def instantiate_my_device(
device_name: str, server: Server, opc_ua_di_ns: int, example_ns: int
) -> asyncua.common.Node:
type_node = await server.nodes.base_object_type.get_child(
(
f"{opc_ua_di_ns}:TopologyElementType",
f"{opc_ua_di_ns}:ComponentType",
f"{opc_ua_di_ns}:DeviceType",
f"{example_ns}:MyDeviceType",
)
)
_logger.info(f"Instantiating new device node for {device_name}...")
device_set_node = await server.nodes.objects.get_child(f"{opc_ua_di_ns}:DeviceSet")
return await device_set_node.add_object(
ua.NodeId(5501, example_ns),
ua.QualifiedName(device_name, example_ns),
type_node,
instantiate_optional=False,
)
```
And the `main` function, just for completeness:
```python
async def main() -> None:
server = Server()
await server.init()
server.set_endpoint("opc.tcp://0.0.0.0:4840/example/server/")
opc_ua_di_ns, example_ns = await load_nodesets(server)
await instantiate_my_device("MyDevice2", server, opc_ua_di_ns, example_ns)
_logger.info("Starting server!")
async with server:
_logger.info("Server started!")
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
try:
asyncio.run(main())
except KeyboardInterrupt:
print()
```
I then connect to the server using UaExpert.
**Expected behavior**<br />
The two instances of MyDeviceType should be equal. Instead, only the instance created using UaModeler is correct.
As expected, it only creates nodes once and correctly uses the Organizes references to reference them from the FunctionalGroups as described above.
The instance created with asyncua doesn't show the same behavior. Instead, it creates multiple nodes within the ParameterSet/MethodSet and the FunctionalGroups.
As an example, this is the DeviceManual and SomeMethod nodes in the instance created in UaModeler. Here the NodeIds of the bodes in the FunctionalGroups are equal to the NodeIds of the nodes in the Object/MethodSet, which means that it's the same node being referenced.
<img width="48%" src="https://github.com/user-attachments/assets/ce039944-8ae3-463c-96b1-afd5dd3ac36e">
<img width="48%" src="https://github.com/user-attachments/assets/3951b458-0ff0-42be-bf04-1b5bfdccdf83">
<img width="48%" src="https://github.com/user-attachments/assets/ff4c4bd2-14af-439b-9722-e8e1856df225">
<img width="48%" src="https://github.com/user-attachments/assets/00e06672-b586-4427-8caf-35137b8f1f40">
On the other hand, in the instance created with asyncua, the NodeIds differ, indicating that it's not the same node but a different one. This is a problem since I rely on the fact that I can reference the same node from multiple places (e.g. FunctionalGroups) to provide structure to the parameters and methods in the ParameterSet and MethodSet.
<img width="48%" src="https://github.com/user-attachments/assets/c48fe1d0-b564-447c-8325-670d18936cf1">
<img width="48%" src="https://github.com/user-attachments/assets/6f9a60f2-b788-4210-b5f9-945692637034">
Another thing you'll notice is that the Identification FunctionalGroup is empty despite the DeviceType making some of the Properties (which are Optional in the base TopologyElementType) Mandatory. I think the problem here is that the instantiate logic in asyncua only looks at the ModellingRule of the node in the base type where it is originally defined but not at subtypes, which might override them. What's strange though, is that the Identification FunctionalGroup is also Optional in TopologyElement but then MyDeviceType makes it Mandatory - this is correctly handled by asyncua. And even though MyDeviceType also overrides DeviceRevision, Manufacturer, and Model (which are all referenced by the Identification FunctionalGroup), they're not instantiated.
My current workflow is to create the instances directly in the model using UaModeler, but I'd like to be able to dynamically instantiate Objects from my types using asyncua.
I looked into the code which handles the instantiation of nodes but I'm not sure how it could be changed to prevent instantiating duplicate nodes. This was my first idea: Since the ObjectType should be using the correct references to the correct nodes (meaning it doesn't have duplicate nodes), then the instantiation logic should be looking at the nodes it encounters in the type and check if their NodeIds are equal to other nodes in the type which it already instantiated and in this case don't instantiate another node but rather create the necessary reference to the already instantiated node. This sounds relatively simple in theory, but I feel this leads to quite some changes in the instantiation logic (due to the necessary bookkeeping of which nodes have been instantiated from which nodes in the type, etc.).
Since I haven't been using asyncua for too long,
So, my first question is, are my observations correct, and would you agree that the instantiation logic needs improvement?
And secondly, would my idea work to produce the desired result, and if so, could someone provide some guidance for implementing that change? Then I would try to propose a PR.
**Version**<br />
Python-Version: 3.10.11 on Windows 11<br />
opcua-asyncio Version (e.g. master branch, 0.9): 1.1.5
| Incorrect instantiation of ObjectType from an imported XML model | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1691/comments | 0 | 2024-08-08T08:37:09Z | 2024-08-08T08:37:09Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1691 | 2,455,211,197 | 1,691 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
We receive data change notificications from a Siemens S7 1517 (Firmware 2.9.4) OPC UA server with asyncua version 1.1.5.
Console output:
```
C:\>python scratchfile_opcua_client.py
Requested session timeout to be 3600000ms, got 30000ms instead
Revised values returned differ from subscription values: CreateSubscriptionResult(SubscriptionId=3410194732, RevisedPublishingInterval=200.0, RevisedLifetimeCount=1000, RevisedMaxKeepAliveCount=150)
datachange_notification for node ns=5;i=6010: DataValue(Value=Variant(Value=False, VariantType=<VariantType.Boolean: 1>, Dimensions=None, is_array=False), StatusCode_=StatusCode(value=0), SourceTimestamp=datetime.datetime(2024, 7, 24, 15, 44, 11, 97178, tzinfo=datetime.timezone.utc), ServerTimestamp=datetime.datetime(2024, 7, 24, 15, 44, 11, 97178, tzinfo=datetime.timezone.utc), SourcePicoseconds=None, ServerPicoseconds=None)
datachange_notification for node ns=5;i=6010: DataValue(Value=Variant(Value=False, VariantType=<VariantType.Boolean: 1>, Dimensions=None, is_array=False), StatusCode_=StatusCode(value=0), SourceTimestamp=datetime.datetime(2024, 7, 24, 15, 49, 21, 96451, tzinfo=datetime.timezone.utc), ServerTimestamp=datetime.datetime(2024, 7, 24, 15, 49, 21, 96451, tzinfo=datetime.timezone.utc), SourcePicoseconds=None, ServerPicoseconds=None)
```
**To Reproduce**<br />
You can use the following script to reproduce the issue. Please exchange the variables host, port and node id "ns=5;i=6010" with your node id in your OPCUA server.
```python
"""OPCUA client"""
import asyncio
import logging
from typing import List
from asyncua import Client, Node, ua
from asyncua.ua.uatypes import StatusCode
NodeList = List[str]
LOGGER = logging.getLogger()
class SubscriptionHandler:
"""The SubscriptionHandler is used to handle the data that is received for the subscription."""
async def datachange_notification(self, node: Node, value, data):
"""Callback for asyncua Subscription. This method will be called when the Client received a data change message from the Server."""
LOGGER.error("datachange_notification for node %s: %s", node.nodeid.to_string(), data.monitored_item.Value)
async def start_sub():
"""Start subscription"""
host = "10.18.168.71"
port = 4840
opcUrl = f"opc.tcp://{host}:{port}/"
client = Client(url=opcUrl, timeout=10)
params = ua.CreateSubscriptionParameters()
params.RequestedPublishingInterval = 100
params.RequestedLifetimeCount = 1000
params.RequestedMaxKeepAliveCount = 10000
params.MaxNotificationsPerPublish = 10000
params.PublishingEnabled = True
params.Priority = 0
nodesToSub: List[Node] = []
node = client.get_node(ua.NodeId.from_string("ns=5;i=6010"))
nodesToSub.append(node)
try:
async with client:
subscription = await client.create_subscription(params, SubscriptionHandler())
results = await subscription.subscribe_data_change(nodes=nodesToSub, sampling_interval=10)
for index, result in enumerate(results):
nodeid = nodesToSub[index].nodeid.to_string()
if isinstance(result, StatusCode):
LOGGER.error("Subscription error: %s", result.name)
else:
LOGGER.info("Node %s was subscribed successfully.", nodeid)
while True:
await asyncio.sleep(1)
await client.check_connection() # Throws a exception if connection is lost
except (ConnectionError, ua.UaError):
LOGGER.error("Connection lost - reconnecting in 2 seconds")
await asyncio.sleep(2)
except asyncio.exceptions.TimeoutError:
LOGGER.error("Timeout occured - reconnecting in 2 seconds")
await asyncio.sleep(2)
async def main():
"""Entry point"""
asyncList = [start_sub()]
await asyncio.gather(*asyncList)
if __name__ == "__main__":
asyncio.run(main())
```
**Expected behavior**<br />
We would expect if there is no Value change that the datachange_notification callback isn't called. We subscribed the node with the FreeOpcUa client (python lib opcua-client 0.8.4), which has the same issue. The tool Unified Automation UaExpert (version 1.4.21 324) doesn't show a data change notification when we subscribe there the same node in these cases. So we can simply exclude that it is a issue on PLC side. We also assume that the FreeOpcUa client uses the library asyncua, because it has the same issue as our script.
**Version**<br />
Python-Version: 3.8, 3.12
opcua-asyncio Version (e.g. master branch, 1.1.5):
| Received DataChangeNotification without Value has changed | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1686/comments | 12 | 2024-07-24T16:01:11Z | 2024-08-13T10:15:42Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1686 | 2,427,962,417 | 1,686 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi everyone, as far as you know, is there an available client example that discovers all the objects of a UA Server?
I made it manually but it is SLOW
```python
import asyncio
from asyncua import Client, ua
async def discover_all_objects_and_variables(endpoint):
async with Client(url=endpoint) as client:
# Get the root node
root = client.nodes.root
# Get the Objects node
objects = client.nodes.objects
print("Root node is: ", root)
print("Objects node is: ", objects)
async def browse(node, indent=0):
# Browse the children of the node
children = await node.get_children()
for child in children:
# Get the attributes of the node
node_class = await child.read_node_class()
node_id = child.nodeid
browse_name = await child.read_browse_name()
display_name = await child.read_display_name()
# Print the node information
output = " " * indent + f"Node: {display_name.Text} (ID: {node_id}, Class: {node_class})"
# If the node class is a variable, read its value and data type
if node_class == ua.NodeClass.Variable:
value = await child.read_value()
data_type = await child.read_data_type()
data_type_name = await client.get_node(data_type).read_display_name()
output += f", Value: {value}, DataType: {data_type_name.Text}"
# Print the node information
print(output)
# If the node class is an object or a variable, browse its children recursively
if node_class in [ua.NodeClass.Object, ua.NodeClass.Variable]:
await browse(child, indent + 1)
# Start browsing from the Objects node
await browse(objects)
# Define the endpoint of the OPC UA server
endpoint = "opc.tcp://localhost:4840/"
# Run the asynchronous function
asyncio.run(discover_all_objects_and_variables(endpoint))
```
I used the opcua-client-gui, and it is actually fast loading all the object/nodes tree… how it is done? | Is there a Client Discover Example? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1681/comments | 0 | 2024-07-23T10:53:15Z | 2024-07-23T12:29:03Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1681 | 2,424,893,707 | 1,681 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I would like to build a opcua-asyncio package for Fedora 40, however the constraints `cryptography>42.0.0` and `pyOpenSSL>23.2.0` are quite limiting. Are they really needed? Maybe they could be slightly relaxed.
If it is not possible, I will have to stay on asyncua 1.1.0.
# pyopenssl
[Fedora 40 provides](https://packages.fedoraproject.org/pkgs/pyOpenSSL/python3-pyOpenSSL/fedora-40.html) pyopenssl 23.2.0. The constraint for asyncua was added in 83539202 (#1593). In the diff between [23.2.0..23.3.0](https://github.com/pyca/pyopenssl/compare/23.2.0...23.3.0) is no mention of `X509_V_FLAG_NOTIFY_POLICY`.
Would it therefore be safe to relax the constraint to `pyopenssl>=23.2.0`, i.e. the version that is readily available in Fedora 40?
# cryptography
[Fedora 40 provides](https://packages.fedoraproject.org/pkgs/python-cryptography/python3-cryptography/fedora-40.html) cryptography 41.0.7. The constraint for cryptography was introduced in 9aedc20a (#1661). The [comment](https://github.com/FreeOpcUa/opcua-asyncio/pull/1661/commits/70c3a178b0f25c2f22a6f1ddb13574f3ec3e6ce1#r1646738504) suggests it was necessary because of the use of `not_valid_after_utc`. But maybe there is a way to support slightly older cryptography? | Relax some constraints on dependencies | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1679/comments | 1 | 2024-07-17T19:56:49Z | 2025-01-24T23:51:32Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1679 | 2,414,447,968 | 1,679 |
[
"FreeOpcUa",
"opcua-asyncio"
] | # Usage of NamespaceIndex for custom DataType-Classes
When I had two OPC UA servers import the same NodeSets but in different order and wanted to access them with clients, I realized that the handling of custom datatypes by the method `load_data_type_definitions()` could possibly be inconsistent.
As can be seen from the following class created by the method, the NamespaceIndex in the NodeId is used to identify the datatype. However, this is dependent on the order of the namespaces on the respective server. The definition of the same datatype can therefore be located on different servers in the same namespace, but does not have to have the same namespaceIndex. If the generated class is now to be used across servers, there are inconsistencies in the way the values are written.
```
@dataclass
class Box:
'''
Box structure autogenerated from StructureDefinition object
'''
data_type = ua.NodeId.from_string('''ns=5;i=3003''')
BoxID: ua.Int16 = ua.Int16(0)
Components: typing.List[ua.Component] = field(default_factory=list)
BoxType: ua.BoxType = ua.BoxType.Type_A
```
Is this intentional or should the namespaceUri be used here instead of the namespaceIndex to ensure consistency regardless of the import sequence?
I have already tried the parameter `overwrite_existing` of the `load_data_type_definitions()`-method, but unfortunately it solves the problem only superficially
I may also not understand exactly how it works, in which case an explanation could also help :)
## Example
When trying to read from the first server and write to the second, UaExpert shows the Value of the Variable with custom datatype `Box` as follows:

## Env
Using `Asyncua==1.1.5` | Possible inconsisent handling of custom datatypes on multiple servers using load_data_type_definitions() | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1678/comments | 2 | 2024-07-17T13:54:18Z | 2024-07-17T14:37:20Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1678 | 2,413,689,975 | 1,678 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I am have a question on top of this answer:
you can only use nodeids for direct read!
the only thing you can do use the translate browsepath to nodeid service to get the nodeid and then read.
_Originally posted by @AndreasHeine in https://github.com/FreeOpcUa/opcua-asyncio/discussions/1228#discussioncomment-5084140_
Basically our need is how we can read and write the values via browse name.
How to use the browse path in that case. | How to use browsepath to get the value of node id. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1673/comments | 8 | 2024-07-02T09:16:01Z | 2024-07-03T10:47:11Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1673 | 2,385,710,368 | 1,673 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello everyone!
First off, thanks a lot to every contributor of this repository; it's a great library that has helped us out tremendously in multiple projects. Secondly, I hope it's okay that I'm using an issue to open a discussion. I'd like to gather some insights from people who are more knowledgable than I am about OPC-UA and this library, hoping that I'll be able to contribute a well-rounded feature out of this discussion in the future.
The topic is handling connection issues and reconnecting properly. Right now, whenever our application loses the connection to the OPC-UA server, for example because the PLC config changed and it's reloading the server, we're reconnecting the client from our application once we try to interact with a node and it fails (we catch the UaError and simply try connecting up to a few times). This was fine until subscriptions came into play. With subscriptions, I'm really having a hard time finding the proper way to detect issues, reconnect and restart the subscriptions.
I've found the `Client._monitor_server_loop()` method, which is started as a task into `Client._monitor_server_task`. Once the connection dies, it'll inform the subscriptions of the `BadShutdown`. This seems to be about the only way to be informed about a connection issue other than emulating that behaviour externally to the client, polling and catching errors when they are raised. Another method of detecting connection issues is the `Client.check_connection()` method. But again, this method must be polled from the application external to the client.
I think ideally the client itself should provide a mechanism to allow applications to react to connection issues and states in general, i.e. callback when the client lost the connection. On top of that, it should then implement an optional reconnect mechanism that, when enabled, automatically attempts to reconnect upon losing connection, including restoring any subscriptions.
My current proposal would be the following:
- Add three `asyncio.Event` instances `Client.connected`, `Client.disconnected`, `Client.failed`. These events are `set()` when the respective connection state is reached and `clear()`-ed when the respectice state is left. This would allow application code to simply `await client.connected.wait()` before each interaction with the client. It would also allow to run error handler tasks once the connection fails with `await client.failed.wait()`.
- Maybe add a set of methods `Client.add_connected_callback()`, `Client.add_disconnected_callback()`, `Client.add_failed_callback()` to register callback functions which are called once the respective state is reached.
- Add a new optional parameter to `Client()` which could be as simple as `auto_reconnect: bool = False`.
- Whenever the `auto_reconnect` is enabled, an additional task `Client._auto_reconnect_task` will be created by the client upon connecting, which continously calls `Client.check_connection()` similiar to how the `Client._monitor_server_loop()` works, and in case of an error automatically tries connecting the client again.
- Probably a bit more configuration is required for that feature, so maybe add a dataclass `AutoReconnectSettings`. The following settings come to mind:
- How often to try reconnecting before giving up
- How long to wait in between connection attempts (maybe with exponential backoff?)
- Whether or not to restart the subscriptions after reestablishing the connection
- Maybe even allow deeper customization by pulling the reconnection logic into its own class `ClientReconnectHandler`, which would implement a simple strategy pattern to allow interchangeable reconnection mechanisms, providing a `ExponentialBackoffReconnectHandler` by default. The parameter could then have the signature of `auto_reconnect: bool | ClientReconnectHandler = False`, applying a default handler with default values when simply set to `True`.
I'd love to hear what you guys think about this and how you would approach this. Maybe someone has already implemented a similiar reconnect mechanism and would like to share their thoughts, I'd greatly appreciate that.
Thanks a lot! | How to properly handle connection issues and reconnecting? (request for comments) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1660/comments | 9 | 2024-06-18T18:51:37Z | 2024-08-17T18:29:16Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1660 | 2,360,490,672 | 1,660 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
`@uamethod` and `call_method` unpack tuple type and change the expected type.
**To Reproduce**<br />
Create a ua method that wraps something in a tuple. Execute the method. Result will not be packed into a tuple or list, but unpacked.
```
@uamethod
def put_into_tuple(parent, input: str) -> tuple[str]:
return (input,)
def test_tuple_behaviour(client, idx):
expected_result = ("test",)
res = client.nodes.objects.call_method(f"{idx}:put_into_tuple", "test")
assert res == expected_result
# FAILED tests/test_sync.py::test_tuple_behaviour - AssertionError: assert 'test' == ('test',)
```
**Expected behavior**<br />
Result is in a tuple or list e.g.
`res == ['test']` or `res == ('test', )`
**Version**<br />
Python-Version: 3.11
opcua-asyncio Version: master
**In detail**<br />
A tuple with a single item `("test",)` is converted into a list in [line 112](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/common/methods.py#L112). The list is than unpacked in [line 28](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/common/methods.py#L28) resulting in the loss of the tuple information. On the other hand, for a list with a single item like `["test"]` this works fine as the list is not unpacked, see [line 114](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/common/methods.py#L114).
For multiple elements this works as expected:
```
@uamethod
def put_multiple_into_tuple(parent, input1, input2) -> tuple[str]:
return (input1, input2)
def test_multiple_inputs_tuple_behaviour(client, idx):
expected_result = ["test1", "test2"]
res = client.nodes.objects.call_method(
f"{idx}:put_multiple_into_tuple", "test1", "test2"
)
assert res == expected_result
# Passed: ["test1", "test2"] == ["test1", "test2"]
```
Is this expected behaviour due to the OPC UA specification or a bug?
| `call_method` and `uamethod` unpack tuple type | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1659/comments | 4 | 2024-06-18T08:29:41Z | 2024-06-27T14:44:11Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1659 | 2,359,272,892 | 1,659 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When the server is closed / restarted by remote operators, the BadShutdown status is sent to the StatusChangeNotification. The tasks running in the threadloop are not closed, which causes the running program to hang. Some of the tasks are cancelled, which results in asyncio's CancelledError, which is not handled.
**To Reproduce**<br />
```
async def start(self, nodes):
...
return await self.api.subscribe(self, nodes, self.time_to_live)
```
```
async def subscribe(self, handler, node_names, lifetime):
try:
self.thread.post(self.do_subscribe(handler, node_names, lifetime))
except TimeoutError as e:
self.logger.error(
f"TimeoutError: no response from server after {self.post_timeout} seconds"
)
self.stop() # Close the connection to the server, never reached
...
```
```
async def do_subscribe(self, handler, node_names, lifetime):
client = await self.client() # method for connecting to the server
nodes = [client.get_node(f"ns={self.namespace_index};s={node_name}") for node_name in node_names]
subscription = await client.create_subscription(500, handler)
await subscription.subscribe_data_change(nodes)
await asyncio.sleep(lifetime)
await subscription.delete()
await asyncio.sleep(1)
```
This is the setup. The error occurs when the server is closed remotely.
**Expected behavior**<br />
All tasks are either executed or cancelled gracefully, such that the program does not hang.
**Screenshots**<br />
```
[OPCUA] [asyncua.client.client] [ERROR] Error in watchdog loop
Traceback (most recent call last):
File "/home/_/.pyenv/versions/3.12.2/lib/python3.12/asyncio/[tasks.py](http://tasks.py/)", line 520, in wait_for
return await fut
^^^^^^^^^
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/client/[client.py](http://client.py/)", line 552, in _monitor_serverloop
\ = await self.nodes.server_state.read_value()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/common/[node.py](http://node.py/)", line 207, in read_value
result = await self.read_data_value()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/common/[node.py](http://node.py/)", line 220, in read_data_value
return await self.read_attribute(ua.AttributeIds.Value, None, raise_on_bad_status)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/common/[node.py](http://node.py/)", line 342, in read_attribute
result = await self.session.read(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/client/ua_client.py", line 404, in read
data = await self.protocol.send_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/client/ua_[client.py](http://client.py/)", line 167, in send_request
data = await asyncio.wait_for(self._send_request(request, timeout, message_type), timeout if timeout else None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/.pyenv/versions/3.12.2/lib/python3.12/asyncio/[tasks.py](http://tasks.py/)", line 519, in wait_for
async with timeouts.timeout(timeout):
File "/home/_/.pyenv/versions/3.12.2/lib/python3.12/asyncio/[timeouts.py](http://timeouts.py/)", line 115, in aexit
raise TimeoutError from exc_val
TimeoutError
[OPCUA] [asyncua.common.subscription] [ERROR] Exception calling status change handler
Traceback (most recent call last):
File "/home/_/.pyenv/versions/3.12.2/lib/python3.12/asyncio/[tasks.py](http://tasks.py/)", line 520, in wait_for
return await fut
^^^^^^^^^
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/client/[client.py](http://client.py/)", line 552, in _monitor_serverloop
\ = await self.nodes.server_state.read_value()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/common/[node.py](http://node.py/)", line 207, in read_value
result = await self.read_data_value()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/common/[node.py](http://node.py/)", line 220, in read_data_value
return await self.read_attribute(ua.AttributeIds.Value, None, raise_on_bad_status)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/common/[node.py](http://node.py/)", line 342, in read_attribute
result = await self.session.read(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/client/ua_client.py", line 404, in read
data = await self.protocol.send_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/work/EEP_DataExtractor_pipeline/.venv/lib/python3.12/site-packages/asyncua/client/ua_[client.py](http://client.py/)", line 167, in send_request
data = await asyncio.wait_for(self._send_request(request, timeout, message_type), timeout if timeout else None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/_/.pyenv/versions/3.12.2/lib/python3.12/asyncio/[tasks.py](http://tasks.py/)", line 519, in wait_for
async with timeouts.timeout(timeout):
File "/home/_/.pyenv/versions/3.12.2/lib/python3.12/asyncio/[timeouts.py](http://timeouts.py/)", line 115, in aexit
raise TimeoutError from exc_val
TimeoutError
```
If applicable, add screenshots to help explain your problem. <br />
**Version**<br />
Python-Version: 3.12 <br />
opcua-asyncio Version (e.g. master branch, 0.9): 1.1.0
| Subscription tasks not closed properly on OPCUA server shutdown | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1652/comments | 2 | 2024-06-03T06:11:26Z | 2024-06-11T09:52:41Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1652 | 2,330,257,778 | 1,652 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi, so I've written a python program that connects to an SPS 1200 OPC UA Server and browses the node structure.
I want to read some node attributes after browsing the complete node structure starting with the objects node.
I've tried using the asyncio taskgroups for that since this really speeds up the process but I ran into the problem where the connection to the server would get disconnected.
My code:
```
async def gahter_node_data(self):
nodes = [] # <- List of Nodes
async with asyncio.TaskGroup() as group:
tasks = [group.create_task(self._collect_node_data(unbrowsed_node)) for unbrowsed_node in nodes]
# Iterate over results
for task in tasks:
# Get result from task
task.result()
async def _collect_node_data(self, node:Node):
# Define required attributes
required_attributes = [
AttributeIds.BrowseName,
AttributeIds.DisplayName,
AttributeIds.NodeClass,
AttributeIds.DataType,
AttributeIds.AccessLevel,
AttributeIds.ArrayDimensions
]
# Bulk request all attributes
node_attributes:List[ua.DataValue] = await node.read_attributes(required_attributes)
```
When I execute the code I get the following error:
```
Traceback (most recent call last):
| File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/tasks.py", line 490, 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 "...", in _collect_node_data
| node_attributes:List[ua.DataValue] = await node.read_attributes(required_attributes)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| File ".../Python/3.11/lib/python/site-packages/asyncua/common/node.py", line 359, in read_attributes
| results = await self.session.read(params)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| File ".../Python/3.11/lib/python/site-packages/asyncua/client/ua_client.py", line 404, in read
| data = await self.protocol.send_request(request)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| File ".../Python/3.11/lib/python/site-packages/asyncua/client/ua_client.py", line 167, in send_request
| data = await asyncio.wait_for(self._send_request(request, timeout, message_type), timeout if timeout else None)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/tasks.py", line 492, in wait_for
| raise exceptions.TimeoutError() from exc
| TimeoutError
```
When I iterate over each node and call the `_collect_node_data()`function it works fine but can take very long when gathering data from many nodes.
**Is there a better or an intended way of doing this kind of operation?** | Bulk reading node attributes causes disconnect | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1649/comments | 0 | 2024-05-27T14:30:38Z | 2024-05-27T17:23:12Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1649 | 2,319,297,854 | 1,649 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I am currently migrating a project from the opcua library to asyncua.sync. I've encountered an issue where the method get_objects_node() is not recognized, leading to an AttributeError. Below is a simplified version of the code snippet and the error message I'm encountering:
```
def setup_control__var(self, ns_index):
"""
This method sets up variables for controlling statuses. It aims to connect the update callback to a named variable in the server.
"""
obj = super().get_objects_node().add_object(ns_index, "CONTROL_STATUS_OBJECT")
```
Error Message
```
File "/path/to/server_opcua.py", line X, in __init__
self.setup_control__var(NAMESPACE_INDEX)
File "/path/to/server_opcua.py", line Y, in setup_control__var
obj = super().get_objects_node().add_object(ns_index, "CONTROL_STATUS_OBJECT")
AttributeError: 'super' object has no attribute 'get_objects_node'
```
Expected Behavior:
The code should access the base "Objects" node of the server and add a new object under this node.
Actual Behavior:
An AttributeError is thrown, indicating that get_objects_node() is not available.
Steps to Reproduce:
Migrate server setup code from opcua to asyncua.sync.
Implement server initialization with a call to setup_control_status_variables.
Run the server initialization process.
Environment:
Python version: 3.10
asyncua version: 1.1.0
Operating System: 23.04
Additional Context:
This functionality worked as expected in the opcua library, but seems to not be directly compatible or requires a different approach in asyncua.sync. Any guidance on how to correctly migrate this functionality would be greatly appreciated.
| Issue with Migrating from opcua to asyncua.sync: AttributeError when accessing get_objects_node | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1644/comments | 1 | 2024-05-15T08:28:28Z | 2024-06-08T09:04:50Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1644 | 2,297,209,279 | 1,644 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When I intend to only send a read request once, using the synchronous version, it tends to cause an infinite read and I have no idea how to fix it.
**To Reproduce**<br />
```
from asyncua.sync import Client, sync_uaclient_method, sync_async_client_method
from asyncua.client import Client as AsyncClient
import time
try:
client = Client(<ip>)
client.connect()
node_to_read = [client.get_node("ns=2;i=2")]
print(node_to_read)
read = sync_async_client_method(AsyncClient.read_values)(client)
read(nodes=node_to_read)
time.sleep(10)
client.disconnect()
except:
client.disconnect()
raise
```
**Expected behavior**<br />
I expect only 1 packet of read request sent from Client
**Screenshots**<br />
This is the Wireshark capture after sending 1 read request, and setting a time.sleep(10) before disconnecting.

**Version**<br />
Python-Version: 3.12.1
opcua-asyncio Version: 1.1.0
| Infinite Read Requests? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1642/comments | 10 | 2024-05-14T10:08:10Z | 2024-05-16T06:39:48Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1642 | 2,295,018,492 | 1,642 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi, I'm having a problem connecting the asyncua client to a third-party OPC UA server from a company. It looks like this company uses a open62541 based server (as specified by the `ApplicationName` from the logs).
**Behavior**
The access works as the following: The client generates the certificate and uses that to connect to the server. A popup appears on the third-party system to accept the certificate. Once accepted, I try connecting again and get the following error:
```bash
asyncua.ua.uaerrors._auto.BadIdentityTokenInvalid: The user identity token is not valid.(BadIdentityTokenInvalid)
```
**Client**
My client is mostly based on the certificate authentication example found in the repository.
```python
import asyncio
import logging
import sys
import socket
from pathlib import Path
from cryptography.x509.oid import ExtendedKeyUsageOID
sys.path.insert(0, "..")
from asyncua import Client
from asyncua.crypto.security_policies import SecurityPolicyBasic256Sha256
from asyncua.crypto.cert_gen import setup_self_signed_certificate
from asyncua.crypto.validator import CertificateValidator, CertificateValidatorOptions
from asyncua.crypto.truststore import TrustStore
from asyncua import ua
logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger(__name__)
cert_base = Path(__file__).parent
cert = Path(cert_base / f"certs/peer-certificate-2.der")
private_key = Path(cert_base / f"certs/peer-private-key-2.pem")
async def task(loop):
host_name = socket.gethostname()
client_app_uri = f"urn:{host_name}:myapp"
url = "opc.tcp://192.168.69.152:16664/"
await setup_self_signed_certificate(private_key,
cert,
client_app_uri,
host_name,
[ExtendedKeyUsageOID.CLIENT_AUTH],
{
'countryName': 'CN',
'stateOrProvinceName': 'AState',
'localityName': 'Foo',
'organizationName': "Bar Ltd",
})
client = Client(url=url)
client.application_uri = client_app_uri
await client.set_security(
SecurityPolicyBasic256Sha256,
certificate=str(cert),
private_key=str(private_key)
)
async with client:
print('Connection worked!')
await asyncio.sleep(2)
def main():
loop = asyncio.get_event_loop()
loop.set_debug(True)
loop.run_until_complete(task(loop))
loop.close()
if __name__ == "__main__":
main()
```
**Screenshots**
I have a UAExpert client that connects successfully even when I use **the same certificate** generated by the python client. This is how the configuration is there:

These are the warnings that appear regarding the IP address not matching what is on the certificate, but once I hit `Ignore` the connection is successful:


**Version**
Python version: 3.12.1
asyncua version: 1.1.0
I tried some things, including some old issues posted here (e.g. #742 and #227) but it looks like this case is different. Any help would be much appreciated! | BadIdentityTokenInvalid when connecting to open62541 based server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1639/comments | 3 | 2024-05-08T16:32:25Z | 2024-05-08T19:46:52Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1639 | 2,285,994,276 | 1,639 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Attempts to serialize an object with SecurityPolicyType or VariantType attributes fail. Enums cannot be serialized. Changing them to IntEnum makes them serializable, plus they are already effectively IntEnums based on their implementation (i.e. `named_attribute = int`).
**To Reproduce**<br />
```python
import json
from asyncua.ua import VariantType, SecurityPolicyType
json.dumps({"variant": VariantType.Boolean, "security_policy": SecurityPolicyType.None})
>>> `TypeError: Object of type VariantType is not JSON serializable`
OR
>>> `TypeError: Object of type SecurityPolicyType is not JSON serializable`
```
**Expected behavior**<br />
Serialization to succeed.
**Version**<br />
Python-Version:3.12
opcua-asyncio Version (e.g. master branch, 0.9): 1.1.0
| VariantType and SecurityPolicyType should be IntEnum | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1634/comments | 0 | 2024-05-01T15:43:00Z | 2024-05-01T19:24:13Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1634 | 2,273,720,064 | 1,634 |
[
"FreeOpcUa",
"opcua-asyncio"
] | New useful codes are introduced as of UA-1.05.03-2023-12-15
e.g.
BadServerTooBusy (0x80EE0000)
BadNoValue (0x80F00000)
https://github.com/OPCFoundation/UA-Nodeset/commit/7d389895a35fc5563b756e49b2369aa2263da77b#diff-eb27980c46c186ace4c8cdf0c9a2d6324fedfecfa621f0997ffee22a1a5d8ca8
latest version available from here:
https://github.com/OPCFoundation/UA-Nodeset/blob/latest/Schema/StatusCode.csv | Statuscodes/uaerrors should be regenerated from latest schema | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1633/comments | 0 | 2024-04-30T08:39:48Z | 2024-04-30T08:41:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1633 | 2,270,867,824 | 1,633 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Does anybody have an idea fo rmy problem.
Sometimes i get disconnects sometimes not.
Latest version of all libraries.
I want wo connect my script with an siemens s7 1215C plc.
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:01.242] DEBUG [__main__:930] Create OPCUA subscriptions
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:01.564] ERROR [iams.aio.opcua:98] Error evaluating datachanges
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | Traceback (most recent call last):
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/opcua.py", line 96, in datachange_notifications
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await self.parent.opcua_datachanges(changes)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/belt.py", line 1021, in opcua_datachanges
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | power, status = self.data.as_influx()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/data.py", line 336, in as_influx
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | "B1": int(self.B1),
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | AttributeError: 'Belt' object has no attribute 'B1'
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:01.769] ERROR [iams.aio.opcua:98] Error evaluating datachanges
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | Traceback (most recent call last):
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/opcua.py", line 96, in datachange_notifications
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await self.parent.opcua_datachanges(changes)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/belt.py", line 1021, in opcua_datachanges
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | power, status = self.data.as_influx()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/data.py", line 336, in as_influx
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | "B1": int(self.B1),
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | AttributeError: 'Belt' object has no attribute 'B1'
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:01.980] ERROR [iams.aio.opcua:98] Error evaluating datachanges
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | Traceback (most recent call last):
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/opcua.py", line 96, in datachange_notifications
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await self.parent.opcua_datachanges(changes)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/belt.py", line 1021, in opcua_datachanges
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | power, status = self.data.as_influx()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/data.py", line 336, in as_influx
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | "B1": int(self.B1),
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | AttributeError: 'Belt' object has no attribute 'B1'
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.159] INFO [market.mixins:955] All tasks started, load data from MES
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.159] DEBUG [iams.aio.interfaces:32] ERPLabCoroutine start running loop
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.160] INFO [__main__:813] Updating data from ERPLab
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.161] INFO [market.mixins:594] All tasks started, load data from MES
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.162] DEBUG [iams.aio.interfaces:32] OrderCoroutine start running loop
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.163] DEBUG [iams.aio.interfaces:32] GRPCCoroutine start running loop
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.163] INFO [iams.aio.manager:83] A Coroutine stopped - shutdown agent
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.166] ERROR [iams.aio.manager:93] Exception raised from coroutine OPCUACoroutine.call
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | Traceback (most recent call last):
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/tasks.py", line 490, in wait_for
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | return fut.result()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | asyncio.exceptions.CancelledError
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox |
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | The above exception was the direct cause of the following exception:
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox |
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | Traceback (most recent call last):
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/interfaces.py", line 27, in __call__
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await self.wait(setups)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/interfaces.py", line 66, in wait
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await asyncio.wait_for(tasks[str(self)], timeout=None)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/tasks.py", line 442, in wait_for
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | return await fut
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/interfaces.py", line 55, in _start
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await self.start()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/opcua.py", line 184, in start
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await self._parent.opcua_start()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/belt.py", line 931, in opcua_start
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await self.opcua_subscribe(self.opcnodes, 100)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/opcua.py", line 363, in opcua_subscribe
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | return await self._opcua.subscribe(nodes, interval)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/opcua.py", line 250, in subscribe
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | await subscription.subscribe_data_change(nodes)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/asyncua/common/subscription.py", line 212, in subscribe_data_change
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | return await self._subscribe(
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/asyncua/common/subscription.py", line 311, in _subscribe
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | mids = await self.create_monitored_items(mirs)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/asyncua/common/subscription.py", line 367, in create_monitored_items
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | results = await self.server.create_monitored_items(params)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/asyncua/client/ua_client.py", line 640, in create_monitored_items
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | data = await self.protocol.send_request(request)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/asyncua/client/ua_client.py", line 160, in send_request
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | data = await asyncio.wait_for(self._send_request(request, timeout, message_type), timeout if timeout else None)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/tasks.py", line 492, in wait_for
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | raise exceptions.TimeoutError() from exc
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | TimeoutError
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | Stack (most recent call last):
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "<frozen runpy>", line 198, in _run_module_as_main
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "<frozen runpy>", line 88, in _run_code
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/src/app/ims/belt.py", line 1419, in <module>
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | run()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/agent.py", line 95, in __call__
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | self.aio_manager(self, executor)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/manager.py", line 36, in __call__
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | loop.run_until_complete(self.main(parent, executor))
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/base_events.py", line 640, in run_until_complete
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | self.run_forever()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/base_events.py", line 607, in run_forever
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | self._run_once()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/base_events.py", line 1922, in _run_once
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | handle._run()
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/events.py", line 80, in _run
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | self._context.run(self._callback, *self._args)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/manager.py", line 93, in main
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | logger.error(
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.168] DEBUG [iams.aio.manager:103] Sending cancel to coroutine OrderCoroutine.call
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.168] DEBUG [iams.aio.manager:103] Sending cancel to coroutine GRPCCoroutine.call
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.168] DEBUG [iams.aio.manager:103] Sending cancel to coroutine MQTTCoroutine.call
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.168] DEBUG [iams.aio.manager:103] Sending cancel to coroutine prod_imsbelt-LN1-7.call
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.168] DEBUG [iams.aio.manager:103] Sending cancel to coroutine InfluxCoroutine.call
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.168] DEBUG [iams.aio.manager:103] Sending cancel to coroutine ERPLabCoroutine.call
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.169] DEBUG [iams.aio.interfaces:38] GRPCCoroutine is stopped
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.169] DEBUG [iams.aio.interfaces:36] MQTTCoroutine received the cancel signal
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.169] DEBUG [iams.aio.interfaces:38] MQTTCoroutine is stopped
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.169] DEBUG [iams.aio.interfaces:36] InfluxCoroutine received the cancel signal
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.169] DEBUG [iams.aio.interfaces:38] InfluxCoroutine is stopped
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.170] DEBUG [iams.aio.interfaces:160] ERPLabCoroutine() received the cancel signal
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.170] DEBUG [iams.aio.interfaces:38] ERPLabCoroutine is stopped
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.170] DEBUG [iams.aio.interfaces:160] OrderCoroutine() received the cancel signal
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.170] DEBUG [iams.aio.interfaces:38] OrderCoroutine is stopped
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.170] DEBUG [iams.aio.interfaces:160] <BeltServicer(prod_imsbelt-LN1-7)> received the cancel signal
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.170] DEBUG [iams.aio.interfaces:38] prod_imsbelt-LN1-7 is stopped
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.171] DEBUG [iams.aio.manager:37] Exit Coroutine-Manager
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.171] DEBUG [iams.agent:100] Removed pidfile /run/iams_agent.pid
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.171] DEBUG [iams.agent:104] Shutdown ...
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.171] DEBUG [iams.agent:106] Sending SIGKILL to kill all processes
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | [14:41:02.211] DEBUG [iams.aio.manager:136] Exception in asyncio
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | Stack (most recent call last):
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/lib/python3.11/asyncio/base_events.py", line 1808, in call_exception_handler
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | self._exception_handler(self, context)
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | File "/usr/local/lib/python3.11/dist-packages/iams/aio/manager.py", line 136, in exception_handler
prod_imsbelt-LN1-7.1.h1k1d03ibxdn@erplab-VirtualBox | logger.debug("Exception in asyncio", stack_info=True)
| Disconnect sometimes | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1620/comments | 1 | 2024-04-24T14:50:01Z | 2024-04-24T15:41:22Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1620 | 2,261,490,417 | 1,620 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When running mypy over code using asyncua I get;
`
...: error: Skipping analyzing "asyncua": module is installed, but missing library stubs or py.typed marker [import-untyped]
...: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
`
This is unneeded because asyncua provides excellent type info.
**To Reproduce**<br />
Run mypy for the following code;
`import asyncua`
**Expected behavior**<br />
No mypy errors.
**Version**<br />
Python-Version: Python 3.11.9 (tags/v3.11.9:de54cf5, Apr 2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)] on win32
opcua-asyncio Version (e.g. master branch, 0.9): asyncua==1.1.0
mypy==1.9.0
| py.typed marker missing | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1619/comments | 0 | 2024-04-18T07:47:25Z | 2024-04-24T20:05:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1619 | 2,249,994,856 | 1,619 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ### Discussed in https://github.com/FreeOpcUa/opcua-asyncio/discussions/1617
<div type='discussions-op-text'>
<sup>Originally posted by **lkaupp** April 16, 2024</sup>
Dear community,
i migrate my old freeopcua code to opcua-asyncio. Under freeopcua the following worked well (pseudo code):
```
class SubHandler:
"""
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: Node, val, data):
print(data)
Node.nodeid.to_string() -> save to text
read txt -> nodeid= NodeId.from_string(nodeid)
nodetosubscribe = Node(self._client.uaclient, nodeid)
handler = SubHandler()
self._opcua_subscription = self._client.create_subscription(100, handler)
self._opcua_handle = self._opcua_subscription.subscribe_data_change(nodetosubscribe)
```
In opcua-asyncio the code seems to working similarly (nodes will be subscribed, [function call takes different time with different amount of nodes subscribe to, equal to the amount in the freeopcua implementation]), but the datachange_notification on the Subhandler is never called. With UAExpert the changes on the same node can be monitored as usual, freeopcua implementation works as usual, but only the opcua-asyncio implementation seems to be not working. Is there something different in reinitializing the nodes from plain txt, is there more to do?
new code:
```
class SubHandler:
"""
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: Node, val, data):
print(data)
Node.nodeid.to_string() -> save to text
read txt -> nodeid= NodeId.from_string(nodeid)
async with self._client:
nodetosubscribe = Node(self._client.uaclient, nodeid)
handler = SubHandler()
self._opcua_subscription = await self._client.create_subscription(100, handler)
self._opcua_handle = await self._opcua_subscription.subscribe_data_change(nodetosubscribe)
```
</div> | Migration freeOpcua to opcua-asyncio subscribe_data_change SubHandler method not called after subscription | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1618/comments | 8 | 2024-04-17T09:58:12Z | 2024-04-23T09:53:58Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1618 | 2,247,885,906 | 1,618 |
[
"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 />
We are running asyncua in a Docker container using an image based on `python:3.10-slim-bullseye`.
Because the person who developed and monitored this solution has left the company, I can't say when it was last working. All I know is that:
- We have a bunch of IoT devices to which we can connect via TCP and retrieve data.
- We have a Python repository used as an interface for reading this data from the devices (which I'll call the "ethernet adapter").
- We have a Python repository (the "OPC UA repo") that uses asyncua to populate nodes/values. This repo has a loop that uses the ethernet adapter to read device data.
- To release the OPC UA repo, we build its Docker image and push it to an image repository in the cloud.
- Finally, a "master repo" pulls the image from the cloud, along with several other images, and runs it using Docker Compose.
After launching the "master" application, which coordinates images (including the OPC UA repo that uses asyncua), I look at its logs and see this error and traceback for the OPC UA container:
```
Exception in subscription loop
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/asyncua/server/internal_subscription.py", line 88, in _subscription_loop
await self.publish_results()
File "/usr/local/lib/python3.10/site-packages/asyncua/server/internal_subscription.py", line 135, in publish_results
await self.pub_result_callback(result, requestdata)
File "/usr/local/lib/python3.10/site-packages/asyncua/server/uaprocessor.py", line 94, in forward_publish_response
self.send_response(requestdata.requesthdr.RequestHandle, requestdata.seqhdr, response)
File "/usr/local/lib/python3.10/site-packages/asyncua/server/uaprocessor.py", line 49, in send_response
struct_to_binary(response), message_type=msgtype, request_id=seqhdr.RequestId)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 336, in struct_to_binary
return serializer(obj)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 401, in serialize
return data_size + b''.join(type_serializer(el) for el in val)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 401, in <genexpr>
return data_size + b''.join(type_serializer(el) for el in val)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 569, in extensionobject_to_binary
body = struct_to_binary(obj)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 336, in struct_to_binary
return serializer(obj)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 401, in serialize
return data_size + b''.join(type_serializer(el) for el in val)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 401, in <genexpr>
return data_size + b''.join(type_serializer(el) for el in val)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 336, in struct_to_binary
return serializer(obj)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 276, in <lambda>
return lambda val: b'' if val is None else serializer(val)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 485, in variant_to_binary
body = pack_uatype(var.VariantType, var.Value)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 191, in pack_uatype
return create_uatype_serializer(vtype)(value)
File "/usr/local/lib/python3.10/site-packages/asyncua/ua/ua_binary.py", line 128, in pack
return struct.pack(self.format, data)
struct.error: required argument is not an integer
```
This error tells me very little. (Some more error information about what was happening at the time of the error would be helpful.)
I can still connect to the server and list the nodes, but all values are absent with `Datatype = Null`, `Statuscode = BadWaitingForInitialData`, and `Server Timestamp = 8:00:00.000 PM`
I know for a fact that it was working a few weeks ago. Since then, a few things have changed, but I have carefully looked at the changes and cannot find one that I would expect to cause any problems. Specifically, the ethernet adapter has been updated, and two new nodes have been added.
But that's all irrelevant because I just tried to deploy an older version without these recent changes, and it still fails. At that point, the server hadn't been changed in several months.
I understand this may not be sufficient information to reproduce, but I'm hoping someone with a better understanding of asyncua than me has some inkling. I'll happily provide more information, I just don't know what to provide.
**To Reproduce**<br />
Steps to reproduce the behavior incl code:
This will be tricky since it worked before these changes.
Here's some code:
```python
class GHOPCServer:
async def __aenter__(self):
await self.init()
await self.server.start()
return self
# Plus lots of irrelevant logic
async def opcua_server_app(args):
async with GHOPCServer(args) as gh_opc_server:
config = GHConfig(gh_opc_server)
await config.install()
gh_poller = GHPoller(config)
await config.reload_from_local_storage()
logger.info("OPCUA Core Setup Complete, registering server wide callback")
await gh_opc_server.register_server_wide_callback(
"Reconfigure", config.reconfig, [ua.VariantType.ByteString], [ua.VariantType.String]
)
logger.info("OPCUA Setup Complete, Beginning Polling Loop")
next_master_update = datetime.datetime(1970, 1, 1)
next_node_update = datetime.datetime(1970, 1, 1)
next_cert_reconcile_update = datetime.datetime.now() + datetime.timedelta(minutes=10)
endpoints = await gh_opc_server.server.get_endpoints()
logger.info("Server endpoints: %s", endpoints)
while True:
if datetime.datetime.now() > next_master_update:
await gh_poller.poll_master_realtime_and_update()
next_master_update = datetime.datetime.now() + datetime.timedelta(minutes=2)
if datetime.datetime.now() > next_node_update:
# poll at 28 and 58
poll_time = datetime.datetime.now()
await gh_poller.poll_send_node_data_and_update()
if 28 <= poll_time.minute <= 57:
next_node_update = poll_time.replace(minute=58, second=0, microsecond=0)
else: # poll_time must be around the 58-59 point or so... add 20 minutes and reset
next_node_update = (poll_time + datetime.timedelta(minutes=20)).replace(
minute=28, second=0, microsecond=0
)
if datetime.datetime.now() > next_cert_reconcile_update:
await gh_opc_server.add_client_certs_in_path()
next_cert_reconcile_update = datetime.datetime.now() + datetime.timedelta(
minutes=10
)
await asyncio.sleep(10)
class GHPoller:
"""Class for centralizing logic for polling the GH masters & nodes and storing the received data against the OPCUA server."""
def __init__(self, config: GHConfig):
self.config = config
async def _update_node_nodes_from_polled_data(self, data_dict):
"""Update node controllers"""
for master_ip, result_dict in data_dict.items():
node_id_to_node_dict = self.config.master_nodes_by_ip[master_ip]["nodes"]
for node_id, polling_result in result_dict["results"].items():
node = node_id_to_node_dict[int(node_id)]
await _update_base_props(node, polling_result)
if isinstance(polling_result, MasterSocketError):
continue # skip processing of individual props due to polling failure
for node_prop_key, content in NODE_DATA_PROPS_FROM_SPEC.items():
variant_type, conversion_func = content
val = conversion_func(polling_result)
await _update_object_param(node, node_prop_key, val, variant_type)
async def poll_master_realtime_and_update(self):
"""Poll the masters and update the OPCUA objects with the results."""
ips_to_poll = list(self.config.master_nodes_by_ip.keys())
if ips_to_poll:
master_data = await poll_masters(ips_to_poll)
await self._update_master_nodes_from_polled_data(master_data)
else:
logger.warning("No masters to poll, skipping poll_master_realtime_and_update")
async def poll_send_node_data_and_update(self):
"""Poll the masters for node data"""
node_meta = {
master_ip: list(master_node_dict["nodes"].keys())
for master_ip, master_node_dict in self.config.master_nodes_by_ip.items()
}
master_data = await poll_nodes(node_meta)
await self._update_node_nodes_from_polled_data(master_data)
async def poll_nodes(node_meta):
"""Polls masters for the cached node_data on the master. Returns a dictionary of the results."""
master_data = {}
threads = []
for master_ip, node_ids in node_meta.items():
thread = Thread(target=_poll_master_for_node_data, args=[master_ip, node_ids, master_data])
thread.daemon = True
thread.start()
threads.append(thread)
# Cannot call thread.join() as it is a blocking call and that would prevent the async server
# from handling requests. Instead, we'll run a busy loop here while the threads are alive.
while True:
for thread in threads:
if thread.is_alive():
break
else: # all threads are dead, let's abort
break
await asyncio.sleep(0.1)
return master_data
```
**Expected behavior**<br />
A clear and concise description of what you expected to happen.
When viewed using UaExpert, these columns should be populated as there are no polling errors:

(and many more)
**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
See also the expected behavior.

(Notice that it continues to fail to write a bunch of None values. These None errors are expected.)
**Version**<br />
Python-Version:<br />3.10
opcua-asyncio Version (e.g. master branch, 0.9): 1.1.0
| Exception in subscription loop: struct.error: required argument is not an integer | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1614/comments | 4 | 2024-04-12T18:56:10Z | 2024-05-02T17:42:38Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1614 | 2,240,732,258 | 1,614 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
The process of acquiring a read_data_type() of node stayed stuck and i don't know why.
I don't know if it's my dumb approach.
**To Reproduce**<br />
I have a module python (x.py) that calls the object My_OPCUA_Client, as follow:

My Object My_OPCUA_Client.

After creating the OPCUA client instance i call from x.py the function getNodeId() which is async, as shown above:

After that, the python interpreter stayed stuck. The result that i obtained is:

So, it starts the awaitable coroutine read_data_type() but doesn't return.
**Expected behavior**<br />
Obtaining the data type of node asynchronously
**Version**<br />
Python-Version:3.11.5
asyncua:1.0.4
asyncio:1.5.8
Thanks for any help. | Stuck in obtaining the read_data_type() of node. Related to asyncio feature. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1612/comments | 5 | 2024-04-09T09:01:19Z | 2024-05-17T22:23:11Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1612 | 2,232,954,155 | 1,612 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I have a template object that I want to clone multiple times to create my device nodes.
I have the following server code snippet:
```python
await self.server.import_xml(os.path.join(self.model_filepath, "../my_model.xml"))
node = await copy_node(await self.server.nodes.objects.get_child(["3:DeviceSet", "3:MyDeviceSet"]),
await self.server.nodes.objects.get_child(["3:DeviceSet", "3:MyDeviceSet","6:Template"]),
ua.NodeId(0, 6),
True)
await node[0].write_attribute(ua.attribute_ids.AttributeIds.DisplayName, ua.DataValue(ua.Variant(ua.LocalizedText("Device A"))))
await node[0].write_attribute(ua.attribute_ids.AttributeIds.BrowseName, ua.DataValue(ua.Variant(ua.QualifiedName("Device A", 6))))
```
My model loads correctly and the Template node is displayed with it's initial display and browsename.
But the copy of my template does also still have this name displayed in the UaExpert client address space on the right, although the values are different in the attributes view on the left.
I also tried the python opensource client and it shows the same behaviour. Why do these two views converge when I update the attributes?
| When copy_node is used, BrowseName is not updated | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1611/comments | 0 | 2024-04-03T14:54:20Z | 2024-04-03T14:54:20Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1611 | 2,223,158,659 | 1,611 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I am trying to run server-with-encryption.py and start the server via _python server-with-encryption.py_ command from terminal. I got requested parent node does not exist issue.
I tried debugging by keeping a breaking point at
# populating our address space
myobj = await server.nodes.objects.add_object(idx, "MyObject"), then I got the below debug report. It says OSError: [Errno 10048] error while attempting to bind on address ('0.0.0.0', 4840): only one usage of each socket address (protocol/network address/port) is normally permitted.
C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\venv\Scripts\python.exe "C:/Program Files/JetBrains/PyCharm Community Edition 2022.3.3/plugins/python-ce/helpers/pydev/pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 59154 --file C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\server-with-encryption.py
Connected to pydev debugger (build 223.8836.43)
INFO:asyncua.server.internal_session:Created internal session Internal
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=11715, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15958, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15959, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15960, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15961, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15962, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15963, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=15964, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=16134, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=16135, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.address_space:add_node: while adding node NumericNodeId(Identifier=16136, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>), requested parent node NumericNodeId(Identifier=15957, NamespaceIndex=0, NodeIdType=<NodeIdType.Numeric: 2>) does not exists
INFO:asyncua.server.internal_server:starting internal server
ERROR:asyncua.server.server:OPC UA Server(opc.tcp://0.0.0.0:4840/freeopcua/server/) error starting server
Traceback (most recent call last):
File "C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\..\asyncua\server\server.py", line 551, in start
await self.bserver.start()
File "C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\..\asyncua\server\binary_server_asyncio.py", line 139, in start
self._server = await asyncio.get_running_loop().create_server(self._make_protocol, self.hostname, self.port)
File "C:\Users\Prasad.DV\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1506, in create_server
raise OSError(err.errno, 'error while attempting '
OSError: [Errno 10048] error while attempting to bind on address ('0.0.0.0', 4840): only one usage of each socket address (protocol/network address/port) is normally permitted
INFO:asyncua.server.internal_server:stopping internal server
INFO:asyncua.server.internal_session:close session Internal
INFO:asyncua.server.subscription_service:delete subscriptions: []
Traceback (most recent call last):
File "C:\Users\Prasad.DV\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Prasad.DV\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\server-with-encryption.py", line 82, in main
async with server:
File "C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\..\asyncua\server\server.py", line 220, in __aenter__
await self.start()
File "C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\..\asyncua\server\server.py", line 555, in start
raise exp
File "C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\..\asyncua\server\server.py", line 551, in start
await self.bserver.start()
File "C:\Users\Prasad.DV\PycharmProjects\OPCUA_Client_Automation\examples\..\asyncua\server\binary_server_asyncio.py", line 139, in start
self._server = await asyncio.get_running_loop().create_server(self._make_protocol, self.hostname, self.port)
File "C:\Users\Prasad.DV\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1506, in create_server
raise OSError(err.errno, 'error while attempting '
OSError: [Errno 10048] error while attempting to bind on address ('0.0.0.0', 4840): only one usage of each socket address (protocol/network address/port) is normally permitted
python-BaseException
Process finished with exit code 1
Can somebody help me in resolving this issue | Parent node does not exist issue while starting using server-with-encryption.py | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1610/comments | 1 | 2024-04-02T04:22:51Z | 2024-05-02T17:44:33Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1610 | 2,219,533,105 | 1,610 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
Its taking time to add channel or object Is there any alternative to do the following:

Code:
await extchannels.add_object(ua.NodeId(NamespaceIndex=ns),'2:ExternalChannel_%s' % num,external_channels)
Here I am using async await to add_object.
There are nearly 12 objects to add and it can be increased upto very high number of channels(objects), On an average its taking 1.5sec for each channel(object) to add just like the following screenshot.

| Replacement for add_object | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1605/comments | 0 | 2024-03-21T12:48:42Z | 2024-03-22T13:42:52Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1605 | 2,200,109,944 | 1,605 |
[
"FreeOpcUa",
"opcua-asyncio"
] | all async as per title
**Describe the bug** <br />
When running both server and client under pytest polling values and change notifications fail with timeout.
**To Reproduce**<br />
- Clone https://gitlab.com/advian-oss/python-asynuapytestexample/-/tree/test_demo?ref_type=heads (note the branch)
- poetry install
- poetry run py.test -v
Or see https://gitlab.com/advian-oss/python-asynuapytestexample/-/merge_requests/1 CI test results
**Expected behavior**<br />
Running both server and client under same eventloop should work normally.
**Version**<br />
Python-Version: 3.11<br />
opcua-asyncio Version (e.g. master branch, 0.9): asyncua==1.1.0
| Race/block condition when running client and server in same asyncio eventloop (under pytest) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1603/comments | 2 | 2024-03-15T12:32:30Z | 2024-03-15T16:40:26Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1603 | 2,188,414,692 | 1,603 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello
I would like to use encryption with security policy Basic256Sha256 + username / password authentication and not certificate exchange.
**To Reproduce**<br />
When I use the below mentioned code, it's trying to load the certificates / key. Returns the error `Error: [Errno 2] No such file or directory: 'None'`
```
security_policy = "Basic256Sha256"
security_mode = "SignAndEncrypt"
await client.set_security_string(f"{security_policy},{security_mode}," + str(None) + "," + str(None))
```
**Version**<br />
Python-Version: 3.12
opcua-asyncio Version: 1.1.0
| Encryption with username/password (not certificate) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1598/comments | 1 | 2024-03-05T11:28:38Z | 2024-03-05T12:34:17Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1598 | 2,168,961,128 | 1,598 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I am connecting to an OPC UA server of a B&R PLC but receiving the error: UASocketProtocol:ServiceFault (BadSessionNotActivated ...). The same code works fine when connecting to an opcua-asyncio server and not to the B&R PLC. However, the implementation of the B&R PLC seem also to be correct, because when connecting with UA Expert everything works as expected. Also, those PLCs are professional grade products which are up-to-date regarding the software stack.
Interestingly, when the PLC is configured to allow security None, also the opcua-asyncio client framework can access the real B&R PLC without any issues.
Any help would be really appreciated, although I know it might be difficult to reproduce without an actual B&R PLC. I've not yet access to the server logs. I will add them when available.
**To Reproduce**<br />
Code to reproduce it is more or less the same like in [client-with-encryption.py](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/examples/client-with-encryption.py) in the examples folder. Nevertheless, here is the code:
```python
client = Client(url=url)
client.set_user('***')
client.set_password('***')
host_name = socket.gethostname()
client_app_uri = f"urn:{host_name}:client"
certificate: Path = Path(Path(__file__).parent.parent / "./key/cert.pem")
private_key: Path = Path(Path(__file__).parent.parent / "./key/key.pem")
client.application_uri = client_app_uri
await setup_self_signed_certificate(private_key,
certificate,
client_app_uri,
host_name,
[ExtendedKeyUsageOID.CLIENT_AUTH],
{
'countryName': '***',
'stateOrProvinceName': '***',
'localityName': '***',
'organizationName': '***',
'commonName': '***'
})
await client.set_security(
SecurityPolicyBasic256Sha256,
private_key=str(private_key),
certificate=str(certificate))
```
**Expected behavior**<br />
A secure connection
**Exception Stack**<br />
```
INFO:asyncua.client.ua_client.UaClient:activate_session
WARNING:asyncua.client.ua_client.UASocketProtocol:ServiceFault (BadSessionNotActivated, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=None, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None)) from server received in response to ReadRequest
ERROR:asyncua.client.client:Error in watchdog loop
Traceback (most recent call last):
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\client.py", line 551, in _monitor_server_loop
_ = await self.nodes.server_state.read_value()
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\common\node.py", line 207, in read_value
result = await self.read_data_value()
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\common\node.py", line 220, in read_data_value
return await self.read_attribute(ua.AttributeIds.Value, None, raise_on_bad_status)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\common\node.py", line 342, in read_attribute
result = await self.session.read(params)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 404, in read
data = await self.protocol.send_request(request)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 172, in send_request
self.check_answer(data, f" in response to {request.__class__.__name__}")
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 181, in check_answer
hdr.ServiceResult.check()
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\ua\uatypes.py", line 375, in check
raise UaStatusCodeError(self.value)
asyncua.ua.uaerrors._auto.BadSessionNotActivated: The session cannot be used because ActivateSession has not been called.(BadSessionNotActivated)
INFO:asyncua.client.ua_client.UaClient:close_session
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 CloseSessionRequest
INFO:asyncua.client.ua_client.UASocketProtocol:close_secure_channel
INFO:asyncua.client.ua_client.UASocketProtocol:Request to close socket received
ERROR:mylogger:error
Traceback (most recent call last):
File "C:\Users\eduar\scoop\apps\python310\current\lib\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 "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\client.py", line 312, in connect
await self.activate_session(username=self._username, password=self._password, certificate=self.user_certificate)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\client.py", line 631, in activate_session
return await self.uaclient.activate_session(params)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 346, in activate_session
data = await self.protocol.send_request(request)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 167, in send_request
data = await asyncio.wait_for(self._send_request(request, timeout, message_type), timeout if timeout else None)
File "C:\Users\eduar\scoop\apps\python310\current\lib\asyncio\tasks.py", line 458, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\test-code\opc-ua-connect-bulk.py", line 76, in main
async with client:
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\client.py", line 94, in __aenter__
await self.connect()
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\client.py", line 315, in connect
await self.close_session()
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\client.py", line 703, in close_session
return await self.uaclient.close_session(True)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 366, in close_session
data = await self.protocol.send_request(request)
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 172, in send_request
self.check_answer(data, f" in response to {request.__class__.__name__}")
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\client\ua_client.py", line 181, in check_answer
hdr.ServiceResult.check()
File "C:\Users\eduar\git\JRZ\streaming-based-ml\code\data-logger\venv\lib\site-packages\asyncua\ua\uatypes.py", line 375, in check
raise UaStatusCodeError(self.value)
asyncua.ua.uaerrors._auto.BadSessionIdInvalid: The session id is not valid.(BadSessionIdInvalid)
INFO:asyncua.client.client:disconnect
INFO:asyncua.client.ua_client.UaClient:close_session
WARNING:asyncua.client.ua_client.UaClient:close_session but connection wasn't established
WARNING:asyncua.client.ua_client.UaClient:close_secure_channel was called but connection is closed
INFO:asyncua.client.ua_client.UASocketProtocol:Socket has closed connection
```
**Version**<br />
Python-Version: 3.10.11
python-opcua: latest from master: asyncua @ git+https://github.com/FreeOpcUa/opcua-asyncio.git@master
| Connecting to a real PLC: UASocketProtocol:ServiceFault, BadSessionNotActivated | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1594/comments | 5 | 2024-02-27T15:15:54Z | 2025-05-19T14:56:27Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1594 | 2,156,862,138 | 1,594 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi as the title says, I want to compare the values of two nodes.
I want to make sure that python does nothing unintendet in the background with the node datatypes.
For example when comparing nodes with different types of int: int16, int32, int64, Uint16, Uint32, Uint64.
I'm worried that the python "==" could create false positive or general negative results when comparing plain values of nodes
Example
```
value1 = node1.read_data_value().Value.Value
value2 = node2.read_data_value().Value.Value
print(value1 == value2)
value1 = node1.get_value()
value2 = node2.get_value()
print(value1 == value2)
```
Is there a better way to compare two ua.DataValue() or ua.Variant() that keeps the datatype of the value in mind?
Instances of these classes can't be compared directly since they also have a timestamp that might not be important for comparing their values.
Sth like this:
```
value1 = node1.read_data_value().Value.Value
value2 = node2.read_data_value().Value.Value
print(ua.uatypes.compare_variants(value1, value2)).
# Returns True if both values are the same when cast to the same datatype
``` | Intendet way for comparing values of two nodes | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1592/comments | 2 | 2024-02-27T14:31:11Z | 2024-03-01T21:14:52Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1592 | 2,156,748,088 | 1,592 |
[
"FreeOpcUa",
"opcua-asyncio"
] | It's been a little over two month since the last release.
@oroulet and @schroeder- Are there PRs you'd see as blocking a potential next release?
I'd start testing the current master-branch as release candidate until you answered. | 1.1.0/(1.0.7) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1589/comments | 3 | 2024-02-22T10:11:29Z | 2024-02-29T08:44:19Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1589 | 2,148,695,836 | 1,589 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ### BadNodeIdUnknown
 | Node Id refers to a node that does not exists in the server address space.(BadNodeIdUnknown) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1585/comments | 2 | 2024-02-20T09:58:24Z | 2024-02-20T10:28:38Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1585 | 2,143,990,240 | 1,585 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ### Could not be imported!
---
**self.server = Server()
await self.server.init()
self.server.set_endpoint(self.endpoint)
await self.server.import_xml(self.xmlfile)**
In import_xml method I am getting following error:
**The following references could not be imported and are probably broken.**

| The following references could not be imported and are probably broken. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1584/comments | 6 | 2024-02-20T08:29:57Z | 2024-02-20T10:27:25Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1584 | 2,143,800,640 | 1,584 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi there,
I am running an [asyncua](https://github.com/FreeOpcUa/opcua-asyncio) client to connect to my Kepware KEPServerEX 6.15 installed in my local machine. I can run and read values successfully with certificate and key when using [opcua](https://github.com/FreeOpcUa/python-opcua). However, I wanted to implement it asynchronously.
**Using [opcua](https://github.com/FreeOpcUa/python-opcua): Working**
client.py
````
from datetime import datetime
from opcua import Client
url = "opc.tcp://192.168.100.139:49320"
client = Client(url)
client.set_user("Administrator")
client.set_password("admin1234!@#$")
client.set_security_string("Basic256Sha256,SignAndEncrypt,cert.der,key.pem")
client.application_uri = "urn:PC16-LT16:Kepware.KEPServerEX.V6:UA%20Server"
client.connect()
dateNow = datetime.now()
volume = client.get_node('ns=2;s=Modbus.GATEWAY.Volume').get_value()
power = client.get_node('ns=2;s=Modbus.GATEWAY.Power').get_value()
temperature = client.get_node('ns=2;s=Modbus.GATEWAY.Temperature').get_value()
watts = client.get_node('ns=2;s=Modbus.GATEWAY.Watts').get_value()
print([dateNow.strftime('%Y-%m-%d %H:%M:%S'),str(volume),str(power),str(temperature),str(watts)])
client.disconnect()
````
**Using [asyncua](https://github.com/FreeOpcUa/opcua-asyncio): Not working**
client.py:
````
import asyncio
from asyncua import Client
from datetime import datetime
async def main():
async with Client("opc.tcp://192.168.100.139:49320") as client:
client.set_user("Administrator")
client.set_password("admin1234!@#$")
client.set_security_string("Basic256Sha256,SignAndEncrypt,cert.der,key.pem")
client.application_uri = "urn:PC16-LT16:Kepware.KEPServerEX.V6:UA%20Server"
dateNow = datetime.now()
volume = await client.get_node('ns=2;s=Modbus.GATEWAY.Volume').read_value()
power = await client.get_node('ns=2;s=Modbus.GATEWAY.Power').read_value()
temperature = await client.get_node('ns=2;s=Modbus.GATEWAY.Temperature').read_value()
watts = await client.get_node('ns=2;s=Modbus.GATEWAY.Watts').read_value()
print([dateNow.strftime('%Y-%m-%d %H:%M:%S'),str(volume),str(power),str(temperature),str(watts)])
if __name__ == "__main__":
asyncio.run(main())
````
**Upon running, the error was:**
````
ServiceFault (BadSecurityChecksFailed, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=None, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None)) from server received in response to CreateSessionRequest
Traceback (most recent call last):
File "C:\opc\client.py", line 22, in <module>
asyncio.run(main())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\asyncio\base_events.py", line 654, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\opc\client.py", line 7, in main
async with Client("opc.tcp://192.168.100.139:49320") as client:
File "C:\Python3.11\Lib\site-packages\asyncua\client\client.py", line 94, in __aenter__
await self.connect()
File "C:\Python3.11\Lib\site-packages\asyncua\client\client.py", line 310, in connect
await self.create_session()
File "C:\Python3.11\Lib\site-packages\asyncua\client\client.py", line 489, in create_session
response = await self.uaclient.create_session(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python3.11\Lib\site-packages\asyncua\client\ua_client.py", line 335, in create_session
data = await self.protocol.send_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python3.11\Lib\site-packages\asyncua\client\ua_client.py", line 172, in send_request
self.check_answer(data, f" in response to {request.__class__.__name__}")
File "C:\Python3.11\Lib\site-packages\asyncua\client\ua_client.py", line 181, in check_answer
hdr.ServiceResult.check()
File "C:\Python3.11\Lib\site-packages\asyncua\ua\uatypes.py", line 375, in check
raise UaStatusCodeError(self.value)
asyncua.ua.uaerrors._auto.BadSecurityChecksFailed: An error occurred verifying security.(BadSecurityChecksFailed)
````
I think, I was doing wrong with asynchronous implementation. Hopefully you could provide an input
Thanks in advance | Connect to Kepware KEPServerEX 6.15 via asyncua | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1583/comments | 2 | 2024-02-18T06:17:00Z | 2024-02-18T13:00:34Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1583 | 2,140,771,034 | 1,583 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When initializing an OPC UA server, I observed that the variable _current_connections in internal_session.py accurately tracks the number of clients connected to the server, essentially reflecting the number of open sessions. However, there seems to be a discrepancy with another variable, CurrentSessionCount, located within the ServerDiagnosticsSummaryDataType class. Unlike _current_connections, CurrentSessionCount consistently remains at 0, failing to update as client sessions change.
Question: Is it expected behavior for CurrentSessionCount to not mirror the actual number of active sessions, or is this an inconsistency that needs addressing? I would like CurrentSessionCount to reflect the same value as _current_connections.
Attempted Workaround:
To align the values of these variables, I attempted the following workaround:
```python
## Assuming server has been initialized and configured
async with server:
try:
while True:
if ServerDiagnosticsSummaryDataType.CurrentSessionCount != server.iserver.isession._current_connections:
ServerDiagnosticsSummaryDataType.CurrentSessionCount = server.iserver.isession._current_connections
await asyncio.sleep(1)
```
**To Reproduce**<br />
1. Check the value of CurrentSessionCount using a print statement:
```python
from asyncua.ua.uaprotocol_auto import ServerDiagnosticsSummaryDataType
print(ServerDiagnosticsSummaryDataType.CurrentSessionCount)
```
2. Connect multiple clients to the server.
3. Observe that the value of CurrentSessionCount remains unchanged despite the varying number of connections.
**Expected behavior**<br />
I expect the CurrentSessionCount variable to accurately reflect the real-time number of current sessions, rather than remaining static at 0.
**Version**<br />
Python-Version: 3.11
opcua-asyncio Version: 1.0.6
| Discrepancy Between _current_connections and CurrentSessionCount in OPC UA Server Implementation | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1569/comments | 1 | 2024-02-07T09:49:26Z | 2024-02-11T21:27:56Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1569 | 2,122,616,615 | 1,569 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi,
I have a server which publishes events derived by BaseEventType. Each event is also prioritized by the "Severity" Attribute of the event.
In the client application I currently want to react on events filtered by the eventtype **and** the severity.
Currently i try to subscribe to the event with the following code example:
```python
def subscribe(client: object, type_name: str, node: ua.Node, handler: object) -> None:
_type_node = client.nodes.base_event_type.get_child([f"0:{type_name}"])
_where_clause = ua.ContentFilter()
_where_clause.Elements.append(__get_filter_element_type(_type_node.nodeid))
_where_clause.Elements.append(__get_filter_element_severity(200))
_event_filter = ua.EventFilter()
_event_filter.SelectClauses.append(__get_attribute_operand_valueNodeId(client))
_event_filter.WhereClause = _where_clause
params = ua.CreateSubscriptionParameters()
params.RequestedPublishingInterval = 100
params.RequestedLifetimeCount = 300
params.RequestedMaxKeepAliveCount = 100
subscription = client.create_subscription(params, handler)
event_handle = subscription.subscribe_events(evtypes=_type_node.nodeid, evfilter=_event_filter)
def __get_filter_element_type(type_node_id: ua.NodeId) -> ua.ContentFilterElement:
el = ua.ContentFilterElement()
el.FilterOperator = ua.FilterOperator.OfType
op = ua.LiteralOperand(Value=ua.Variant(type_node_id))
el.FilterOperands.append(op)
return el
def __get_filter_element_severity(severity: int) -> ua.ContentFilterElement:
el = ua.ContentFilterElement()
el.FilterOperator = ua.FilterOperator.GreaterThanOrEqual
op = ua.SimpleAttributeOperand()
op.BrowsePath.append(ua.QualifiedName("Severity", 0))
op.AttributeId = ua.AttributeIds.Value
op.TypeDefinitionId = ua.NodeId(ua.ObjectIds.BaseEventType)
op2 = ua.LiteralOperand(Value=ua.Variant(severity))
el.FilterOperands.append(op)
el.FilterOperands.append(op2)
return el
```
The above code works with only the first element in the ContentFilter list. All following entries in the list are ignored.
It looks like that an operator like and, or not... is missing in the contentfilter.
I can not find any example or code snippet for solving that problem. I only found examples with a single element in the contentfilter.
Am i totally doing it wrong? Any help is appreciated.
Thanks and Regards
Harald
Python-Version: 3.10.12
opcua-asyncio Version: master-branch
| Question: How to filter events on subscription with where_clause | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1568/comments | 2 | 2024-02-07T09:18:25Z | 2024-02-19T09:06:37Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1568 | 2,122,547,540 | 1,568 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When the data types are loaded, the following error appears:
`RuntimeError: Unknown datatype for field: StructureField(Name='Life', Description=LocalizedText(Locale=None, Text=None), DataType=NodeId(Identifier='anontype4', NamespaceIndex=28, NodeIdType=<NodeIdType.String: 3>), ValueRank=-1, ArrayDimensions=[], MaxStringLength=0, IsOptional=False) in structure:Tl_V14_t, please report`
The following method is used:
`await client.load_data_type_definitions()`
As it stands, the package cannot instantiate structure elements that are not present in the address space of the structure.
However, according to the OPC UA Spec. this is permitted, the server does not have to provide "HasSubtype References", but an "inverse Reference".
This means that the data type can be determined when reading the data.
However, the package still seems to be strongly orientated towards the old "Dictionary Concept" and also attempts to browse the data types provided according to 1.04 OPC UA Spec. at startup.
The advantage of the "new" concept is that not all data types provided by the server have to be browsed at startup, which has a positive effect on the start of the application.
The client would simply have to skip data types that it cannot browse at startup and should not abort.
Python-Version: 3.11.0
opcua-asyncio Version: 1.0.6
| RuntimeError: Unknown datatype for field: StructureField | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1567/comments | 2 | 2024-02-07T08:32:35Z | 2024-04-11T13:54:15Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1567 | 2,122,466,064 | 1,567 |
[
"FreeOpcUa",
"opcua-asyncio"
] | `RuntimeError` is used in several places. That is a rather generic exception which, if sub-classed instead would allow more fine grained error handling.
E.g.:
https://github.com/FreeOpcUa/opcua-asyncio/blob/3268568df3b2c314920d97bb059cc48b3a98d5a1/asyncua/common/structures104.py#L219
How about introducing a `DataType(Exception)` in that case and similar exceptions in other cases? | Generic Exceptions | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1565/comments | 2 | 2024-02-06T16:21:20Z | 2024-02-06T19:36:07Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1565 | 2,121,192,490 | 1,565 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi all,
I am experiencing an issue with the Nodeset for CNC-Machines. Importing the nodeset into SiOME works just fine. However, when I want to export my information model as binary file, SiOME aborts the compiling and gives me this error: "Status: 70002006; Unknown error". Other nodesets like the DI-Nodeset can be compiled to binary by SiOME. Does anyone have an idea why only the CNC-nodeset cannot be compiled to binary?
Thanks!
| CNC nodeset cannot compile SiOME | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1562/comments | 1 | 2024-02-02T08:49:27Z | 2024-02-02T10:51:46Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1562 | 2,114,417,854 | 1,562 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I use a B&R PLC as OPC UA Server and changed the sampling interval of one tag to 50ms.
The tag is subscribed by opcua-asyncio. *(see code below)*
**Current behaviour:**
The Python Client still respects the default timer of 1s
**Expected behaviour:**
The python client gets a new value every ~50ms
Tag:

Default timers:

But if I change the default timer to 50ms (from Timer7 to Timer3), the python client works as desired. (But only this one Tag should have an interval of 50ms)
If I then change the tag to a higher limit e.g. to 10s, it also behaves as desired.
I tested the same with UaExpert as a Client:
| Client | Default timer | Tag timer | result |
| ------------- | ------------- | ------------- | ------------- |
| Python | 1000ms | 50ms | every ~1s |
| UA-Expert | 1000ms | 50ms | every ~200ms |
| Python | 50ms | default | every ~50ms |
| UA-Expert | 50ms | default | every ~200ms |
| Python | 50ms | 10s | every ~10s |
| UA-Expert | 50ms | 10s | every ~10s |
I use the following code to make a subscription:
```python
class MyHandler(SubHandler):
def __init__(self):
self._queue = asyncio.Queue()
def datachange_notification(self, node: Node, value, data: DataChangeNotif) -> None:
self._queue.put_nowait([node, value, data])
print(f'Data change notification was received and queued.')
async def process(self) -> None:
try:
while True:
# Get data in a queue.
[node, value, data] = self._queue.get_nowait()
path = await node.get_path(as_string=True)
print(f'New value {value} of "{path}" was processed.')
except asyncio.QueueEmpty:
pass
async def main() -> None:
async with Client(url=ENDPOINT) as client:
node = client.get_node(ua.NodeId(Identifier='::001234:test1', NamespaceIndex=6))
handler = MyHandler()
subscription = await client.create_subscription(handler=handler, period=0)
print(subscription.parameters)
await subscription.subscribe_data_change(node)
while True:
await handler.process()
await asyncio.sleep(0.05)
```
My print statement returns the following subscription values:
```
Revised values returned differ from subscription values: CreateSubscriptionResult(SubscriptionId=1473704468, RevisedPublishingInterval=50.0, RevisedLifetimeCount=10000, RevisedMaxKeepAliveCount=2700)
CreateSubscriptionParameters(RequestedPublishingInterval=50.0, RequestedLifetimeCount=10000, RequestedMaxKeepAliveCount=54000, MaxNotificationsPerPublish=10000, PublishingEnabled=True, Priority=0)
```
I don't know why it says RequestedPublishingInterval=50.0, I set it to 0.
Ua Expert logs the following settings:
```
Creating new subscription: ClientHandle=17, PublishingEnable=1, LifeTimeCount=360, MaxKeepAliveCount=10, Priority=0, PublishingInterval=50
Revised values: LifeTimeCount=360, MaxKeepAliveCount=10, Priority=0, PublishingInterval=50, SubscriptionId=1473704473
Item [NS6|String|:::001234:test1] succeeded : RevisedSamplingInterval=200, RevisedQueueSize=1, MonitoredItemId=1 [ret = Good]
```
I also can only change the PublishingInterval, but the RevisedSamplingInterval stays at 200ms. Is this the limiting factor for python as well? Does the sampling interval respect the default timer?
**Versions**
Python-Version: 3.11.4
opcua-asyncio Version: 1.0.6
AS Runtime: C4.92
| Setting publishing interval of subscription doesn't change behaviour | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1561/comments | 11 | 2024-02-01T17:51:03Z | 2024-02-05T10:08:32Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1561 | 2,113,090,978 | 1,561 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
**Describe the bug** <br />
When defining a variable with the data type 'float' in asyncua opcua, the server interprets it as a 'double', leading to a typing inconsistency on the client side.
**To Reproduce**<br />
1. create an opcua server with a variable of type "float":
```
my_object = await server.nodes.objects.add_object(idx, “MyObjects”)
ns = “ns=1;s=TagName”
my_var = await my_object.add_variable(ns, “MyVariable”, 0.0, datatype=ua.NodeId(ua.ObjectIds.Float))
await my_var.set_writable()
```
2. Use a client to push data to the server using the "float" type
3. Error faced :
```
Variant: Variant(Value=3.200000047683716, VariantType=<VariantType.Float: 10>, Dimensions=None, is_array=False) with type VariantType.Float does not have expected type: VariantType.Double
```
Upon investigating the root cause of the issue, we found in the file "asyncua/ua/uatypes.py," specifically within the method "_guess_type" of the "Variant" class, the code causing the issue is:
```
if isinstance(val, float):
return VariantType.Double
```
To address the issue, we attempted to replace the above code with the following snippet:
```
if isinstance(val, float):
return VariantType.Float
```
This modification successfully resolved the problem, ensuring proper handling of the "float" type, and rectifying the typing inconsistency observed in the previous code
**Expected behavior**<br />
When declaring a float variable, it is interpreted by the server as such.
**Version**<br />
Python-Version: 3.11<br />
opcua-asyncio Version: 1.0.6
| OPC-UA datatype Float interpreted as Double by server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1559/comments | 4 | 2024-01-31T14:02:44Z | 2024-10-02T10:18:39Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1559 | 2,110,165,748 | 1,559 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Congratulations for your project, in general your OPCUA server works well, but I did find some issues with XML import:
In my XML type definition I have a structure defined defining the field "ID" and others:
` <UADataType NodeId="ns=1;i=3019" BrowseName="1:DataDescriptionType">
<References>
...
<Reference ReferenceType="HasSubtype" IsForward="false">i=22</Reference>
</References>
<Definition Name="1:DataDefinitionType">
<Field Name="ID" DataType="String">
...`
Then there is another data type which is subtype of the previous, defining additional fileds:
` <UADataType NodeId="ns=1;i=3003" BrowseName="1:DataDefinitionType">
...
<References>
...
<Reference ReferenceType="HasSubtype" IsForward="false">ns=1;i=3019</Reference>
</References>
<Definition Name="1:DataDefinitionType">
<Field Name="EngineeringUnits" DataType="EUInformation">
...
`
Expected behavior: An instance of the data type "DataDefinitionType" includes also the fields from the "DataDescriptionType".
Observed behavior: The instance of "DataDefinitionType" has only the fields directly defined under it.
I can fix this if I refer all the required fields directly under the data type "DataDefinitionType" and refer it as subtype of structure (i=22), However, I do not want to edit this node set as it is a companion specification (TMC).
Versions:
Python: 3.9
asyncua: 1.0.1
| Issue importing nested UA extension data types from XML (HasSubType) | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1554/comments | 1 | 2024-01-19T14:08:22Z | 2024-01-19T14:30:53Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1554 | 2,090,647,921 | 1,554 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Based on my understanding, clients making ReadRequests has to have nodesToRead that are smaller than MaxNodesToRead defined in https://reference.opcfoundation.org/Core/Part5/v104/docs/6.3.11, together with other operation limits for other requests.
However I do not seem to find this implementation in this library as for the read example, there is no check on the length of nodes passed in either read_values or read_attributes of client and read_attributes of ua_client.
Did I miss something? | Question regarding OperationsLimitsType | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1551/comments | 1 | 2024-01-15T05:11:29Z | 2024-02-05T10:00:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1551 | 2,081,263,869 | 1,551 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Found while investigating [node-opcua/issue1232](https://github.com/node-opcua/node-opcua/issues/1232)
https://github.com/FreeOpcUa/opcua-asyncio/blob/f48b4f51fda55b67d3106ff6800e868c4e060fec/asyncua/common/manage_nodes.py#L401
should be Object and not ObjecType
**To Reproduce**<br />
Use [example.py](https://raw.githubusercontent.com/FreeOpcUa/opcua-asyncio/master/examples/server-custom-structures-and-enums.py)
**Expected behavior**<br />
**Screenshots**<br />
actual

The DataTypeEncoding instance is wrongly set to nodeClass=ObjectType

Expected ( like in any other companion specification )
The DataTypeEncoding instance should be nodeClass=Object

**Version**<br />
Python-Version: 3.x
opcua-asyncio: 1.0.6
| DataTypeEncoding object pointed by the "HasEncoding" links should have node class Object instead of ObjectType | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1549/comments | 1 | 2024-01-14T11:16:25Z | 2024-02-16T22:19:05Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1549 | 2,080,685,272 | 1,549 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi!
I have been seeing the following `ERROR` log message when using `asyncua`:
```
[ERROR] [asyncua.crypto.uacrypto]: certificate does not contain the application uri (urn:freeopcua:client). Most applications will reject a connection without it.
[ERROR] [asyncua.crypto.uacrypto]: certificate does not contain the hostname in DNSNames eeeccc7d53d4. Some applications will check this.
```
However, for my specific application, the certificates I am using work and allow communication with the OPCUA Server. Therefore, I think this log level should be `WARNING` instead of `ERROR` since it does not cause an error in ALL applications.
Thanks! | Lower Certificate Error in Logs | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1544/comments | 0 | 2024-01-02T22:28:22Z | 2024-01-12T07:33:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1544 | 2,063,026,931 | 1,544 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Currently it is not possible to change the attribute bits for float and double values.
I am running the following code:
```python
def set_bit(node: SyncNode, bit: int, value: bool):
'''Sets the value of the indicated bit for the given node.'''
if value:
node.set_attr_bit(asyncua.ua.AttributeIds.Value, bit)
else:
node.unset_attr_bit(asyncua.ua.AttributeIds.Value, bit)
```
Whenever the value attribute of `node` is a float or double, calling this function raises an exception:
```
...
File "C:\automatedTestingEnv\Lib\site-packages\asyncua\ua\ua_binary.py", line 30, in set_bit
return data | mask
~~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'float' and 'int'
```
Python version: 3.12
opcua-asyncio version: 1.0.6
| Cannot set attribute bits for float or double values | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1543/comments | 1 | 2023-12-28T08:40:19Z | 2023-12-28T13:33:42Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1543 | 2,058,155,776 | 1,543 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When attempting to set or unset the final bit of signed integer values (sbyte, int16/32/64) I am getting an out of bounds error.
I am connecting to a third party server, getting the node that I require and running the following code:
```python
def set_bit(node: SyncNode, bit: int, value: bool):
'''Sets the value of the indicated bit for the given node.'''
if value:
node.set_attr_bit(asyncua.ua.AttributeIds.Value, bit)
else:
node.unset_attr_bit(asyncua.ua.AttributeIds.Value, bit)
```
This raises an exception for certain values of `bit` (7 for sbyte, 15 for int16...) giving the reason (int16 example):
```
struct.error: short format requires -32768 <= number <= 32767
```
However this does not fail if the function would not actually change the value of the bit, for example the following code would run without issues:
```python
value = asyncua.ua.Variant(-32768, asyncua.ua.VariantType.Int16)
node.set_value(value)
node.set_attr_bit(asyncua.ua.AttributeIds.Value, 15)
```
Finally, there are no issues when using unsigned variable types (byte, uint16/32/64).
Python-Version: 3.12
opcua-asyncio Version: 1.0.6 | Cannot set final bit of signed integers using set_attr_bit | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1542/comments | 0 | 2023-12-28T08:32:15Z | 2023-12-28T08:32:15Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1542 | 2,058,148,671 | 1,542 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I've written a simple class to connect to Prosys simulation server and browse tags. Following is the sample code:
```
class UAClient:
def __init__(self):
super().__init__()
self.url = "opc.tcp://DESKTOP-33QTGC2:53530/OPCUA/SimulationServer"
self.client = None
async def connect_to_server_async(self):
self.client = Client(url=self.url)
await self.client.connect()
def connect_to_server(self):
asyncio.run(self.connect_to_server_async())
async def browse_level1_nodes_async(self):
obj_node = self.client.get_objects_node()
children = await obj_node.get_children()
resp = {"children": []}
for child in children:
br_name = await child.read_browse_name()
node_class = await child.read_node_class()
node_type = "object" if node_class == NodeClass.Variable else "variable"
child_data = {"name": br_name, "node_id": br_name.to_string(), "node_type": node_type}
resp["children"].append(child_data)
print(resp)
def browse_level1_nodes(self):
asyncio.run(self.browse_level1_nodes_async())
if __name__ == "__main__":
obj = UAClient()
obj.connect_to_server()
obj.browse_level1_nodes()
```
As we can see, first the connection is established with server using connect_to_server() method and it waits till completion using asyncio.run(). Then, level 1 children are browsed using browse_level1_nodes() and again asyncio.run() is used to wait for completion.
However when the program is run, following exception is raised:
```
Error while renewing session
Traceback (most recent call last):
File "C:\Users\surni\AppData\Roaming\Python\Python37\site-packages\asyncua\client\client.py", line 572, in _renew_channel_loop
await asyncio.sleep(duration)
File "C:\Program Files\Itanta\Python37\lib\asyncio\tasks.py", line 595, in sleep
return await future
concurrent.futures._base.CancelledError
Error in watchdog loop
Traceback (most recent call last):
File "C:\Users\surni\AppData\Roaming\Python\Python37\site-packages\asyncua\client\client.py", line 549, in _monitor_server_loop
await asyncio.sleep(timeout)
File "C:\Program Files\Itanta\Python37\lib\asyncio\tasks.py", line 595, in sleep
return await future
concurrent.futures._base.CancelledError
Traceback (most recent call last):
File "browse_nodes_github.py", line 38, in <module>
obj.browse_level1_nodes()
File "browse_nodes_github.py", line 32, in browse_level1_nodes
asyncio.run(self.browse_level1_nodes_async())
File "C:\Program Files\Itanta\Python37\lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\Program Files\Itanta\Python37\lib\asyncio\base_events.py", line 579, in run_until_complete
return future.result()
concurrent.futures._base.CancelledError
```
When both connection and node browsing is inside a single function, it works properly.
Expected behavior: Browsing nodes should work after connection is successful, when called one after other. | asyncio.run() consecutively for connection and node browsing doesn't work | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1541/comments | 6 | 2023-12-26T15:51:31Z | 2023-12-27T15:43:00Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1541 | 2,056,521,485 | 1,541 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi,
Since OPCUA servers are deploy on local devices, how can an OPCUA client from cloud/internet discover the servers?
Is there any example or demo on this?
Thanks! | how to discover local server from remote client? | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1538/comments | 4 | 2023-12-21T15:28:00Z | 2023-12-22T17:26:48Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1538 | 2,052,630,602 | 1,538 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When using ua.QueryFirstRequest() as a client, the server response is that this service is not supported.
Is there any way to fix this or extend the server to handle a query service as mentioned in OPC UA Part 4?
Client-Code:
```
data2 = await self.client.uaclient.protocol.send_request(
ua.QueryFirstRequest(Parameters=ua.QueryFirstParameters(
NodeTypes=[ua.NodeTypeDescription(
TypeDefinitionNode=ua.ExpandedNodeId(58,0,ua.NodeIdType.TwoByte, "http://opcfoundation.org/UA/", 0),
IncludeSubTypes=True,
DataToReturn=[ua.QueryDataDescription(
AttributeId=3,
)])],
MaxDataSetsToReturn=10,
MaxReferencesToReturn=10
)
)
)
response2 = struct_from_binary(ua.QueryFirstResponse, data2)
print(response2.Parameters)
```
Client-Logger:
`
asyncua.ua.uaerrors._auto.BadServiceUnsupported: The server does not support the requested service.(BadServiceUnsupported)
`
Server-Logger:
`
WARNING:asyncua.server.uaprocessor:Unknown message received NodeId(Identifier=615, NamespaceIndex=0, NodeIdType=<NodeIdType.FourByte: 1>) (User(role=<UserRole.User: 3>, name=None))
ERROR:asyncua.server.uaprocessor:sending service fault response: The server does not support the requested service. (BadServiceUnsupported)
` | Server doens't support Views | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1537/comments | 2 | 2023-12-21T13:51:27Z | 2023-12-21T14:19:00Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1537 | 2,052,462,794 | 1,537 |
[
"FreeOpcUa",
"opcua-asyncio"
] | During parsing a node-set, StuctureDefinition objects are created for sub-data-types of data-type Structure.
Important information of a structure definition are the supported encodings (Binary, XML. JSON) and the proposed default encoding.
OPC UA [Part 3 8.48 StructureDefinition](https://reference.opcfoundation.org/Core/Part3/v105/docs/8.48) defines the DefaultEncodingId as follows:
> The NodeId of the default DataTypeEncoding for the DataType. The default shall always be Default Binary encoding.
However, the current implementation wrongly assumes, that the first HasEncoding reference of the data-type node represents the default encoding, see snippet:
def _get_sdef(self, obj):
..
sdef = ua.StructureDefinition()
..
for refdata in obj.refs:
if refdata.reftype == self.session.nodes.HasEncoding.nodeid:
# supposing that default encoding is the first one...
sdef.DefaultEncodingId = refdata.target
break
Since some existing "real world" companion specifications to not sort the HasEncoding references in the node-set with "Default Binary" on top (and are not mandated to do so), the wrong assumption causes runtime errors when trying to transfer such data between client and server.
In order to determine the correct DefaultNodeId, additional data of the references' target nodes is required (browse_name, display_name). As far as I understand, this data does not exist within the context of the _get_sdef() method. Imho this would either require following the references' targets within the scope of the method or doing a second pass.
Please consider additional issues in the context of handling HasEncoding e.g., [xmlimporter.add_object(): Exclusion of HasEncoding target objects sometimes fails for 'Default JSON'](https://github.com/FreeOpcUa/opcua-asyncio/issues/1522). | DataType Encoding: xml_importer._get_sdef() wrongly assumes, that the first HasEncoding reference represents the default encoding. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1536/comments | 5 | 2023-12-19T09:06:13Z | 2023-12-19T15:52:11Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1536 | 2,048,224,958 | 1,536 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Browsing a server built with opcua-asyncio for HasTypeDefinition references is broken.
When specifying a NodeClassMask of only ObjectType or VariableType, no results are returned.
If the NodeClassMask is set to 0 (all NodeClasses should be returned), then 1 result is returned, however it incorrectly identifies the NodeClass as `NodeClass.DataType`. (I suspect this is the cause of the 0 length result when a mask is supplied).
This code written against Eclipse Milo dev/1.0 branch reproduces, though you should be able to reproduce from any OPC UA SDK: https://gist.github.com/kevinherron/f85ce3b0eebe84008e59a5192f6b404d
Results:
```
Browsing with NodeClass mask: 24
No references found
Browsing with NodeClass mask: 0
Reference[0]:
NodeId: ExpandedNodeId{ns=0, id=2138, serverIndex=0}
BrowseName: QualifiedName{name=ServerStatusType, namespaceIndex=0}
DisplayName: LocalizedText{text=ServerStatusType, locale=null}
NodeClass: DataType
TypeDefinition: ExpandedNodeId{ns=0, id=0, serverIndex=0}
```
Wireshark capture: [browse_has_type_definition.zip](https://github.com/FreeOpcUa/opcua-asyncio/files/13696531/browse_has_type_definition.zip)
| Browsing for HasTypeDefinition references is broken | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1529/comments | 14 | 2023-12-17T14:44:35Z | 2025-03-09T18:22:39Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1529 | 2,045,245,961 | 1,529 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello. I am unable to connect to Siemens OPC UA server for Sinumerik 840D based device. Currently i am using a SinuTrain emulator for a lathe. I'm able to connect and read node values via `CNCnetPDM.OpcUA.Client.exe`

### My code
```python
import asyncio
from asyncua import Client
async def main():
url = "opc.tcp://127.0.0.1:4840"
client = Client(url)
client.set_user("OpcUaClient")
client.set_password("OpcUaClient")
await client.set_security_string("Basic128Rsa15,SignAndEncrypt,certificate.pem, key.pem")
await client.connect()
print(f"Connected to: {url}")
servicelevel_node = client.get_node("ns=0;i=2267")
servicelevel_node_value = servicelevel_node.get_value()
print(servicelevel_node_value)
client.disconnect()
asyncio.run(main())
```
### Error
Using a code written above returns asn1 error ValueError: error parsing asn1 value:
`ParseError
{ kind: EncodedDefault, location: ["Certificate::tbs_cert", "TbsCertificate::raw_extensions", 0, "Extension::critical"] }`
I have sucessfuly created `certificate.pem`, `certificate.der` and `private_key.pem` files via OpenSSL. But it seems that the main error is related to the server certificate from Siemens OPC UA Server.
## Here's the simplified call stack:
```python
client.connect()
-> self.activate_session(username=self._username, password=self._password, certificate=self.user_certificate)
-> pubkey = uacrypto.x509_from_der(self.security_policy.server_certificate).public_key()
-> return x509.load_der_x509_certificate(data, default_backend())
-> return rust_x509.load_der_x509_certificate(data)
```
#### Version
`python==3.11.0`
`asyncua==1.0.5` | Error parsing server certificate in Siemens (Sinumerik 840D) miniweb OPC UA Server. Version 4.7 SW | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1525/comments | 6 | 2023-12-13T13:37:13Z | 2024-09-11T08:40:12Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1525 | 2,039,732,342 | 1,525 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
**Describe the bug** <br />
I can not read custom structures from an opcua-asyncio Server using a B&R PLC with an OPC UA client. Reading always fails with Error 0x80390000 Bad_DataEncodingUnsupported.
I already contacted the B&R Suppport. B&R claims the Error indicates that the Sever uses an old implementation of the OPCUA standard.
I also tried other OPC UA Servers where my B&R client could read custom structures.
The same problem might be already mentioned inside the Discussion of the older librabry python-opcua here: [#1527](https://github.com/FreeOpcUa/python-opcua/discussions/1527)
**To Reproduce**<br />
I used the example server-custom-structures-and-enums.py from this repository.
For the client I used the OpcUa_Sample from B&R Automation Studio V4.9.6.42.
**Version**<br />
Python-Version:<br /> Python 3.9.7
opcua-asyncio Version (e.g. master branch, 0.9): <br /> asyncua 1.0.5
| Reading Custom Structure with B&R OPC UA client fails with Error 0x80390000 Bad_DataEncodingUnsupported | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1524/comments | 3 | 2023-12-13T13:31:50Z | 2024-02-16T22:19:43Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1524 | 2,039,722,314 | 1,524 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
When loading node sets with user specific data types, the supported encoding rules are provided via HasEncoding references which point to an object with display names "Default Binary", "Default XML", "Default JSON".
(for further information [OPC 10000-6: UA Part 6: Mappings](https://reference.opcfoundation.org/Core/Part6/v105/docs/5.4))
Since these referenced objects typically don't have parent objects within the namespace, the xmlimporter.add_object() method excludes such objects from further checks.
However, due to a misspelling "Default Json" instead of "Default JSON" this exclusion does not work as expected and loading node sets could fail with an error.<br />
Corrected version of code (lines xmlimporter.py 358 - 360):
# do not verify these nodes because some nodesets contain invalid elements
if obj.displayname != 'Default Binary' and obj.displayname != 'Default XML' and obj.displayname != 'Default JSON':
res[0].StatusCode.check()
**To Reproduce**<br />
Specific node set still to be published.
**Version**<br />
Python-Version:<br />
opcua-asyncio Version (master branch & update):
| xmlimporter.add_object(): Exclusion of HasEncoding target objects sometimes fails for 'Default JSON' | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1522/comments | 0 | 2023-12-11T10:51:36Z | 2023-12-11T13:01:25Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1522 | 2,035,390,925 | 1,522 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello,
this is not really a bug but more an issue i'm failing to solve.
My use case is a PLC whose variables for whatever reason (might) have "timestamps" (Source and Server) either locked or basically not writeable. So whenever i do
`await h_tmax_m2.write_value(60)`
i receive
`ERROR: The server does not support writing the combination of value, status and timestamps provided.(BadWriteNotSupported)`
I was hoping to create a Datavalue with `SourceTimestamp=None and ServerTimestamp=None` mainly because another program i have is not complaining about it while it uses these values although i'm not sure whether it will fix the issue.
The write operation works but the program crashes and i didnt want to wrap everything in a try except caluse
So i've tried something like
```
dv = ua.DataValue(
ua.Variant(
100,
ua.VariantType.Int16
),
StatusCode_=ua.StatusCodes.Good,
SourceTimestamp=None,
ServerTimestamp=None
)
await h_tmax_m2.write_attribute(ua.AttributeIds.Value, dv)
```
but i receive the following
`TypeError: must be called with a dataclass type or instance`
which i'm struggling to understand why.
What am i doing wrong in the cose above? Is there a better way to solve this?
Regards,
| BadWriteNotSupported and TypeError: must be called with a dataclass type or instance | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1520/comments | 5 | 2023-12-10T10:44:52Z | 2023-12-10T14:33:32Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1520 | 2,034,315,431 | 1,520 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
get_children() appears to have a memory leak or runaway behaviour for asyncua version 1.0.5 that was not present in version 1.0.4.
**To Reproduce**<br />
Steps to reproduce the behavior incl code:
Example code for traversing down to the relevant data nodes. Last call to get_children() fails.
<pre>
# Connect and traverse tree to locate top node for sensor data
client = Client(url)
await client.connect()
# Get a list of all 'sensor data' nodes
root = client.get_root_node()
children = await root.get_children()
c85 = await children[0].get_children()
c851 = await c85[1].get_children()
allsensors = await c851[2].get_children()
</pre>
The last get_children() call should return about 83000 items. Using asyncua version 1.0.4 this works fine, while in version 1.0.5 it consumes all available memory before failing.
**Expected behavior**<br />
Expect the get_children() call to return list of child nodes without crashing or consuming all memory.
**Version**<br />
Python-Version: Tested on 3.9 and 3.11. Problem in both cases<br />
opcua-asyncio Version 1.0.5 (current default with pip install)
| get_children() memory leak or runaway behaviour in asyncua 1.0.5 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1519/comments | 14 | 2023-12-08T13:49:34Z | 2023-12-18T11:47:42Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1519 | 2,032,690,463 | 1,519 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
[call_method_client.txt](https://github.com/FreeOpcUa/opcua-asyncio/files/13557393/call_method_client.txt)
[call_method_server.txt](https://github.com/FreeOpcUa/opcua-asyncio/files/13557395/call_method_server.txt)
****
root@Server-Ubuntu-1604:/home/syed/POC/POC# pip3.8 show asyncua
Name: asyncua
Version: 1.0.5
Summary: Pure Python OPC-UA client and server library
Home-page: http://freeopcua.github.io/
Author: Olivier Roulet-Dubonnet
Author-email: olivier.roulet@gmail.com
License: GNU Lesser General Public License v3 or later
Location: /usr/local/lib/python3.8/site-packages
Requires: aiofiles, aiosqlite, cryptography, pyOpenSSL, python-dateutil, pytz, sortedcontainers, typing-extensions
Required-by:
**VM OS (For both client and Server) :**
root@client-ubuntu-1604:/home/syed/POC/POC# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.7 LTS
Release: 16.04
Codename: xenial
**Python Version : Python 3.8.0**
**Getting Following error on Server Program:**
<img width="667" alt="image" src="https://github.com/FreeOpcUa/opcua-asyncio/assets/15814146/464a0589-4279-4d83-899e-3e362bfb1fca">
root@Server-Ubuntu-1604:/home/syed/POC/POC# python3.8 call_method_server.py
Starting Server
Starting Server
Endpoints other than open requested but private key and certificate are not set.
Error while processing message
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/asyncua/server/uaprocessor.py", line 137, in process_message
return await self._process_message(typeid, requesthdr, seqhdr, body)
File "/usr/local/lib/python3.8/site-packages/asyncua/server/uaprocessor.py", line 468, in _process_message
self.send_response(requesthdr.RequestHandle, seqhdr, response)
File "/usr/local/lib/python3.8/site-packages/asyncua/server/uaprocessor.py", line 49, in send_response
struct_to_binary(response), message_type=msgtype, request_id=seqhdr.RequestId)
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 336, in struct_to_binary
return serializer(obj)
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 401, in serialize
return data_size + b''.join(type_serializer(el) for el in val)
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 401, in <genexpr>
return data_size + b''.join(type_serializer(el) for el in val)
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 325, in serialize
return b''.join(
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 327, in <genexpr>
else serializer(obj.__dict__[name])
File "/usr/local/lib/python3.8/site-packages/asyncua/ua/ua_binary.py", line 400, in serialize
data_size = Primitives.Int32.pack(len(val))
TypeError: object of type 'Variant' has no len()
**AT the same time client has following error:**
<img width="784" alt="image" src="https://github.com/FreeOpcUa/opcua-asyncio/assets/15814146/6dab43e1-3ae8-4fbe-8879-be4e3c062aed">
root@client-ubuntu-1604:/home/syed/POC/POC# python3.8 call_method_client.py
Starting Client
ServiceFault (BadInternalError, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=None, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None)) from server received in response to CallRequest
An error occurred: An internal error occurred as a result of a programming or configuration error.(BadInternalError)
| Server program with asyncua library getting failed while client is calling method on server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1517/comments | 0 | 2023-12-05T08:47:13Z | 2023-12-07T07:15:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1517 | 2,025,634,912 | 1,517 |
[
"FreeOpcUa",
"opcua-asyncio"
] | On a server with around 6000 tags streaming with frequency of 1 second, we are seeing lag build up. What are the expected throughput for python opcua subscriptions. On 3000 tags, it is working fine | OPCUA Subscription limit | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1516/comments | 12 | 2023-12-05T07:12:32Z | 2023-12-05T09:19:28Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1516 | 2,025,432,384 | 1,516 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I have tried to change the AttributeId's argument, but then 'nodeid' is overwriting 'value' in response.

| I am using client.get_attributes() method for the bulk read of the nodes, in which the response containes value, sourcetimestamp, servertimestamp and status code. How can i get node id also in the response. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1514/comments | 5 | 2023-12-04T10:55:23Z | 2023-12-06T11:05:28Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1514 | 2,023,576,311 | 1,514 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
To save some time, please provide us following informations, if possible:
**Describe the bug** <br />
I'm trying to connect as a client in a sha256, Sign&Encrypt server and the server administrator need to trust my cert. I'm getting this error:
**> error parsing asn1 value: ParseError { kind: InvalidValue, location: ["AuthorityKeyIdentifier::authority cert serial number"] }**
**To Reproduce**<br />
Steps to reproduce the behavior incl code:
> cert_base = Path(__file__).parent
>
> cert = Path(cert_base / f"my_cert.der")
> private_key = Path(cert_base / "my_private_key.pem")
> host_name = socket.gethostname()
> client_app_uri = f"urn:{host_name}:aignosi:sientia"
>
> await setup_self_signed_certificate(private_key,
> cert,
> client_app_uri,
> host_name,
> [ExtendedKeyUsageOID.CLIENT_AUTH],
> {
> 'countryName': 'BR',
> 'stateOrProvinceName': 'MG',
> 'localityName': 'Belo Horizonte',
> 'organizationName': "My Company",
> 'emailAddress': 'myemail@hotmail.com'
> })
>
> # # return a new connection
> connection = asyncua.Client(url, watchdog_intervall=300)
> connection.application_uri = client_app_uri
> await connection.set_security(
> SecurityPolicyBasic256,
> certificate=str(cert),
> private_key=str(private_key),
> # server_certificate="certificate-example.der"
> )
>
>
> connection.certificate_validator =CertificateValidator(CertificateValidatorOptions.EXT_VALIDATION|CertificateValidatorOptions.PEER_SERVER)
>
>
> await connection.connect()
asyncua==1.0.5
Python 3.11
Thankss
| Can't connect to OPC server | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1512/comments | 1 | 2023-11-30T18:15:08Z | 2023-12-01T13:45:01Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1512 | 2,019,247,333 | 1,512 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ## Set the initial source timestamp for all nodes using a subscription to the current time when the code is executed
I'm new to opcua, and I'm facing an issue when running my script. Upon retrieving all nodes, I observe that the subscription mode returns outdated data, possibly from a days ago. because some sensors do not change when starting the process. how can I modify the initial values to get the timestamp of running the script and than do the subscription.
```
def datachange_notification(self, node: Node, val, data):
node = str(node)
if node in SubHandler.result.keys():
source_timestamp = data.monitored_item.Value.SourceTimestamp
server_timestamp = data.monitored_item.Value.ServerTimestamp
print(f"source timestamp : {source_timestamp}, Value : {SubHandler.result[node][0]} = {val}")
else:
print("Node not found")
```
**Expected behavior**<br />
In my current implementation, I've noticed that when obtaining to get the initial values of all nodes, such as the 'position_z' node, the timestamp appears to be outdated. first I aim to retrieve all nodes from my node dictionary with timestamps set to when the script is executed and than work like a normal subscription and get the source timestamp in the subscription.
**Output**<br />

| change the init node source timestamp using Subscription | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1509/comments | 6 | 2023-11-29T18:07:29Z | 2023-12-06T13:34:20Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1509 | 2,017,149,701 | 1,509 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
The ItemSubscriptionDeleted callback doesn't get called when a client disconnects. So if i keep a list of which nodes are subscribed, it is not correct after some clients have disconnected.
**To Reproduce**<br />
Connect to server with ua-expert. Then subscribe to some nodes and close the connection.
**Expected behavior**<br />
ItemSubscriptionDeleted callback for the subscribed nodes when a client disconnects
**Version**<br />
Python-Version: Python 3.11.5<br />
opcua-asyncio Version (e.g. master branch, 0.9): 1.0.5
| ItemSubscriptionDeleted callback doesn't work on client disconnect | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1508/comments | 0 | 2023-11-29T10:39:45Z | 2023-11-29T10:39:45Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1508 | 2,016,294,037 | 1,508 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Cannot read node for node id format "nsu=xxxxx;s=yyyyy"
**To Reproduce**<br />
```
id = "nsu=http://xyz.com/UA/Connectivity/;s=35.Running"
node = client.get_node(id)
value = await node.read_value()
```
Then, get error `asyncua.ua.uaerrors._auto.BadEncodingLimitsExceeded: The message encoding/decoding limits imposed by the stack have been exceeded.(BadEncodingLimitsExceeded)`
**Expected behavior**<br />
Read the value.
**Version**<br />
Python-Version: 3.10.12 <br />
opcua-asyncio Version (e.g. master branch, 0.9): 0.9
| Cannot read node for format "nsu=xxxxx;s=yyyyy" | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1506/comments | 4 | 2023-11-28T01:58:33Z | 2023-12-04T07:43:18Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1506 | 2,013,449,016 | 1,506 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Client can not start a connection to a KepServerEx server(v 6.13) with using any encrypted method. Setting security to None and not using any certificates is fine. Server info is:
Algorithm: Basic256Sha256
Method: SignAndEncrypt
Certificate: Generated by KepServerEx
Minimal code that I'm using:
```python
from asyncua.sync import Client
def main():
url = r"opc.tcp://username:password@127.0.0.1:49320"
client = Client(url)
client.load_client_certificate("<cert_path>")
client.connect()
print(client)
client.disconnect()
if __name__ == "__main__":
main()
```
Running this code raises this exception:
<details>
<summary> Full stack trace </summary>
```
ServiceFault (BadSecurityChecksFailed, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=None, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None)) from server received in response to CreateSessionRequest
Traceback (most recent call last):
File "client_certificate.py", line 19, in <module>
main()
File "client_certificate.py", line 14, in main
client.connect()
File "<project_dir>\venv\lib\site-packages\asyncua\sync.py", line 96, in wrapper
result = self.tloop.post(aio_func(*args, **kwargs))
File "<project_dir>\venv\lib\site-packages\asyncua\sync.py", line 54, in post
return futur.result()
File "C:\Users\Acer\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\_base.py", line 446, in result
return self.__get_result()
File "C:\Users\Acer\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\_base.py", line 391, in __get_result
raise self._exception
File "<project_dir>\venv\lib\site-packages\asyncua\client\client.py", line 294, in connect
await self.create_session()
File "<project_dir>\venv\lib\site-packages\asyncua\client\client.py", line 474, in create_session
response = await self.uaclient.create_session(params)
File "<project_dir>\venv\lib\site-packages\asyncua\client\ua_client.py", line 335, in create_session
data = await self.protocol.send_request(request)
File "<project_dir>\venv\lib\site-packages\asyncua\client\ua_client.py", line 172, in send_request
self.check_answer(data, f" in response to {request.__class__.__name__}")
File "<project_dir>\venv\lib\site-packages\asyncua\client\ua_client.py", line 181, in check_answer
hdr.ServiceResult.check()
File "<project_dir>\venv\lib\site-packages\asyncua\ua\uatypes.py", line 373, in check
raise UaStatusCodeError(self.value)
asyncua.ua.uaerrors._auto.BadSecurityChecksFailed: An error occurred verifying security.(BadSecurityChecksFailed)
```
</details>
**Version**<br />
Python-Version: 3.9<br />
opcua-asyncio Version (e.g. master branch, 0.9): (pip) 1.0.4
I've tried several workarounds and still could not succeed. Does this connection requires a .pem key? If so, how can i retrieve it?
| Sync Client Encrypted Connection Failed to KepServerEx | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1505/comments | 2 | 2023-11-27T15:03:53Z | 2024-05-02T17:41:38Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1505 | 2,012,476,625 | 1,505 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Is the usermanager already implemented in the asyncua.sync module?
I've tried multiple ways on implementing a user and password verification method but it seems like it's not working.
[Not implemented?](https://github.com/FreeOpcUa/opcua-asyncio/blob/a6fe064ab0f2334c5351324a97816ec42126a046/asyncua/server/user_managers.py#L9C13-L9C13)
[Server(user_manager=UserManager())](https://github.com/FreeOpcUa/opcua-asyncio/blob/a6fe064ab0f2334c5351324a97816ec42126a046/tests/test_password.py#L20C11-L20C45) is not working and returns "got an unexpected keyword argument 'user_manager'" | Sync Module is missing Server parameter user_manager | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1502/comments | 1 | 2023-11-23T15:01:55Z | 2023-11-24T07:25:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1502 | 2,008,396,773 | 1,502 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Good afternoon everyone;
I came across uamethod these days and wanted to know whether it would be possible to use it as decorator for functions whose signature does not have "parent" as first attribute?
https://github.com/FreeOpcUa/opcua-asyncio/blob/e9978c157d6c68720143211b9d794f2a8cba245e/asyncua/common/methods.py#L73-L90
When the fuction decorated with it is actually a method and the class is already the parent of the "function" I see little use in having it being part of every of our server methods?
If I understand it correctly a method currently can't look like this, if I want to decorate it with uamethod, even if it' not making use of 'parent'?
```python
from asyncua.common import uamethod
from asyncua.sync import Server
class PinController:
def __init__(self, some_server: Server):
self.server = some_server
server.link_method(
server.get_node(ua.NodeId.from_string("ns=1;i=42")), uamethod(self.on_set_output)
)
def on_set_output(self, pin: ua.UInt32, value: ua.Boolean) -> None:
# set the pin to something useful
pass
``` | [Question] uamethod no parent | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1493/comments | 4 | 2023-11-13T13:55:24Z | 2023-11-17T08:33:52Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1493 | 1,990,711,673 | 1,493 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
Type hints merged in #1432 does not permit `int` as `nodeid` parameter on `create_variable`, `create_property`, etc.
in these functions, `nodeid` (and `bname`) parameters are passed to `_parse_nodeid_qname` function and it can handle `(int, str)` case.
**To Reproduce**<br />
```
$ pyright examples/server-minimal.py
examples/server-minimal.py
examples/server-minimal.py:26:51 - error: Argument of type "int" cannot be assigned to parameter "nodeid" of type "NodeId | str" in function "add_object"
Type "int" cannot be assigned to type "NodeId | str"
"int" is incompatible with "NodeId"
"int" is incompatible with "str" (reportGeneralTypeIssues)
examples/server-minimal.py:27:38 - error: Argument of type "int" cannot be assigned to parameter "nodeid" of type "NodeId | str" in function "add_variable"
Type "int" cannot be assigned to type "NodeId | str"
"int" is incompatible with "NodeId"
"int" is incompatible with "str" (reportGeneralTypeIssues)
(snip)
```
**Version**<br />
Python-Version: 3.10.12<br />
opcua-asyncio Version: 1.0.5
| Incorrect type hints on Node methods | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1491/comments | 0 | 2023-11-13T12:20:12Z | 2023-11-13T14:29:30Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1491 | 1,990,547,868 | 1,491 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
pylint hits:
> W0221: Number of parameters was 3 in 'SyncNode.write_value' and is now 2 in overriding 'TypedNode.write_value' method (arguments-differ)
Since 1.0.5 was released [three hours ago](https://pypi.org/project/asyncua/).
**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 />

**Version**<br />
Python-Version: 3.9<br />
opcua-asyncio Version (e.g. master branch, 0.9): 1.0.5
| 1.0.5 SyncNode.write_value parameters changed | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1489/comments | 3 | 2023-11-10T13:19:30Z | 2024-02-29T17:55:03Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1489 | 1,987,617,206 | 1,489 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I was trying to follow the example from [server-with-encryption](https://github.com/FreeOpcUa/opcua-asyncio/blob/master/examples/server-with-encryption.py) but in the latest version of the PyPI package (1.0.4), does not seem to include the associated code (`asyncua/crypto/validator.py`, updates on the server class, etc)
**To Reproduce**<br />
Install the latest version of the package and run the mentioned example.
**Screenshots**<br />
As a quick fix, after manually copying the validator.py file in the right directory:

The server class is still missing some features.
**Workaround**<br />
Cloning and manually installing the package from the repository fixes the issue
**Version**<br />
Python-Version:3.11<br />
opcua-asyncio Version PyPI 1.0.4:
| Certificate validator logic not present in latest version of package | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1483/comments | 0 | 2023-11-04T17:27:37Z | 2023-11-04T17:34:46Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1483 | 1,977,438,272 | 1,483 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When running the example statemachine-example.py, an exception occurs.
INFO:asyncua.common.instantiate_util:Instantiate: Skip node without modelling rule QualifiedName(NamespaceIndex=0, Name='InitialStateType') as part of QualifiedName(NamespaceIndex=2, Name='Finished')
INFO:asyncua.common.instantiate_util:Instantiate: Skip node without modelling rule QualifiedName(NamespaceIndex=0, Name='ChoiceStateType') as part of QualifiedName(NamespaceIndex=2, Name='Finished')
WARNING:asyncua.server.address_space:Write refused: Variant: Variant(Value=NodeId(Identifier=6, NamespaceIndex=2, NodeIdType=<NodeIdType.FourByte: 1>), VariantType=<VariantType.NodeId: 17>, Dimensions=None, is_array=False) with type VariantType.NodeId does not have expected type: VariantType.Null
Traceback (most recent call last):
File "statemachine-example.py", line 87, in <module>
asyncio.run(main())
File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "statemachine-example.py", line 54, in main
await mystatemachine.change_state(state1, trans1, f"{mystatemachine._name}: Idle", 300)
File "/home/abc/.local/lib/python3.8/site-packages/asyncua/common/statemachine.py", line 183, in change_state
await self._write_state(state)
File "/home/abc/.local/lib/python3.8/site-packages/asyncua/common/statemachine.py", line 206, in _write_state
await self._current_state_id_node.write_value(state.node.nodeid, varianttype=ua.VariantType.NodeId)
File "/home/abc/.local/lib/python3.8/site-packages/asyncua/common/node.py", line 255, in write_value
await self.write_attribute(ua.AttributeIds.Value, dv)
File "/home/abc/.local/lib/python3.8/site-packages/asyncua/common/node.py", line 307, in write_attribute
result[0].check()
File "/home/abc/.local/lib/python3.8/site-packages/asyncua/ua/uatypes.py", line 373, in check
raise UaStatusCodeError(self.value)
asyncua.ua.uaerrors._auto.BadTypeMismatch: The value supplied for the attribute is not of the same type as the attribute"s value.(BadTypeMismatch)
| When running the example statemachine-example.py, an exception occurs. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1479/comments | 2 | 2023-10-31T02:00:21Z | 2024-04-22T19:27:21Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1479 | 1,969,496,186 | 1,479 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi!
I am working on a OPC UA client and need to check what is the reason why the connection failed e.g. BadTcpEndpointUrlInvalid. So far I have found no information or any hint how to get the original OPC UA error code and a TimeoutError is the only returned exception at the moment. Sorry if this is duplicate, but can you give me a pointer in the right direction ?
Thanks | API Question: How to get the original OPCUA Error as client | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1477/comments | 2 | 2023-10-26T20:20:37Z | 2023-11-15T07:53:18Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1477 | 1,964,311,681 | 1,477 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi, I have a question re. this issue: I use link_method to implement a method in the server. It seems that load_data_type_definitions loads only the base UA Data Types under Structure, but not the additionally loaded Data Types from other nodesets.
How can I use Data Types from imported xml nodesets, for example to create an output within my implemented method in the form:
...
value = ua.uaprotocol_auto.F_JobResponseDataType()
value.JobOrderID = input.Value
...
May data type, generated by SiOME under Types/DataTypes/BaseDataType/Structure is here:
<UADataType NodeId="ns=10;i=3005" BrowseName="10:F_JobResponseDataType">
<DisplayName>F_JobResponseDataType</DisplayName>
<References>
<Reference ReferenceType="HasSubtype" IsForward="false">i=22</Reference>
<Reference ReferenceType="HasEncoding">ns=10;i=5092</Reference>
<Reference ReferenceType="HasEncoding">ns=10;i=5093</Reference>
</References>
<Definition Name="F_JobResponseDataType">
<Field DataType="String" Name="JobOrderID"/>
<Field IsOptional="true" DataType="String" Name="Description"/>
<Field IsOptional="true" DataType="String" Name="ProductID"/>
<Field IsOptional="true" DataType="String" Name="PartSerialNumber"/>
<Field IsOptional="true" DataType="DateTime" Name="StartTime"/>
<Field IsOptional="true" DataType="DateTime" Name="EndTime"/>
<Field DataType="ISA95JobOrderStateEnum" Name="JobState"/>
<Field IsOptional="true" DataType="ns=10;i=3013" Name="PartState"/>
<Field IsOptional="true" DataType="Int32" Name="LinePosition"/>
<Field IsOptional="true" DataType="String" Name="MaterialContainerIDIn"/>
<Field IsOptional="true" DataType="String" Name="MaterialContainerIDOut"/>
<Field IsOptional="true" DataType="ns=10;i=3012" Name="JobResponseData"/>
<Field IsOptional="true" DataType="ns=10;i=3017" ValueRank="1" Name="PersonnelActuals"/>
<Field IsOptional="true" DataType="ns=10;i=3015" ValueRank="1" Name="EquipmentActuals"/>
<Field IsOptional="true" DataType="ns=10;i=3018" ValueRank="1" Name="PhysicalAssetActuals"/>
<Field IsOptional="true" DataType="ns=10;i=3001" ValueRank="1" Name="MaterialActuals"/>
</Definition>
</UADataType>
Thanks.
Plamen
PS: I am afraid that I commented a closed issue or discussion, so I created her a new one.
_Originally posted by @plamenk in https://github.com/FreeOpcUa/opcua-asyncio/discussions/1293#discussioncomment-7373942_ | It seems that load_data_type_definitions loads only the base UA Data Types under Structure, but not the additionally loaded Data Types from other nodesets. | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1475/comments | 3 | 2023-10-25T19:24:04Z | 2023-10-26T06:47:36Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1475 | 1,962,078,507 | 1,475 |
[
"FreeOpcUa",
"opcua-asyncio"
] |
Hi. I am new to OPC UA and stuck with calling a method with an KeyValuePair argument as input.
I posted the details of my question on
[Stack Overflow]
(https://stackoverflow.com/questions/77338446/call-method-with-keyvaluepair-input-argument)
Can anybody give me a hint? Thanks! | Python OPC UA call method with an KeyValusPaia argument as input | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1474/comments | 8 | 2023-10-22T09:03:43Z | 2023-10-30T11:23:10Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1474 | 1,955,821,719 | 1,474 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi all,
I found at the serverstatus node and its children node.
all the node type are NumericNodeId but other stack such milo and open62541 are FourByteNodeId.
Also it seems the standard opc ua has define as FourByteNodeId.
https://reference.opcfoundation.org/Core/Part6/v105/docs/5.2.2.9#_Ref131423295
Thank you very for your consideration.
I look forward to any response.
here the result from my server.
result of freeopcua device
Node: Node(NumericNodeId(i=2257))
Node id: NumericNodeId(i=2257)
Browse name: QualifiedName(0:StartTime)
Display name: LocalizedText(Encoding:2, Locale:None, Text:StartTime)
Description: LocalizedText(Encoding:0, Locale:None, Text:None)
Value: 2023-10-17 03:10:06.778950
Can we define this all children node of Serverstatus node as Fourbytenodeid?
Python-Version: 3.10
opcua-asyncio Version (e.g. master branch, 0.9): 1.0.4
| Wrong Node type at ServerStatus Node | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1473/comments | 8 | 2023-10-20T12:32:39Z | 2023-10-24T17:18:44Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1473 | 1,954,196,626 | 1,473 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ### Discussed in https://github.com/FreeOpcUa/opcua-asyncio/discussions/1468
<div type='discussions-op-text'>
<sup>Originally posted by **MacherelR** October 16, 2023</sup>
Hello everyone,
I'm currently facing a problem implementing an opc-ua client service in form of a fastAPI app.
In fact, everything is working well to subscribe and unsubscribe to the server nodes, but I can't figure out a way to catch and handle the exceptions coming from the _monitor_server_loop method of asyncua.Client.
# FastAPI app codea
~~~
import asyncio
import json
import logging
import os
import time
# from asyncua import Client
from lysr_opc.CustomClient import AsyncuaClient as Client
from confluent_kafka.admin import AdminClient, NewTopic
from fastapi import FastAPI
from lysr_opc.opcua_browser import OPCUABrowser
from lysr_opc.opcua_subscriber import OPCUASubscriber
from lysr_opc.utils import convert_nodeid_to_string
from lysr_opc.config import OPCUA_SERVER_URL, KAFKA_URL, LOG_LEVEL
from lysr_opc.utils import get_logger
api_logger = get_logger(LOG_LEVEL)
logging.getLogger("asyncua").setLevel(logging.WARNING)
# OPCUA_SERVER_URL = os.environ.get('OPC_SERVER_URL')
# KAFKA_BROKER = os.environ.get('KAFKA_BROKER')
# DEVICE_ID = os.environ.get('DEVICE_ID')
app = FastAPI()
subscription = None
subscribers = {}
client = Client(OPCUA_SERVER_URL)
subscriber = None
def handle_exception(context):
# context["message"] will always be there; but context["exception"] may not
msg = context.get("exception", context["message"])
api_logger.exception(f"!!!!!!!!!!!!!!!!!! Caught exception: {msg}")
@app.on_event("startup")
async def startup_event():
global client, subscriber
try:
await client.connect()
api_logger.info("Client connected !")
except Exception as e:
if isinstance(e, TimeoutError):
api_logger.exception(f"Error : {type(e).__name__}, unable to connect to server, verify address.")
else:
api_logger.exception(f"Error : {type(e).__name__}, {e}")
try:
subscriber = OPCUASubscriber(client)
except Exception as e:
api_logger.exception(f"Error : {type(e).__name__}, {e}")
return {"status": f"Error : {type(e).__name__}, {e}"}
loop = asyncio.get_event_loop()
loop.set_exception_handler(handle_exception)
@app.on_event("shutdown")
async def shutdown_event():
global client, subscriber
await subscriber.kill()
await client.disconnect()
api_logger.info("Client disconnected !")
# Methods used for debug purpose
@app.get("/createTopic/{nodeid}")
async def create_topic(nodeid: str):
# With confluent-kafka
admin_kafka = AdminClient({'bootstrap.servers': KAFKA_URL})
if admin_kafka.list_topics().topics.get(convert_nodeid_to_string(nodeid)) is None:
ret = f"Topic {nodeid} already existing."
api_logger.info(ret)
return ret
new_topic = NewTopic(convert_nodeid_to_string(nodeid), num_partitions=1, replication_factor=1)
fs = admin_kafka.create_topics([new_topic])
ret = ""
for topic, f in fs.items():
try:
f.result() # The result itself is None
ret = f"Topic {topic} created"
api_logger.info(ret)
except Exception as e:
ret = f"Failed to create topic {topic}: {e}"
api_logger.info(ret)
return ret
@app.get("/getRunningThreads")
async def get_running_threads():
import threading
for thread in threading.enumerate():
api_logger.info(f"Thread name: {thread.name} | Thread ID: {thread.ident}")
# return threading.enumerate()
# End of debug methods
@app.get("/browseServer")
async def execute_browse_command():
browser = OPCUABrowser(client)
api_logger.info("Starting to design the browsing tree...")
start = time.time()
tree = await browser.get_tree(["0:Objects"])
end = time.time()
api_logger.info(f"Tree design established in {end - start} seconds !")
browser.export_json(output_file="../tree_light.json")
api_logger.info("Tree design exported !")
return json.dumps(tree, indent=2)
@app.post("/subscribe/{nodeid}")
async def subscribe_to_node(nodeid: str):
global subscriber
try:
status = await subscriber.subscribe_node(nodeid)
except Exception as e:
api_logger.exception(f"Error : {type(e).__name__}, {e}")
return {"status": f"Error : {type(e).__name__}, {e}"}
return status
@app.post("/subscribeMultiple")
async def subscribe_to_multiple_nodes(nodeids: list[str]):
global subscriber
res = await subscriber.subscribe_nodes(nodeids)
return {"status": res}
@app.post("/unsubscribe/{nodeid}")
async def unsubscribe_to_node(nodeid: str):
global subscriber
try:
status = await subscriber.unsubscribe(nodeid)
except Exception as e:
api_logger.exception(f"Error : {type(e).__name__}, {e}")
return {"status": f"Error : {type(e).__name__}, {e}"}
return status
@app.post("/unsubscribeMultiple")
async def unsubscribe_to_multiple_nodes(nodeids: list[str]):
global subscribers
res = await subscriber.unsubscribe_nodes(nodeids)
return {"status": res}
# @app.get("/getStatus")
# async def get_status():
# global subscriber
# return subscriber.get_status()
~~~
--------------------------------------------------------------------------------------
# The OPCUASubscriber.subscribe_node(nodeid) code :
~~~
async def subscribe_node(self, nodeid):
if nodeid in self.subscriptionsStates.keys():
if self.subscriptionsStates[nodeid].status == SubscriptionStatus.SUBSCRIPTION_FAILED:
self.logger.info(f"Subscription for nodeid {nodeid} previously failed, retrying...")
elif self.subscriptionsStates[nodeid].status == SubscriptionStatus.ACTIVE:
self.logger.info(f"Subscription already existing for node {nodeid}")
return self.subscriptionsStates[nodeid]
try:
found_node = self.client.get_node(nodeid=nodeid)
found_node_name = await found_node.read_browse_name()
self.node_map[nodeid] = found_node_name.Name
if self.sub is None:
self.handler = SubHandler(self.node_map, producer=self.producer)
self.sub = await self.client.create_subscription(period=1000,handler=self.handler)
if self.handler is not None:
self.handler.update_node_map(self.node_map)
# self.subs[nodeid] = sub
monitored_item = await self.sub.subscribe_data_change(found_node)
self.monitored_items[nodeid] = monitored_item
self.subscriptionsStates[nodeid] = SubScriptionState(nodeid=nodeid, message="Subscription success", status=SubscriptionStatus.ACTIVE)
except Exception as e:
self.subscriptionsStates[nodeid] = SubScriptionState(nodeid=nodeid, message=f"Error : {type(e).__name__}, {e}", status=SubscriptionStatus.SUBSCRIPTION_FAILED)
self.logger.exception(f"Error : {type(e).__name__}, {e}")
return self.subscriptionsStates[nodeid]
~~~
--------------------------------------------------------------------------------------
I guess the fact that it isn't used inside a "with" statement or an infinite loop is the problem to catch the exceptions launched by an asyncio task inside the client... Has anyone ever faced this problem or has a solution ?
</div> | Handle server monitoring exceptions from client side in as fastAPI app | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1472/comments | 0 | 2023-10-17T06:10:05Z | 2023-10-26T13:44:51Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1472 | 1,946,618,681 | 1,472 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi,
I found some thing in serverstatus node 2256 that StartTime and CurrentTime in the value of serverstatus node are not updating.
But the StartTime Node 2257 and CurrentTime node 2258 work correctly updating.

Python-Version: 3.10
opcua-asyncio Version (e.g. master branch, 0.9): 1.0.4
please advice how to resolve. | StartTime and CurrentTime in ServerStatus node not update | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1469/comments | 4 | 2023-10-16T10:14:03Z | 2023-10-30T10:12:42Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1469 | 1,944,862,310 | 1,469 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I have a program that runs smoothly when it's fully automated.
However when I tried to add a new asyncua unrelated function that just returns some List I get the exception `Connection is closed`.
This function opens a realsense window on which you draw some points and it returns the coordinates of those points.
I didn't know where it came from but it seems after waiting a couple of seconds the server or the client disconnects and then the whole program is dead and I have to relaunch it.
**To Reproduce**<br />
To reproduce this bug it's fairly easy. To send a signal to my server I use this main function :
async def __write_node_value_by_id(self, node_id: str, value) -> bool:
try:
```
# Lire le nœud en utilisant son Node ID
node = self.__client.get_node(node_id)
# Écrire la nouvelle valeur dans le nœud
await node.write_value(value)
print(f"Value {value} written to Node.")
return True
except ua.uaerrors._auto.BadUserAccessDenied:
print(self.__bcolors.FAIL + f"Access denied: Node {node_id} is not writable." + self.__bcolors.ENDC)
return False
except Exception as e:
if "BadTypeMismatch" in str(e):
print(self.__bcolors.FAIL + f"Une erreur s'est produite : {str(e)}. Value to set is {type(value)} and node is {type(await self.__client.get_node(node_id).get_value())}" + self.__bcolors.ENDC)
else:
print(self.__bcolors.FAIL + f"Une erreur s'est produite : {str(e)}" + self.__bcolors.ENDC)
return False
```
Then I call it a bunch of times
```
await self.__write_node_value_by_id(some_address, some_value)
await self.__write_node_value_by_id(some_other_address, some_other_value)
await self.__write_node_value_by_id(some_other__other_address, some_other_other_value)
```
I put a breakpoint on one of them and wait for a 10-15 seconds and then when I release the breakpoint I get the exception `Connection is closed`.
**Expected behavior**<br />
I suspect the problem actually comes from asyncio and not freeopcua but I don't know for sure, I'm not familiar with asyncio.
It's like there's a hidden timeout somewhere ?
Do anyone know where this comes from, I haven't found any occurrence of this particular issue online ?
And if that cannot be avoided, how can I effectively detect it so it reconnects ?
**Version**<br />
Python-Version:3.11<br />
opcua-asyncio Version 1.0.4:
| Connection closes after waiting on breakpoint or other function | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1467/comments | 1 | 2023-10-13T16:05:13Z | 2023-10-14T06:54:13Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1467 | 1,942,222,379 | 1,467 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Typing added to `Node.add_object` in daa74c28033e765d2d56d6a81a995ba246818658 does not include the full typing of `create_object`.
Specifically:
https://github.com/FreeOpcUa/opcua-asyncio/blob/daa74c28033e765d2d56d6a81a995ba246818658/asyncua/common/node.py#L810
Should be the same as:
https://github.com/FreeOpcUa/opcua-asyncio/blob/daa74c28033e765d2d56d6a81a995ba246818658/asyncua/common/manage_nodes.py#L65
This bug is present in [master](https://github.com/FreeOpcUa/opcua-asyncio/blob/ab6d30a9b628553ab461b47ba61b93fe4d6f7871/asyncua/common/node.py#L812) and [v1.0.5a3](https://github.com/FreeOpcUa/opcua-asyncio/blob/6e4a83c9f798c0dd9937cc37ebb27a8ab37d377d/asyncua/common/node.py#L812) | Incorrect typing on `Node.add_object` | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1466/comments | 0 | 2023-10-13T10:47:25Z | 2023-11-13T14:29:30Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1466 | 1,941,710,627 | 1,466 |
[
"FreeOpcUa",
"opcua-asyncio"
] | When checking namespace dependencies, PublicationDate and Version are taken from the NamespacePublicationDate resp. NamespaceVersion instead from the tags with the same names. Is there a reason for that? Normally, they are identical, but with the Robotics nodeset, this interpretation shows up, Refer to https://github.com/OPCFoundation/UA-Nodeset/issues/99#issuecomment-1754419092. | An unusual interpretation of the namespace dependencies | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1464/comments | 0 | 2023-10-10T06:30:53Z | 2023-10-10T06:30:53Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1464 | 1,934,492,348 | 1,464 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hi,
I notice serverstatus node has SecondsTillShutdown and ShutdownReason but their values are null comparing to other opcua stack.
other stack SecondsTillShutdown is 0.
and ShutdownReason "","" .
Currently, I have the issues that the client want to check the health of this serverstatus node. but It is different.
What can we do please?
| SecondsTillShutdown and ShutdownReason null | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1462/comments | 1 | 2023-10-03T09:45:10Z | 2023-10-03T10:50:03Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1462 | 1,923,741,947 | 1,462 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Version**<br />
Python-Version:<br />
opcua-asyncio Version 1.0.4:
**Describe the bug** <br />
I have variables defined in my PLC as `REAL`.
I have no problem writing in `LREAL`s but when I try to write in a `REAL` defined variable I get a mismatch error.
In my code I catch the exception to show the types like that :
```
if "BadTypeMismatch" in str(e):
print(f"An error occurred : {str(e)}. Value to set is {type(value)} and node is {type(await self.__client.get_node(node_id).get_value())}")
```
This results in : `An error occurred : Value to set is <class 'float'> and node is <class 'float'>`.
Also I've just checked I have the same problem with an INT variable.
CodeSys defines `REAL` and `LREAL` as such :
<html>
<body>
<!--StartFragment-->
Data Type | Lower Limit | Upper Limit | Memory
-- | -- | -- | --
REAL | -3.402823e+38 | 3.402823e+38 | 32 Bit
LREAL | -1.7976931348623158e+308 | 1.7976931348623158e+308 | 64 Bit
<!--EndFragment-->
</body>
</html>
So I have tried with `numpy.float32()` but I get an another exception that just returns `'float32'`.
**To Reproduce**<br />
My function looks like that
```
try:
# Lire le nœud en utilisant son Node ID
node = self.__client.get_node("somenodeaddress")
# Écrire la nouvelle valeur dans le nœud
await node.write_value(value)
print(f"Value {value} written to Node {node_id}")
return True
except ua.uaerrors._auto.BadUserAccessDenied:
print(f"Access denied: Node {node_id} is not writable.")
return False
except Exception as e:
if "BadTypeMismatch" in str(e):
print(f"Une erreur s'est produite : {str(e)}. Value to set is {type(value)} and node is {type(await self.__client.get_node(node_id).get_value())}")
else:
print(f"Une erreur s'est produite : {str(e)}")
return False
```
**Expected behavior**<br />
Can anyone tell me if there is a way to write in 32bits nodes ? | Can't write real values | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1455/comments | 2 | 2023-09-29T09:21:36Z | 2023-09-29T10:03:29Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1455 | 1,918,911,496 | 1,455 |
[
"FreeOpcUa",
"opcua-asyncio"
] | **Describe the bug** <br />
I'm connecting to a server using minimal client example. The code has been modified slightly and anonymised. This code works against the minimal server example. When deployed a `RuntimeError: can't start new thread` is raised. This code is deployed as a docker container. The server is from Rockwell. Looking for guidance as I'm quite stuck on this one...
**To Reproduce**<br />
```
import asyncio
import logging
import os
import asyncua
logging.basicConfig()
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.INFO)
async def test_opc():
host = os.environ["OPC_HOST"]
port = os.environ["OPC_PORT"]
username = os.environ["OPC_USERNAME"]
password = os.environ["OPC_PASSWORD"]
url = f"opc.tcp://{host}:{port}/" # no path is configured
client = asyncua.Client(url=url)
client.set_user(username)
client.set_password(password)
await client.connect()
node = client.nodes.server_state
node_value = await node.get_value()
_logger.info(f"Node: {node_value}")
await client.disconnect()
if __name__ == "__main__":
asyncio.run(test_opc())
```
**Expected behavior**<br />
Is able to connect and log server_state information.
**Stacktrace**<br />
```
Traceback (most recent call last):
File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/app/entry_point.py", line 34, in test_opc
await client.connect()
File "/usr/local/lib/python3.11/site-packages/asyncua/client/client.py", line 284, in connect
await self.connect_socket()
File "/usr/local/lib/python3.11/site-packages/asyncua/client/client.py", line 347, in connect_socket
await self.uaclient.connect_socket(self.server_url.hostname, self.server_url.port)
File "/usr/local/lib/python3.11/site-packages/asyncua/client/ua_client.py", line 300, in connect_socket
await asyncio.wait_for(asyncio.get_running_loop().create_connection(self._make_protocol, host, port), self._timeout)
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 479, in wait_for
return fut.result()
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1045, in create_connection
infos = await self._ensure_resolved(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1419, in _ensure_resolved
return await loop.getaddrinfo(host, port, family=family, type=type,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 867, in getaddrinfo
return await self.run_in_executor(
^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 829, in run_in_executor
executor.submit(func, *args), loop=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 176, in submit
self._adjust_thread_count()
File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 199, in _adjust_thread_count
t.start()
File "/usr/local/lib/python3.11/threading.py", line 957, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/app/entry_point.py", line 47, in <module>
asyncio.run(test_opc())
File "/usr/local/lib/python3.11/asyncio/runners.py", line 189, in run
with Runner(debug=debug) as runner:
File "/usr/local/lib/python3.11/asyncio/runners.py", line 63, in __exit__
self.close()
File "/usr/local/lib/python3.11/asyncio/runners.py", line 73, in close
loop.run_until_complete(loop.shutdown_default_executor())
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 571, in shutdown_default_executor
thread.start()
File "/usr/local/lib/python3.11/threading.py", line 957, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread
```
**Version**<br />
Python-Version: 3.11.5 <br />
opcua-asyncio Version (e.g. master branch, 0.9): 1.0.4
docker version: 20.10.8
| Simple client example causes RuntimeError: can't start new thread | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1452/comments | 2 | 2023-09-26T08:02:40Z | 2023-12-21T22:58:20Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1452 | 1,912,935,562 | 1,452 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Hello, I have a problem converting my program from the OPCUA library to the Asyncua library.
My program is designed so that it establishes the connection in one Function and in separate Functions for
Read or Write Data
Is there a way to keep this in this library?
Currently I'm getting this error
**return await future
^^^^^^^^^^^^
asyncio.exceptions.CancelledError**
Current test program for test implementation:
```python
async def asyncconnect(devicename, url, opcname, opcpassword, timeout):
global client
connect = False
absolutpfad = os.getcwd()
if opcname == "" and opcpassword == "":
client = Client(url)
elif opcname != "" and opcpassword != "":
absolutpfad = os.getcwd()
client = Client(url)
client.set_user(opcname)
client.set_password(opcpassword)
devicename2 = devicename
devicename2 = devicename2.replace(":", ".")
await client.set_security_string(
"Basic256Sha256,SignAndEncrypt,./OCV_Data/Certificates/" + devicename2 + ".pem,.\OCV_Data\Certificates\key_" + devicename[
12:17] + ".pem")
client.application_uri = "urn:" + devicename
await client.connect()
async def read(nodeid_string):
global client
node_list = []
for nodeid in nodeid_string:
node_list.append(client.get_node(nodeid))
values = await client.read_values(node_list)
print(values)
nodeid_string=['ns=3;s="USER_OPCUA_OCV_DATA_DB"."CellData"[1]."Celltype"','ns=3;s="USER_OPCUA_OCV_DATA_DB"."CellData"[1]."Partnumber_AI"']
asyncio.run(asyncconnect(devicename, url, opcname, opcpassword, timeout))
asyncio.run(read(nodeid_string))
``` | Possibility Separate Function Blocks for Connect and Read/Write Data | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1451/comments | 0 | 2023-09-22T21:49:07Z | 2023-09-29T08:25:25Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1451 | 1,909,555,571 | 1,451 |
[
"FreeOpcUa",
"opcua-asyncio"
] | Dear community,
this is a copy / extended question from the wrongly created issue in https://github.com/FreeOpcUa/python-opcua/discussions/1525#discussioncomment-6861616. @schroeder- , many thanks for your hint. Indeed, I am using opcua-asyncio,can load many specs based on the included 1.04 spec and run my server, based on the examples you provided.
WOuld you be so kind and provide me with an example how to use the wrapper in order to import the file from https://reference.opcfoundation.org/api/nodesets/2.
Thanks in advance.
Plamen | Using latest http://opcfoundation.org/UA/ nodeset 1.05.02 | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1449/comments | 8 | 2023-09-21T18:21:57Z | 2024-04-16T13:52:53Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1449 | 1,907,527,201 | 1,449 |
[
"FreeOpcUa",
"opcua-asyncio"
] | asyncio became incompatible with cryptography<40.0.0 with this commit: https://github.com/FreeOpcUa/opcua-asyncio/commit/97db2dd541d9c01dd5c4013f2faab059005e81ae
PrivateKeyTypes was added in cryptography 40.0.0 (see [here](https://cryptography.io/en/latest/hazmat/primitives/asymmetric/#cryptography.hazmat.primitives.asymmetric.types.PrivateKeyTypes))
Therefore this version constraint should be specified in install_requires of setup.py. | Specify in install_requires that cryptography>=40.0.0 is required | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1448/comments | 3 | 2023-09-20T08:29:16Z | 2024-01-08T07:37:10Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1448 | 1,904,463,222 | 1,448 |
[
"FreeOpcUa",
"opcua-asyncio"
] | There doesn't seem to be an implementation for http://opcfoundation.org/UA/SecurityPolicy#Aes256_Sha256_RsaPss yet.
I have started to implement one, see below standalone example that dynamically adds the new policy to `security_policies` module:
```python
import time
from asyncua.crypto import security_policies, uacrypto
from asyncua.crypto.security_policies import (
Cryptography,
DecryptorAesCbc,
DecryptorRsa,
EncryptorAesCbc,
EncryptorRsa,
MessageSecurityMode,
SecurityPolicy,
Signer,
SignerHMac256,
Verifier,
VerifierHMac256,
require_cryptography,
)
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
def encrypt_rsa_oaep_sha256(public_key, data):
ciphertext = public_key.encrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None
),
)
return ciphertext
def decrypt_rsa_oaep_sha256(private_key, data):
text = private_key.decrypt(
bytes(data),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None
),
)
return text
def sign_pss_sha256(private_key, data):
return private_key.sign(
data,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA256()), salt_length=32
),
hashes.SHA256(),
)
def verify_pss_sha256(certificate, data, signature):
certificate.public_key().verify(
signature,
data,
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA256()), salt_length=32
),
hashes.SHA256(),
)
class SignerPssSha256(Signer):
def __init__(self, client_pk):
require_cryptography(self)
self.client_pk = client_pk
self.key_size = self.client_pk.key_size // 8
def signature_size(self):
return self.key_size
def signature(self, data):
return sign_pss_sha256(self.client_pk, data)
class VerifierPssSha256(Verifier):
def __init__(self, server_cert):
require_cryptography(self)
self.server_cert = server_cert
self.key_size = self.server_cert.public_key().key_size // 8
def signature_size(self):
return self.key_size
def verify(self, data, signature):
verify_pss_sha256(self.server_cert, data, signature)
class SecurityPolicyAes256Sha256RsaPss(SecurityPolicy):
"""Security policy Aes256_Sha256_RsaPss implementation.
- SymmetricSignatureAlgorithm_HMAC-SHA2-256
https://tools.ietf.org/html/rfc4634
- SymmetricEncryptionAlgorithm_AES256-CBC
http://www.w3.org/2001/04/xmlenc#aes256-cbc
- AsymmetricSignatureAlgorithm_RSA-PSS-SHA2-256
http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
- AsymmetricEncryptionAlgorithm_RSA-OAEP-SHA2-256
http://www.w3.org/2001/04/xmlenc#rsa-oaep
- KeyDerivationAlgorithm_P-SHA2-256
http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk/p_sha256
- CertificateSignatureAlgorithm_RSA-PKCS15-SHA2-256
http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
- Aes256Sha256RsaPss_Limits
-> DerivedSignatureKeyLength: 256 bits
-> MinAsymmetricKeyLength: 2048 bits
-> MaxAsymmetricKeyLength: 4096 bits
-> SecureChannelNonceLength: 32 bytes
"""
URI = "http://opcfoundation.org/UA/SecurityPolicy#Aes256_Sha256_RsaPss"
signature_key_size = 32
symmetric_key_size = 32
secure_channel_nonce_length = 32
AsymmetricEncryptionURI = "http://opcfoundation.org/UA/security/rsa-oaep-sha2-256"
AsymmetricSignatureURI = "http://opcfoundation.org/UA/security/rsa-pss-sha2-256"
@staticmethod
def encrypt_asymmetric(pubkey, data):
return encrypt_rsa_oaep_sha256(pubkey, data)
def __init__(self, peer_cert, host_cert, client_pk, mode, permission_ruleset=None):
require_cryptography(self)
if isinstance(peer_cert, bytes):
peer_cert = uacrypto.x509_from_der(peer_cert)
# even in Sign mode we need to asymmetrically encrypt secrets
# transmitted in OpenSecureChannel. So SignAndEncrypt here
self.asymmetric_cryptography = Cryptography(MessageSecurityMode.SignAndEncrypt)
self.asymmetric_cryptography.Signer = SignerPssSha256(client_pk)
self.asymmetric_cryptography.Verifier = VerifierPssSha256(peer_cert)
self.asymmetric_cryptography.Encryptor = EncryptorRsa(
peer_cert, encrypt_rsa_oaep_sha256, 66
)
self.asymmetric_cryptography.Decryptor = DecryptorRsa(
client_pk, decrypt_rsa_oaep_sha256, 66
)
self.symmetric_cryptography = Cryptography(mode)
self.Mode = mode
self.peer_certificate = uacrypto.der_from_x509(peer_cert)
self.host_certificate = uacrypto.der_from_x509(host_cert)
if permission_ruleset is None:
from asyncua.crypto.permission_rules import SimpleRoleRuleset
permission_ruleset = SimpleRoleRuleset()
self.permissions = permission_ruleset
def make_local_symmetric_key(self, secret, seed):
# specs part 6, 6.7.5
key_sizes = (self.signature_key_size, self.symmetric_key_size, 16)
(sigkey, key, init_vec) = uacrypto.p_sha256(secret, seed, key_sizes)
self.symmetric_cryptography.Signer = SignerHMac256(sigkey)
self.symmetric_cryptography.Encryptor = EncryptorAesCbc(key, init_vec)
def make_remote_symmetric_key(self, secret, seed, lifetime):
# specs part 6, 6.7.5
key_sizes = (self.signature_key_size, self.symmetric_key_size, 16)
(sigkey, key, init_vec) = uacrypto.p_sha256(secret, seed, key_sizes)
if self.symmetric_cryptography.Verifier or self.symmetric_cryptography.Decryptor:
self.symmetric_cryptography.Prev_Verifier = self.symmetric_cryptography.Verifier
self.symmetric_cryptography.Prev_Decryptor = self.symmetric_cryptography.Decryptor
self.symmetric_cryptography.prev_key_expiration = (
self.symmetric_cryptography.key_expiration
)
# lifetime is in ms
self.symmetric_cryptography.key_expiration = time.time() + (lifetime * 0.001)
self.symmetric_cryptography.Verifier = VerifierHMac256(sigkey)
self.symmetric_cryptography.Decryptor = DecryptorAesCbc(key, init_vec)
def define_policy_aes256_sha256_rsa_pss():
setattr(
security_policies, "SecurityPolicyAes256_Sha256_RsaPss", SecurityPolicyAes256Sha256RsaPss
)
```
Let me know your thoughts. I can open a PR and integrate the code to the existing base if you feel it's worth it. | support for Aes256Sha256RsaPss security policy | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1446/comments | 3 | 2023-09-19T10:16:08Z | 2023-09-29T10:59:01Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1446 | 1,902,656,969 | 1,446 |
[
"FreeOpcUa",
"opcua-asyncio"
] | I tried to use your example but it crashes at my S7-1500 UDT
```
client = Client(url=config['opc']['server'])
client.secure_channel_timeout = config['opc']['timeout']
client.session_timeout = config['opc']['timeout']
await client.connect()
root = client.get_root_node()
print("Objects node is: ", root)
# Node objects have methods to read and write node attributes as well as browse or populate address space
print(f"Children of root are:")
for c in await root.get_children():
print(f'\t{c} {await c.read_display_name()} {await c.read_browse_name()}')
namespaces = await client.get_namespace_array()
for ns in namespaces:
print( f'Index of {ns}: {await client.get_namespace_index(ns)}' )
print("Register namespace")
idx = await client.register_namespace(namespaces[3])
print("idx", idx)
path = f'ns=3;s="S360 Main Data DB"."Offline Nest"[0]."PDR"."LPC"'
print(f'Create node for {path}')
node = client.get_node(path)
dt_id = await node.read_data_type()
dt = client.get_node(dt_id)
dtd = await dt.read_data_type_definition()
value = await node.read_value()
print("*"*50)
print(f"Node:{node}")
print(f'Value:{value}')
print(f'Datatype:{dt}')
print(f'Datatypedefinition:{dtd}')
print()
print()
print("*"*50)
print("Load datatype defintions")
await client.load_data_type_definitions()
```
Log: [opc.log](https://github.com/FreeOpcUa/opcua-asyncio/files/12611113/opc.log)
That is what Prosys is showing:



I am not quiet good with OPC-UA yet, so I don't know really what I could do to help you to recreate it but let me know and I will try to give you all data you need asap
Also: Can I only create definitions for a subset?
I checked #234 and tried this:
```
node = client.get_node(path)
dt_id = await node.read_data_type()
dt = client.get_node(dt_id)
dtd = await dt.read_data_type_definition()
value = await node.read_value()
```
But I did not understand how to access the data in a convenient pythonic way | load_data_type_definitions crashes on S7-1500 UDT | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1441/comments | 11 | 2023-09-14T16:18:52Z | 2023-10-02T08:25:06Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1441 | 1,896,911,641 | 1,441 |
[
"FreeOpcUa",
"opcua-asyncio"
] | ### Discussed in https://github.com/FreeOpcUa/opcua-asyncio/discussions/1434
<div type='discussions-op-text'>
<sup>Originally posted by **dostojewskyi** September 11, 2023</sup>
Hi all,
I try to read/write Nodes from an OPCua Server which only has ByteString NodeIDs.
Problem:
opcua-asyncio directly encodes ByteString to hex. unfortunately there are OPCua Server out there having the ByteString on base64 which results in a different hex encoding.
I don't know if server exist using different base, but at least there are Servers out there having it.
So the module should include a check what base the bytestring is and if 64 is True, it directly decode via ```base64.b64decode(b'<bytestring>')```
ty | read/write Bytestring NodesIds | https://api.github.com/repos/FreeOpcUa/opcua-asyncio/issues/1436/comments | 1 | 2023-09-11T17:39:03Z | 2023-09-12T06:18:13Z | https://github.com/FreeOpcUa/opcua-asyncio/issues/1436 | 1,890,968,290 | 1,436 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.