openopc2
openopc2 copied to clipboard
Bug: OpcDaClient problems with Multithreading
I have discovered that if you try to connect the OpcDaClient
on a thread, it throws an Exception
. Please see the below code snippet (done with MatrikonOPC Simulation Server):
from threading import Thread
from openopc2.config import OpenOpcConfig
from openopc2.da_client import OpcDaClient
MATRIKON_SIMULATION_SERVER = "Matrikon.OPC.Simulation"
open_opc_config = OpenOpcConfig()
open_opc_config.OPC_SERVER = MATRIKON_SIMULATION_SERVER
# 1. Instantiate client in main thread
opc = OpcDaClient(open_opc_config=open_opc_config)
# 2. Connect client in another thread (doesn't work)
thread = Thread(
target=opc.connect, kwargs={"opc_server": MATRIKON_SIMULATION_SERVER}
)
thread.start()
thread.join()
# 2. Connect client in the main thread (works)
opc.connect(opc_server=MATRIKON_SIMULATION_SERVER)
# 3. Try reading tag
result = opc.read("Random.Boolean")
_ = 0 # Debug here
If you use the main thread the whole time, this works.
If you call OpcDaClient.connect
on a thread, you get this Exception
when OpcCom.connect
calls self.opc_client.Connect
:
pywintypes.com_error(-2147352567,
'Exception occurred.',
(0, None, None, None, 0, -2147467259),
None)
Notable, OpenOPC (not OpenOPC 2) doesn't have this error:
from threading import Thread
import OpenOPC
MATRIKON_SIMULATION_SERVER = "Matrikon.OPC.Simulation"
# 1. Instantiate client in main thread
opc = OpenOPC.open_client("localhost") # Open mode
# 2. Connect client in another thread (works)
thread = Thread(
target=opc.connect, kwargs={"opc_server": MATRIKON_SIMULATION_SERVER}
)
thread.start()
thread.join()
# 3. Try reading tag
result = opc.read("Random.Boolean")
_ = 0 # Debug here
This is a bummer for me, because I use a software framework where all device connections are all made asynchronously (on a thread). I would like to use OpenOPC2, but this is an issue.