FreeOpcUa / opcua-asyncio

OPC UA library for python >= 3.7
GNU Lesser General Public License v3.0
1.04k stars 346 forks source link

Connect to Kepware KEPServerEX 6.15 via asyncua #1583

Closed shamyjun22 closed 4 months ago

shamyjun22 commented 4 months ago

Hi there, I am running an asyncua 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. However, I wanted to implement it asynchronously.

Using 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: 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

schroeder- commented 4 months ago

With the following line you do connect to the server. async with Client("opc.tcp://192.168.100.139:49320") as client:

Rewrite the code like this:

async def main():
      # configure client
      client = Client("opc.tcp://192.168.100.139:49320")
      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"
      # connect to the server
      async with client:
          # connected
           .....
shamyjun22 commented 4 months ago

Hi @schroeder, thanks.